Support forced SSL-verified connection with given CA certificate

This commit is contained in:
Maarten Bezemer 2016-11-22 16:18:45 +01:00 committed by Toshio Kuratomi
parent 09ceaafd42
commit 1f1379ea61
3 changed files with 101 additions and 10 deletions

View file

@ -89,10 +89,25 @@ options:
required: false required: false
default: present default: present
choices: [ "present", "absent" ] choices: [ "present", "absent" ]
ssl_mode:
description:
- Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server.
- See https://www.postgresql.org/docs/current/static/libpq-ssl.html for more information on the modes.
required: false
default: disable
choices: [disable, allow, prefer, require, verify-ca, verify-full]
version_added: '2.3'
ssl_rootcert:
description:
- Specifies the name of a file containing SSL certificate authority (CA) certificate(s). If the file exists, the server's certificate will be verified to be signed by one of these authorities.
required: false
default: null
version_added: '2.3'
notes: notes:
- The default authentication assumes that you are either logging in as or sudo'ing to the C(postgres) account on the host. - The default authentication assumes that you are either logging in as or sudo'ing to the C(postgres) account on the host.
- This module uses I(psycopg2), a Python PostgreSQL database adapter. You must ensure that psycopg2 is installed on - This module uses I(psycopg2), a Python PostgreSQL database adapter. You must ensure that psycopg2 is installed on
the host before using this module. If the remote host is the PostgreSQL server (which is the default case), then PostgreSQL must also be installed on the remote host. For Ubuntu-based systems, install the C(postgresql), C(libpq-dev), and C(python-psycopg2) packages on the remote host before using this module. the host before using this module. If the remote host is the PostgreSQL server (which is the default case), then PostgreSQL must also be installed on the remote host. For Ubuntu-based systems, install the C(postgresql), C(libpq-dev), and C(python-psycopg2) packages on the remote host before using this module.
- The ssl_rootcert parameter requires at least Postgres version 8.4 and I(psycopg2) version 2.4.3.
requirements: [ psycopg2 ] requirements: [ psycopg2 ]
author: "Ansible Core Team" author: "Ansible Core Team"
''' '''
@ -242,6 +257,8 @@ def main():
lc_collate=dict(default=""), lc_collate=dict(default=""),
lc_ctype=dict(default=""), lc_ctype=dict(default=""),
state=dict(default="present", choices=["absent", "present"]), state=dict(default="present", choices=["absent", "present"]),
ssl_mode=dict(default="disable", choices=['disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full']),
ssl_rootcert=dict(default=None),
), ),
supports_check_mode = True supports_check_mode = True
) )
@ -257,6 +274,7 @@ def main():
lc_collate = module.params["lc_collate"] lc_collate = module.params["lc_collate"]
lc_ctype = module.params["lc_ctype"] lc_ctype = module.params["lc_ctype"]
state = module.params["state"] state = module.params["state"]
sslrootcert = module.params["ssl_rootcert"]
changed = False changed = False
# To use defaults values, keyword arguments must be absent, so # To use defaults values, keyword arguments must be absent, so
@ -266,16 +284,21 @@ def main():
"login_host":"host", "login_host":"host",
"login_user":"user", "login_user":"user",
"login_password":"password", "login_password":"password",
"port":"port" "port":"port",
"ssl_mode":"sslmode",
"ssl_rootcert":"sslrootcert"
} }
kw = dict( (params_map[k], v) for (k, v) in iteritems(module.params) kw = dict( (params_map[k], v) for (k, v) in iteritems(module.params)
if k in params_map and v != '' ) if k in params_map and v != '' and v is not None)
# If a login_unix_socket is specified, incorporate it here. # If a login_unix_socket is specified, incorporate it here.
is_localhost = "host" not in kw or kw["host"] == "" or kw["host"] == "localhost" is_localhost = "host" not in kw or kw["host"] == "" or kw["host"] == "localhost"
if is_localhost and module.params["login_unix_socket"] != "": if is_localhost and module.params["login_unix_socket"] != "":
kw["host"] = module.params["login_unix_socket"] kw["host"] = module.params["login_unix_socket"]
if psycopg2.__version__ < '2.4.3' and sslrootcert is not None:
module.fail_json(msg='psycopg2 must be at least 2.4.3 in order to user the ssl_rootcert parameter')
try: try:
db_connection = psycopg2.connect(database="postgres", **kw) db_connection = psycopg2.connect(database="postgres", **kw)
# Enable autocommit so we can create databases # Enable autocommit so we can create databases
@ -287,6 +310,13 @@ def main():
.ISOLATION_LEVEL_AUTOCOMMIT) .ISOLATION_LEVEL_AUTOCOMMIT)
cursor = db_connection.cursor( cursor = db_connection.cursor(
cursor_factory=psycopg2.extras.DictCursor) cursor_factory=psycopg2.extras.DictCursor)
except TypeError:
e = get_exception()
if 'sslrootcert' in e.args[0]:
module.fail_json(msg='Postgresql server must be at least version 8.4 to support sslrootcert')
module.fail_json(msg="unable to connect to database: %s" % e)
except Exception: except Exception:
e = get_exception() e = get_exception()
module.fail_json(msg="unable to connect to database: %s" % e) module.fail_json(msg="unable to connect to database: %s" % e)
@ -318,7 +348,7 @@ def main():
e = get_exception() e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
except SystemExit: except SystemExit:
# Avoid catching this on Python 2.4 # Avoid catching this on Python 2.4
raise raise
except Exception: except Exception:
e = get_exception() e = get_exception()

View file

@ -120,6 +120,20 @@ options:
- 'Alias: I(login_password))' - 'Alias: I(login_password))'
default: null default: null
required: no required: no
ssl_mode:
description:
- Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server.
- See https://www.postgresql.org/docs/current/static/libpq-ssl.html for more information on the modes.
required: false
default: disable
choices: [disable, allow, prefer, require, verify-ca, verify-full]
version_added: '2.3'
ssl_rootcert:
description:
- Specifies the name of a file containing SSL certificate authority (CA) certificate(s). If the file exists, the server's certificate will be verified to be signed by one of these authorities.
required: false
default: null
version_added: '2.3'
notes: notes:
- Default authentication assumes that postgresql_privs is run by the - Default authentication assumes that postgresql_privs is run by the
C(postgres) user on the remote host. (Ansible's C(user) or C(sudo-user)). C(postgres) user on the remote host. (Ansible's C(user) or C(sudo-user)).
@ -139,6 +153,7 @@ notes:
specified via I(login). If R has been granted the same privileges by specified via I(login). If R has been granted the same privileges by
another user also, R can still access database objects via these privileges. another user also, R can still access database objects via these privileges.
- When revoking privileges, C(RESTRICT) is assumed (see PostgreSQL docs). - When revoking privileges, C(RESTRICT) is assumed (see PostgreSQL docs).
- The ssl_rootcert parameter requires at least Postgres version 8.4 and I(psycopg2) version 2.4.3.
requirements: [psycopg2] requirements: [psycopg2]
author: "Bernhard Weitzhofer (@b6d)" author: "Bernhard Weitzhofer (@b6d)"
""" """
@ -274,17 +289,31 @@ class Connection(object):
"password":"password", "password":"password",
"port":"port", "port":"port",
"database": "database", "database": "database",
"ssl_mode":"sslmode",
"ssl_rootcert":"sslrootcert"
} }
kw = dict( (params_map[k], getattr(params, k)) for k in params_map kw = dict( (params_map[k], getattr(params, k)) for k in params_map
if getattr(params, k) != '' ) if getattr(params, k) != '' and getattr(params, k) is not None )
# If a unix_socket is specified, incorporate it here. # If a unix_socket is specified, incorporate it here.
is_localhost = "host" not in kw or kw["host"] == "" or kw["host"] == "localhost" is_localhost = "host" not in kw or kw["host"] == "" or kw["host"] == "localhost"
if is_localhost and params.unix_socket != "": if is_localhost and params.unix_socket != "":
kw["host"] = params.unix_socket kw["host"] = params.unix_socket
self.connection = psycopg2.connect(**kw) sslrootcert = params.ssl_rootcert
self.cursor = self.connection.cursor() if psycopg2.__version__ < '2.4.3' and sslrootcert is not None:
module.fail_json(msg='psycopg2 must be at least 2.4.3 in order to user the ssl_rootcert parameter')
try:
self.connection = psycopg2.connect(**kw)
self.cursor = self.connection.cursor()
except TypeError:
e = get_exception()
if 'sslrootcert' in e.args[0]:
module.fail_json(msg='Postgresql server must be at least version 8.4 to support sslrootcert')
module.fail_json(msg="unable to connect to database: %s" % e)
def commit(self): def commit(self):
@ -541,7 +570,9 @@ def main():
port=dict(type='int', default=5432), port=dict(type='int', default=5432),
unix_socket=dict(default='', aliases=['login_unix_socket']), unix_socket=dict(default='', aliases=['login_unix_socket']),
login=dict(default='postgres', aliases=['login_user']), login=dict(default='postgres', aliases=['login_user']),
password=dict(default='', aliases=['login_password'], no_log=True) password=dict(default='', aliases=['login_password'], no_log=True),
ssl_mode=dict(default="disable", choices=['disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full']),
ssl_rootcert=dict(default=None)
), ),
supports_check_mode = True supports_check_mode = True
) )

View file

@ -124,6 +124,20 @@ options:
default: 'no' default: 'no'
choices: [ "yes", "no" ] choices: [ "yes", "no" ]
version_added: '2.0' version_added: '2.0'
ssl_mode:
description:
- Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server.
- See https://www.postgresql.org/docs/current/static/libpq-ssl.html for more information on the modes.
required: false
default: disable
choices: [disable, allow, prefer, require, verify-ca, verify-full]
version_added: '2.3'
ssl_rootcert:
description:
- Specifies the name of a file containing SSL certificate authority (CA) certificate(s). If the file exists, the server's certificate will be verified to be signed by one of these authorities.
required: false
default: null
version_added: '2.3'
notes: notes:
- The default authentication assumes that you are either logging in as or - The default authentication assumes that you are either logging in as or
sudo'ing to the postgres account on the host. sudo'ing to the postgres account on the host.
@ -140,6 +154,7 @@ notes:
- If you specify PUBLIC as the user, then the privilege changes will apply - If you specify PUBLIC as the user, then the privilege changes will apply
to all users. You may not specify password or role_attr_flags when the to all users. You may not specify password or role_attr_flags when the
PUBLIC user is specified. PUBLIC user is specified.
- The ssl_rootcert parameter requires at least Postgres version 8.4 and I(psycopg2) version 2.4.3.
requirements: [ psycopg2 ] requirements: [ psycopg2 ]
author: "Ansible Core Team" author: "Ansible Core Team"
''' '''
@ -580,7 +595,9 @@ def main():
role_attr_flags=dict(default=''), role_attr_flags=dict(default=''),
encrypted=dict(type='bool', default='no'), encrypted=dict(type='bool', default='no'),
no_password_changes=dict(type='bool', default='no'), no_password_changes=dict(type='bool', default='no'),
expires=dict(default=None) expires=dict(default=None),
ssl_mode=dict(default='disable', choices=['disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full']),
ssl_rootcert=dict(default=None)
), ),
supports_check_mode = True supports_check_mode = True
) )
@ -605,6 +622,7 @@ def main():
else: else:
encrypted = "UNENCRYPTED" encrypted = "UNENCRYPTED"
expires = module.params["expires"] expires = module.params["expires"]
sslrootcert = module.params["ssl_rootcert"]
if not postgresqldb_found: if not postgresqldb_found:
module.fail_json(msg="the python psycopg2 module is required") module.fail_json(msg="the python psycopg2 module is required")
@ -617,19 +635,31 @@ def main():
"login_user":"user", "login_user":"user",
"login_password":"password", "login_password":"password",
"port":"port", "port":"port",
"db":"database" "db":"database",
"ssl_mode":"sslmode",
"ssl_rootcert":"sslrootcert"
} }
kw = dict( (params_map[k], v) for (k, v) in iteritems(module.params) kw = dict( (params_map[k], v) for (k, v) in iteritems(module.params)
if k in params_map and v != "" ) if k in params_map and v != "" and v is not None)
# If a login_unix_socket is specified, incorporate it here. # If a login_unix_socket is specified, incorporate it here.
is_localhost = "host" not in kw or kw["host"] == "" or kw["host"] == "localhost" is_localhost = "host" not in kw or kw["host"] == "" or kw["host"] == "localhost"
if is_localhost and module.params["login_unix_socket"] != "": if is_localhost and module.params["login_unix_socket"] != "":
kw["host"] = module.params["login_unix_socket"] kw["host"] = module.params["login_unix_socket"]
if psycopg2.__version__ < '2.4.3' and sslrootcert is not None:
module.fail_json(msg='psycopg2 must be at least 2.4.3 in order to user the ssl_rootcert parameter')
try: try:
db_connection = psycopg2.connect(**kw) db_connection = psycopg2.connect(**kw)
cursor = db_connection.cursor(cursor_factory=psycopg2.extras.DictCursor) cursor = db_connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
except TypeError:
e = get_exception()
if 'sslrootcert' in e.args[0]:
module.fail_json(msg='Postgresql server must be at least version 8.4 to support sslrootcert')
module.fail_json(msg="unable to connect to database: %s" % e)
except Exception: except Exception:
e = get_exception() e = get_exception()
module.fail_json(msg="unable to connect to database: %s" % e) module.fail_json(msg="unable to connect to database: %s" % e)