Skip to content

Commit 7de971e

Browse files
committed
Add SSL connection related error logs
1 parent 60fedc9 commit 7de971e

File tree

14 files changed

+87
-34
lines changed

14 files changed

+87
-34
lines changed

SecretsManagerMongoDBRotationMultiUser/lambda_function.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
22
# SPDX-License-Identifier: MIT-0
33

4+
import re
45
import boto3
56
import json
67
import logging
@@ -380,8 +381,13 @@ def connect_and_authenticate(secret_dict, port, dbname, use_ssl):
380381
client = MongoClient(host=secret_dict['host'], port=port, connectTimeoutMS=5000, serverSelectionTimeoutMS=5000, ssl=use_ssl)
381382
db = client[dbname]
382383
db.authenticate(secret_dict['username'], secret_dict['password'])
384+
logger.info("Successfully established %s connection as user '%s' with host: '%s'" % ("SSL/TLS" if use_ssl else "non SSL/TLS", secret_dict['username'], secret_dict['host']))
383385
return db
384-
except errors.PyMongoError:
386+
except errors.PyMongoError as e:
387+
if 'SSL handshake failed' in e.args[0]:
388+
logger.error("Unable to establish SSL/TLS handshake, check that SSL/TLS is enabled on the host: %s" % secret_dict['host'])
389+
elif re.search("hostname '.+' doesn't match", e.args[0]):
390+
logger.error("Hostname verification failed when estlablishing SSL/TLS Handshake with host: %s" % secret_dict['host'])
385391
return None
386392

387393

SecretsManagerMongoDBRotationSingleUser/lambda_function.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
22
# SPDX-License-Identifier: MIT-0
33

4+
import re
45
import boto3
56
import json
67
import logging
@@ -374,8 +375,13 @@ def connect_and_authenticate(secret_dict, port, dbname, use_ssl):
374375
client = MongoClient(host=secret_dict['host'], port=port, connectTimeoutMS=5000, serverSelectionTimeoutMS=5000, ssl=use_ssl)
375376
db = client[dbname]
376377
db.authenticate(secret_dict['username'], secret_dict['password'])
378+
logger.info("Successfully established %s connection as user '%s' with host: '%s'" % ("SSL/TLS" if use_ssl else "non SSL/TLS", secret_dict['username'], secret_dict['host']))
377379
return db
378-
except errors.PyMongoError:
380+
except errors.PyMongoError as e:
381+
if 'SSL handshake failed' in e.args[0]:
382+
logger.error("Unable to establish SSL/TLS handshake, check that SSL/TLS is enabled on the host: %s" % secret_dict['host'])
383+
elif re.search("hostname '.+' doesn't match", e.args[0]):
384+
logger.error("Hostname verification failed when estlablishing SSL/TLS Handshake with host: %s" % secret_dict['host'])
379385
return None
380386

381387

SecretsManagerRDSMariaDBRotationMultiUser/lambda_function.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -396,8 +396,11 @@ def connect_and_authenticate(secret_dict, port, dbname, use_ssl):
396396
try:
397397
# Checks hostname and verifies server certificate implictly when 'ca' key is in 'ssl' dictionary
398398
conn = pymysql.connect(secret_dict['host'], user=secret_dict['username'], passwd=secret_dict['password'], port=port, db=dbname, connect_timeout=5, ssl=ssl)
399+
logger.info("Successfully established %s connection as user '%s' with host: '%s'" % ("SSL/TLS" if use_ssl else "non SSL/TLS", secret_dict['username'], secret_dict['host']))
399400
return conn
400-
except pymysql.OperationalError:
401+
except pymysql.OperationalError as e:
402+
if 'certificate verify failed: IP address mismatch' in e.args[1]:
403+
logger.error("Hostname verification failed when estlablishing SSL/TLS Handshake with host: %s" % secret_dict['host'])
401404
return None
402405

403406

@@ -496,7 +499,7 @@ def is_rds_replica_database(replica_dict, master_dict):
496499
try:
497500
describe_response = rds_client.describe_db_instances(DBInstanceIdentifier=replica_instance_id)
498501
except Exception as err:
499-
logger.warn("Encountered error while verifying rds replica status: %s" % err)
502+
logger.warning("Encountered error while verifying rds replica status: %s" % err)
500503
return False
501504
instances = describe_response['DBInstances']
502505

SecretsManagerRDSMariaDBRotationSingleUser/lambda_function.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -373,8 +373,11 @@ def connect_and_authenticate(secret_dict, port, dbname, use_ssl):
373373
try:
374374
# Checks hostname and verifies server certificate implictly when 'ca' key is in 'ssl' dictionary
375375
conn = pymysql.connect(secret_dict['host'], user=secret_dict['username'], passwd=secret_dict['password'], port=port, db=dbname, connect_timeout=5, ssl=ssl)
376+
logger.info("Successfully established %s connection as user '%s' with host: '%s'" % ("SSL/TLS" if use_ssl else "non SSL/TLS", secret_dict['username'], secret_dict['host']))
376377
return conn
377-
except pymysql.OperationalError:
378+
except pymysql.OperationalError as e:
379+
if 'certificate verify failed: IP address mismatch' in e.args[1]:
380+
logger.error("Hostname verification failed when estlablishing SSL/TLS Handshake with host: %s" % secret_dict['host'])
378381
return None
379382

380383

SecretsManagerRDSMySQLRotationMultiUser/lambda_function.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -408,8 +408,11 @@ def connect_and_authenticate(secret_dict, port, dbname, use_ssl):
408408
try:
409409
# Checks hostname and verifies server certificate implictly when 'ca' key is in 'ssl' dictionary
410410
conn = pymysql.connect(secret_dict['host'], user=secret_dict['username'], passwd=secret_dict['password'], port=port, db=dbname, connect_timeout=5, ssl=ssl)
411+
logger.info("Successfully established %s connection as user '%s' with host: '%s'" % ("SSL/TLS" if use_ssl else "non SSL/TLS", secret_dict['username'], secret_dict['host']))
411412
return conn
412-
except pymysql.OperationalError:
413+
except pymysql.OperationalError as e:
414+
if 'certificate verify failed: IP address mismatch' in e.args[1]:
415+
logger.error("Hostname verification failed when estlablishing SSL/TLS Handshake with host: %s" % secret_dict['host'])
413416
return None
414417

415418

@@ -546,7 +549,7 @@ def is_rds_replica_database(replica_dict, master_dict):
546549
try:
547550
describe_response = rds_client.describe_db_instances(DBInstanceIdentifier=replica_instance_id)
548551
except Exception as err:
549-
logger.warn("Encountered error while verifying rds replica status: %s" % err)
552+
logger.warning("Encountered error while verifying rds replica status: %s" % err)
550553
return False
551554
instances = describe_response['DBInstances']
552555

SecretsManagerRDSMySQLRotationSingleUser/lambda_function.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -376,8 +376,11 @@ def connect_and_authenticate(secret_dict, port, dbname, use_ssl):
376376
try:
377377
# Checks hostname and verifies server certificate implictly when 'ca' key is in 'ssl' dictionary
378378
conn = pymysql.connect(secret_dict['host'], user=secret_dict['username'], passwd=secret_dict['password'], port=port, db=dbname, connect_timeout=5, ssl=ssl)
379+
logger.info("Successfully established %s connection as user '%s' with host: '%s'" % ("SSL/TLS" if use_ssl else "non SSL/TLS", secret_dict['username'], secret_dict['host']))
379380
return conn
380-
except pymysql.OperationalError:
381+
except pymysql.OperationalError as e:
382+
if 'certificate verify failed: IP address mismatch' in e.args[1]:
383+
logger.error("Hostname verification failed when estlablishing SSL/TLS Handshake with host: %s" % secret_dict['host'])
381384
return None
382385

383386

SecretsManagerRDSOracleRotationMultiUser/lambda_function.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ def lambda_handler(event, context):
1717
This handler uses the master-user rotation scheme to rotate an RDS Oracle user credential. During the first rotation, this
1818
scheme logs into the database as the master user, creates a new user (appending _CLONE to the username), and grants the
1919
new user all of the permissions from the user being rotated. Once the secret is in this state, every subsequent rotation
20-
simply creates a new secret with the AWSPREVIOUS user credentials, adds any missing permissions that are in the current
21-
secret, changes that user's password, and then marks the latest secret as AWSCURRENT.
20+
simply creates a new secret with the AWSPREVIOUS user credentials, changes that user's password, and then marks the
21+
latest secret as AWSCURRENT.
2222
2323
The Secret SecretString is expected to be a JSON string with the following format:
2424
{
@@ -206,7 +206,7 @@ def set_secret(service_client, arn, token):
206206
escaped_current = cur.fetchone()[0]
207207

208208
# Passwords cannot have double quotes in Oracle, remove any double quotes to allow the password to be properly escaped
209-
pending_password = pending_dict['password'].replace("\"","")
209+
pending_password = pending_dict['password'].replace("\"", "")
210210

211211
# Check to see if the user already exists
212212
cur.execute("SELECT USERNAME FROM DBA_USERS WHERE USERNAME=:username", username=pending_dict['username'].upper())
@@ -219,7 +219,8 @@ def set_secret(service_client, arn, token):
219219
cur.execute("CREATE USER %s IDENTIFIED BY \"%s\"" % (escaped_username, pending_password))
220220
for grant_type in ['ROLE_GRANT', 'SYSTEM_GRANT', 'OBJECT_GRANT']:
221221
try:
222-
cur.execute("SELECT DBMS_METADATA.GET_GRANTED_DDL(:grant_type, :username) FROM DUAL", grant_type=grant_type, username=current_dict['username'].upper())
222+
cur.execute("SELECT DBMS_METADATA.GET_GRANTED_DDL(:grant_type, :username) FROM DUAL", grant_type=grant_type,
223+
username=current_dict['username'].upper())
223224
results = cur.fetchall()
224225
for row in results:
225226
sql = row[0].read().strip(' \n\t').replace("%s" % escaped_current, "%s" % escaped_username)
@@ -325,8 +326,9 @@ def get_connection(secret_dict):
325326
conn = cx_Oracle.connect(secret_dict['username'],
326327
secret_dict['password'],
327328
secret_dict['host'] + ':' + port + '/' + secret_dict['dbname'])
329+
logger.info("Successfully established connection as user '%s' with host: '%s'" % (secret_dict['username'], secret_dict['host']))
328330
return conn
329-
except (cx_Oracle.DatabaseError, cx_Oracle.OperationalError) :
331+
except (cx_Oracle.DatabaseError, cx_Oracle.OperationalError):
330332
return None
331333

332334

@@ -398,6 +400,7 @@ def get_alt_username(current_username):
398400
raise ValueError("Unable to clone user, username length with _CLONE appended would exceed 30 characters")
399401
return new_username.upper()
400402

403+
401404
def is_rds_replica_database(replica_dict, master_dict):
402405
"""Validates that the database of a secret is a replica of the database of the master secret
403406
@@ -424,7 +427,7 @@ def is_rds_replica_database(replica_dict, master_dict):
424427
try:
425428
describe_response = rds_client.describe_db_instances(DBInstanceIdentifier=replica_instance_id)
426429
except Exception as err:
427-
logger.warn("Encountered error while verifying rds replica status: %s" % err)
430+
logger.warning("Encountered error while verifying rds replica status: %s" % err)
428431
return False
429432
instances = describe_response['DBInstances']
430433

@@ -435,4 +438,4 @@ def is_rds_replica_database(replica_dict, master_dict):
435438

436439
# DB Instance identifiers are unique - can only be one result
437440
current_instance = instances[0]
438-
return master_instance_id == current_instance.get('ReadReplicaSourceDBInstanceIdentifier')
441+
return master_instance_id == current_instance.get('ReadReplicaSourceDBInstanceIdentifier')

SecretsManagerRDSOracleRotationSingleUser/lambda_function.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ def set_secret(service_client, arn, token):
173173
conn = get_connection(current_dict)
174174
if not conn and previous_dict:
175175
# If both current and pending do not work, try previous
176-
conn = get_connection(pending_dict)
176+
conn = get_connection(previous_dict)
177177

178178
# Make sure the user/host from previous and pending match
179179
if previous_dict['username'] != pending_dict['username']:
@@ -195,10 +195,10 @@ def set_secret(service_client, arn, token):
195195
escaped_username = cur.fetchone()[0]
196196

197197
# Passwords cannot have double quotes in Oracle, remove any double quotes to allow the password to be properly escaped
198-
pending_password = pending_dict['password'].replace("\"","")
198+
pending_password = pending_dict['password'].replace("\"", "")
199199

200200
# Now set the password to the pending password
201-
sql="ALTER USER %s IDENTIFIED BY \"%s\"" % (escaped_username, pending_dict['password'])
201+
sql = "ALTER USER %s IDENTIFIED BY \"%s\"" % (escaped_username, pending_dict['password'])
202202
cur.execute(sql)
203203
conn.commit()
204204
logger.info("setSecret: Successfully set password for user %s in Oracle DB for secret arn %s." % (pending_dict['username'], arn))
@@ -295,8 +295,9 @@ def get_connection(secret_dict):
295295
conn = cx_Oracle.connect(secret_dict['username'],
296296
secret_dict['password'],
297297
secret_dict['host'] + ':' + port + '/' + secret_dict['dbname'])
298+
logger.info("Successfully established connection as user '%s' with host: '%s'" % (secret_dict['username'], secret_dict['host']))
298299
return conn
299-
except (cx_Oracle.DatabaseError, cx_Oracle.OperationalError) :
300+
except (cx_Oracle.DatabaseError, cx_Oracle.OperationalError):
300301
return None
301302

302303

SecretsManagerRDSPostgreSQLRotationMultiUser/lambda_function.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
22
# SPDX-License-Identifier: MIT-0
33

4+
import re
45
import boto3
56
import json
67
import logging
@@ -398,8 +399,15 @@ def connect_and_authenticate(secret_dict, port, dbname, use_ssl):
398399
else:
399400
conn = pgdb.connect(host=secret_dict['host'], user=secret_dict['username'], password=secret_dict['password'], database=dbname, port=port,
400401
connect_timeout=5, sslmode='disable')
402+
logger.info("Successfully established %s connection as user '%s' with host: '%s'" % ("SSL/TLS" if use_ssl else "non SSL/TLS", secret_dict['username'], secret_dict['host']))
401403
return conn
402-
except pg.InternalError:
404+
except pg.InternalError as e:
405+
if "server does not support SSL, but SSL was required" in e.args[0]:
406+
logger.error("Unable to establish SSL/TLS handshake, SSL/TLS is not enabled on the host: %s" % secret_dict['host'])
407+
elif re.search('server common name ".+" does not match host name ".+"', e.args[0]):
408+
logger.error("Hostname verification failed when estlablishing SSL/TLS Handshake with host: %s" % secret_dict['host'])
409+
elif re.search('no pg_hba.conf entry for host ".+", SSL off', e.args[0]):
410+
logger.error("Unable to establish SSL/TLS handshake, SSL/TLS is enforced on the host: %s" % secret_dict['host'])
403411
return None
404412

405413

@@ -500,7 +508,7 @@ def is_rds_replica_database(replica_dict, master_dict):
500508
try:
501509
describe_response = rds_client.describe_db_instances(DBInstanceIdentifier=replica_instance_id)
502510
except Exception as err:
503-
logger.warn("Encountered error while verifying rds replica status: %s" % err)
511+
logger.warning("Encountered error while verifying rds replica status: %s" % err)
504512
return False
505513
instances = describe_response['DBInstances']
506514

SecretsManagerRDSPostgreSQLRotationSingleUser/lambda_function.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
22
# SPDX-License-Identifier: MIT-0
33

4+
import re
45
import boto3
56
import json
67
import logging
@@ -382,8 +383,15 @@ def connect_and_authenticate(secret_dict, port, dbname, use_ssl):
382383
else:
383384
conn = pgdb.connect(host=secret_dict['host'], user=secret_dict['username'], password=secret_dict['password'], database=dbname, port=port,
384385
connect_timeout=5, sslmode='disable')
386+
logger.info("Successfully established %s connection as user '%s' with host: '%s'" % ("SSL/TLS" if use_ssl else "non SSL/TLS", secret_dict['username'], secret_dict['host']))
385387
return conn
386-
except pg.InternalError:
388+
except pg.InternalError as e:
389+
if "server does not support SSL, but SSL was required" in e.args[0]:
390+
logger.error("Unable to establish SSL/TLS handshake, SSL/TLS is not enabled on the host: %s" % secret_dict['host'])
391+
elif re.search('server common name ".+" does not match host name ".+"', e.args[0]):
392+
logger.error("Hostname verification failed when estlablishing SSL/TLS Handshake with host: %s" % secret_dict['host'])
393+
elif re.search('no pg_hba.conf entry for host ".+", SSL off', e.args[0]):
394+
logger.error("Unable to establish SSL/TLS handshake, SSL/TLS is enforced on the host: %s" % secret_dict['host'])
387395
return None
388396

389397

0 commit comments

Comments
 (0)