From 770680180ba2950b832858693d9202101a56cb17 Mon Sep 17 00:00:00 2001 From: Bernhard Weitzhofer Date: Sun, 7 Apr 2013 23:07:58 +0200 Subject: [PATCH] Use psycopg2's string handling to escape password string This allows the password to contain single quotes and should make it safe to use randomly generated passwords (provided passwords can be represented in the connection encoding). --- library/postgresql_user | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/library/postgresql_user b/library/postgresql_user index 597be84af34..ad5858f95ac 100644 --- a/library/postgresql_user +++ b/library/postgresql_user @@ -142,8 +142,10 @@ def user_exists(cursor, user): def user_add(cursor, user, password, role_attr_flags): """Create a new database user (role).""" - query = "CREATE USER \"%(user)s\" with PASSWORD '%(password)s' %(role_attr_flags)s" - cursor.execute(query % {"user": user, "password": password, "role_attr_flags": role_attr_flags}) + query = 'CREATE USER "%(user)s" WITH PASSWORD %%(password)s %(role_attr_flags)s' % { + "user": user, "role_attr_flags": role_attr_flags + } + cursor.execute(query, {"password": password}) return True def user_alter(cursor, user, password, role_attr_flags): @@ -168,8 +170,10 @@ def user_alter(cursor, user, password, role_attr_flags): if password is not None: # Update the role attributes, including password. - alter = "ALTER USER \"%(user)s\" WITH PASSWORD '%(password)s' %(role_attr_flags)s" - cursor.execute(alter % {"user": user, "password": password, "role_attr_flags": role_attr_flags}) + alter = 'ALTER USER "%(user)s" WITH PASSWORD %%(password)s %(role_attr_flags)s' % { + "user": user, "role_attr_flags": role_attr_flags + } + cursor.execute(alter, {"password": password}) else: # Update the role attributes, excluding password. alter = "ALTER USER \"%(user)s\" WITH %(role_attr_flags)s"