From 6a2cc91b62f227ca71d759654ed34c138d236800 Mon Sep 17 00:00:00 2001 From: deva Date: Tue, 19 Aug 2008 07:16:05 +0000 Subject: Fixed SQL injection (escaping of \', \0 and \). --- server/src/database.cc | 39 ++++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) (limited to 'server/src') diff --git a/server/src/database.cc b/server/src/database.cc index 96aa697..d5221f4 100644 --- a/server/src/database.cc +++ b/server/src/database.cc @@ -28,6 +28,30 @@ #include +std::string protect(std::string in) +{ + std::string out; + + for(size_t i = 0; i < in.size(); i++) { + switch(in[i]) { + case '\'': + case '\\': + out.append(2, in[i]); + break; + + case '\0': + out.append(1, '0'); + break; + + default: + out.append(1, in[i]); + break; + } + } + + return out; +} + Database::Database(std::string hostname, std::string user, std::string password) #ifndef WITHOUT_DB : c("host=" + hostname + " user=" + user + " password=" + password + " dbname=pracro") @@ -67,7 +91,8 @@ void Database::commit(std::string user, std::string ts = "INSERT INTO transactions" - " VALUES('"+cpr+"', '"+macro+"', '"+version+"', '"+timestamp.str()+"', '"+user+"')"; + " VALUES('"+protect(cpr)+"', '"+protect(macro)+"', '"+protect(version)+ + "', '"+protect(timestamp.str())+"', '"+protect(user)+"')"; std::stringstream oid; @@ -87,7 +112,7 @@ void Database::commit(std::string user, std::string fs = "INSERT INTO fields" - " VALUES('"+oid.str()+"', '"+i->first+"', '"+i->second+"')"; + " VALUES('"+protect(oid.str())+"', '"+protect(i->first)+"', '"+protect(i->second)+"')"; #ifndef WITHOUT_DB W.exec(fs); @@ -130,15 +155,15 @@ Values Database::getValues(std::string cpr, std::stringstream query; query << "SELECT fields.name, fields.value, transactions.timestamp"; query << " FROM fields, transactions"; - query << " WHERE transactions.cpr = '" << cpr << "'"; + query << " WHERE transactions.cpr = '" << protect(cpr) << "'"; query << " AND transactions.oid = fields.transaction"; query << " AND transactions.timestamp >= " << oldest; std::vector< std::string >::iterator i = fields.begin(); bool first = true; while(i != fields.end()) { - if(first) query << " AND ( fields.name = '" << (*i) << "'"; - else query << " OR fields.name = '" << (*i) << "'"; + if(first) query << " AND ( fields.name = '" << protect(*i) << "'"; + else query << " OR fields.name = '" << protect(*i) << "'"; first = false; i++; } @@ -185,8 +210,8 @@ bool Database::checkMacro(std::string cpr, std::stringstream query; query << "SELECT oid"; query << " FROM transactions"; - query << " WHERE cpr = '" << cpr << "'"; - query << " AND macro = '" << macro << "'"; + query << " WHERE cpr = '" << protect(cpr) << "'"; + query << " AND macro = '" << protect(macro) << "'"; query << " AND timestamp >= " << oldest; query << " ORDER BY timestamp"; -- cgit v1.2.3