Escaping Strings SQLite

From SA-MP Wiki

Jump to: navigation, search

Image:50px-Ambox_outdated_serious.png This article is outdated. It may use methods or functions which no longer exist or which are deemed obsolete by the community. Caution is advised. This functionality has been replaced with the format specifier %q as of SA-MP 0.3.7 R2.


Description:

Escape a string to prevent SQL injection (for SQLite).


SQLite obviously uses SQL (Structured Query Language), which can be exploited with SQL Injection (see here).

Fortunately, this exploit can be patched by escaping strings. This is a common issue in MySQL, however most of the released MySQL plugins include a function to automatically escape strings. In SQLite, there is no native function to do so, however Y_LESS released some code to patch this exploit (which has been included below).

SQL queries are mainly affected by user inputs, where a user gets to define parts of a query, where they can inject malicious code into the query, resulting in SQL injection. Simply patch any user inputs with the function below.

#define MAX_INI_ENTRY_TEXT 80
 
stock DB_Escape(text[])
{
	new
		ret[MAX_INI_ENTRY_TEXT * 2],
		ch,
		i,
		j;
	while ((ch = text[i++]) && j < sizeof (ret))
	{
		if (ch == '\'')
		{
			if (j < sizeof (ret) - 2)
			{
				ret[j++] = '\'';
				ret[j++] = '\'';
			}
		}
		else if (j < sizeof (ret))
		{
			ret[j++] = ch;
		}
		else
		{
			j++;
		}
	}
	ret[sizeof (ret) - 1] = '\0';
	return ret;
}

Related Functions

The following functions may be useful, as they are related to this function in one way or another.

Personal tools