Tag Archives: mysqldb

A quick Python MySQLdb fix…

Okay, so I enjoy writing code in python a lot more than I ever would in php.  So when I came across the MySQLdb module, I was thrilled.  Now I could do anything that php could do and more, in my opinion.  Well, except php’s python comes with all sort of proctections such as mysql_real_escape()… hmm, what to do now.  Well, better come to a solution.  Here’s that solution in all of it’s glory:

#!/usr/bin/env python
## FILENAME: sql.py

def clean(unclean):
	cleaned = ""
	badchrs = "\\\/\"\'"
	temp    = ""
	for ch in unclean:
		temp = ch
		if temp in badchrs:
			temp = "\\" + temp
		cleaned += temp
	return cleaned

As for usage, just place this with your script (most likely in cgi-bin) and import it:

import sql
name    = sql.clean(form.getvalue('name'))

Obviously, there can be more escapes added but for the initial framework, this is the start of a simple fix! for discussion, what vulnerabilities are in this code? What are other ways to extend the MySQLdb module? Please comment…