forked from ubergeek42/lambda-letsencrypt
-
Notifications
You must be signed in to change notification settings - Fork 2
/
lambda_function.py
698 lines (607 loc) · 27.8 KB
/
lambda_function.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
from __future__ import print_function
import logging
import datetime
from time import strftime, gmtime, sleep
from dateutil.tz import tzutc
from simple_acme import AcmeUser, AcmeAuthorization, AcmeCert
from functools import partial
import dns.resolver
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
# aws imports
import boto3
import botocore
# Configure logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger("Lambda-LetsEncrypt")
logger.setLevel(logging.DEBUG)
import config as cfg
###############################################################################
# No need to edit beyond this line
###############################################################################
# Global Variables and AWS Resources
s3 = boto3.resource('s3', region_name=cfg.AWS_REGION)
cloudfront = boto3.client('cloudfront', region_name=cfg.AWS_REGION)
iam = boto3.client('iam', region_name=cfg.AWS_REGION)
sns = boto3.client('sns', region_name=cfg.AWS_REGION)
elb = boto3.client('elbv2', region_name=cfg.AWS_REGION)
route53 = boto3.client('route53', region_name=cfg.AWS_REGION)
# Internal files to store user/authorization information
USERFILE = 'letsencrypt_user.json'
AUTHZRFILE = 'letsencrypt_authzr.json'
# Functions for storing/retrieving/deleting files from our config bucket
def save_file(site_id, filename, content):
s3.Object(cfg.S3CONFIGBUCKET, site_id + "/" + filename).put(Body=content)
def load_file(directory, filename):
try:
obj = s3.Object(cfg.S3CONFIGBUCKET, directory + "/" + filename).get()
return obj['Body'].read()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'NoSuchKey':
return False
return False
def delete_file(directory, filename):
try:
s3.Object(cfg.S3CONFIGBUCKET, directory + "/" + filename).delete()
return True
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'NoSuchKey':
return False
return False
# Verify the bucket exists
def check_bucket(bucketname):
try:
s3.meta.client.head_bucket(Bucket=bucketname)
exists = True
except botocore.exceptions.ClientError as e:
error_code = int(e.response['Error']['Code'])
if error_code == 404:
exists = False
# TODO: handle other errors better
exists = False
return exists
def get_user():
# Generate a user key to use with letsencrypt
userfile = load_file('letsencrypt', USERFILE)
user = None
if userfile is not False:
logger.info("User key exists, loading...")
user = AcmeUser.unserialize(userfile)
user.register(cfg.EMAIL)
else:
logger.info("Creating user and key")
user = AcmeUser(keybits=cfg.USERKEY_BITS)
user.create_key()
user.register(cfg.EMAIL)
save_file('letsencrypt', USERFILE, user.serialize())
return user
def notify_email(subject, message):
if cfg.SNS_TOPIC_ARN:
logger.info("Sending notification")
sns.publish(
TopicArn=cfg.SNS_TOPIC_ARN,
Subject="[Lambda-LetsEncrypt] {}".format(subject),
Message=message
)
def s3_challenge_solver(domain, token, keyauth, bucket=None, prefix=None):
# logger.info("Writing file {} with content '{}.{}' for domain '{}'".format(token, token, keyauth, domain))
logger.info("Got prefix {}".format(prefix))
filename = "{}/.well-known/acme-challenge/{}".format(prefix, token)
logger.info("Writing {} into S3 Bucket {}".format(filename, bucket))
expires = datetime.datetime.now() + datetime.timedelta(days=3)
challenge = s3.Object(bucket, filename)
challenge.put(
Body=keyauth,
Expires=expires
)
challenge.Acl().put(ACL='public-read')
return True
def http_challenge_verifier(domain, token, keyauth):
url = "http://{}/.well-known/acme-challenge/{}".format(domain, token)
try:
response = urlopen(url)
contents = response.read()
code = response.getcode()
except Exception as e:
logger.warn("Failed to verify:")
logger.warn(e)
return False
if code != 200:
logger.warn("HTTP code {} returned, expected 200".format(code))
return False
if contents != keyauth:
logger.warn("Validation body didn't match, expected '{}', got '{}'".format(keyauth, contents))
return False
return True
def route53_challenge_solver(domain, token, keyauth, zoneid=None):
name = '_acme-challenge.{}'.format(domain)
logger.info("set route53 {} record to {}".format(name, keyauth))
response = route53.change_resource_record_sets(
HostedZoneId=zoneid,
ChangeBatch={
'Comment': "Lamdba LetsEncrypt DNS Challenge Response",
'Changes': [{
'Action': 'UPSERT',
'ResourceRecordSet': {
'Name': name,
'Type': 'TXT',
'TTL': 300,
'ResourceRecords': [{
'Value': '"{}"'.format(keyauth)
}]
}
}]
}
)
return True
def route53_challenge_verifier(domain, token, keyauth):
# From https://github.com/brendanmckenzie/lambda-letsencrypt/commit/5f7b5b5ed4541f885a4ea090e30b4b82951b42a3
# DNS propagation may make this somewhat time consuming.
# try to resolve record '_acme-challenge.domain' and verify that the txt record value matches 'keyauth'
logger.info("Attempting to verify Route53 challenge."
"DNS record propagation might sometimes be so slow that lambda timeouts (max is 5min)."
"In that case this will fail, but it will succeed next time.")
record = '_acme-challenge.{}'.format(domain)
try:
records = dns.resolver.query(record, 'TXT')
current_keyauth = records[0].strings[0].strip()
logger.info('got txt record from dns: {}, excpected: {}'.format(current_keyauth, keyauth))
if (current_keyauth == keyauth):
logger.info('txt record is correct! Note that it is not guaranteed that letsencrypt also sees the record yet...')
return True
logger.info('dns txt record not yet propagated')
return False
except:
logger.info('dns txt get failed')
return False
def authorize_domain(user, domain):
authzrfilename = 'authzr-{}.json'.format(domain)
authzrfile = load_file(domain['DOMAIN'], authzrfilename)
if authzrfile is not False:
logger.info('authz loaded file: {}'.format(authzrfile))
authzr = AcmeAuthorization.unserialize(user, authzrfile)
else:
logger.info('Failed to load file: {}'.format(authzrfilename))
authzr = AcmeAuthorization(user=user, domain=domain['DOMAIN'])
status = authzr.authorize()
# If authorization is expired, delete authzr file and try again with a new one
if (status == 'expired'):
logger.info('Authorization for {} expired, deleting and recreating'.format(domain['DOMAIN']))
if delete_file(domain['DOMAIN'], authzrfilename):
return authorize_domain(user, domain)
else:
logger.warn('Error deleting file: {}'.format(authzrfilename))
# save the (new/updated) authorization response
save_file(domain['DOMAIN'], authzrfilename, authzr.serialize())
logger.debug(authzr.serialize())
# see if we're done:
#
# Note:
# - It might take 3 lambda invocation runs before certs are generated:
# Round 1: Authorisation challenge is created, will have status=pending.
# Lamba function sets the challenge hash to route53 dns but will not see the value through dns (not propagated),
# so will return False and challenge is leaved as 'pending'
# Round 2: (maybe next day / after some hours or at least minutes, depending your scheduling).
# The dns verifying function gets correct value (dns propagated).
# Requests letsencrypt to verify the challenge. Status was 'pending' in this step.
# Round 3: Letsencrypt has verified the challenge, so status='valid'. Certs will be finally are created!
#
# - Note: If round 2 is very soon (e.g. 0-15 minutes) it is possible that dns is still not propagated fully. So
# lamda could see the new value and request verification from letsencrypt, which could be on the other side
# of internet and not see yet the same dns record. In that case complete_challenges will fail, and next time status will be 'invalid'
# and authzr.authorize() will set internal challenge url to null which will cause it to create new challenge
# in the next round. Which might fail again for same reason.
# So it is SAFER to have LONG ENOUGH interval between lambda invocations. Even once a day should be ok
# since:
# - challenges have 1 month expiration time (no hurry!)
# - lambda starts to renew certs when they have 30 day still left
# - So even if it would take 3 days from creating challenge to have new certs, it should be ok
if status == 'pending':
if 'http-01' in domain['VALIDATION_METHODS']:
logger.info("Attempting challenge 'http-01'")
authzr.complete_challenges(
"http-01",
partial(s3_challenge_solver, bucket=cfg.S3CHALLENGEBUCKET, prefix=domain['CLOUDFRONT_ID']),
http_challenge_verifier
)
if 'dns-01' in domain['VALIDATION_METHODS']:
logger.info("Attempting challenge 'dns-01'")
authzr.complete_challenges(
"dns-01",
partial(route53_challenge_solver, zoneid=domain['ROUTE53_ZONE_ID']),
route53_challenge_verifier
)
logger.info("Waiting for challenge to be confirmed for '{}'".format(domain['DOMAIN']))
return False
elif status == 'valid':
logger.info("Got domain authorization for: {}".format(domain['DOMAIN']))
return authzr
else: # probably failed the challenge
logger.warn("Some error happend with authz request for '{}'(review above messages)".format(domain['DOMAIN']))
logger.warn("Will retry again next time this runs")
return False
def iam_upload_cert(certname, cert, key, chain):
# upload new cert
try:
newcert = iam.upload_server_certificate(
Path="/cloudfront/",
ServerCertificateName=certname,
CertificateBody=cert,
PrivateKey=key,
CertificateChain=chain
)
cert_id = newcert['ServerCertificateMetadata']['ServerCertificateId']
cert_arn = newcert['ServerCertificateMetadata']['Arn']
logger.info("Uploaded cert '{}' ({})".format(certname, cert_id))
return cert_id, cert_arn
except botocore.exceptions.ClientError as e:
logger.error("Error uploading iam cert:")
logger.error(e)
return False
def iam_delete_cert(arn=None, cert_id=None):
oldcert_name = None
allcerts = iam.list_server_certificates(
PathPrefix="/cloudfront/"
)
for c in allcerts['ServerCertificateMetadataList']:
if c['ServerCertificateId'] == cert_id or c['Arn'] == arn:
oldcert_name = c['ServerCertificateName']
break
if not oldcert_name:
logger.warn('Unable to find old certificate to delete')
return
logger.info('Deleting old certificate {}'.format(oldcert_name))
retries = 5
while retries > 0:
try:
iam.delete_server_certificate(ServerCertificateName=oldcert_name)
return
except botocore.exceptions.ClientError as e:
# we only retry if it said cert deleteconflict since it may take a few moments
# for something to stop using the certificate(e.g. elb)
if e.response['Error']['Code'] == 'DeleteConflict':
logger.info("Cert in use while trying to delete, retrying...")
sleep(5)
continue
logger.error("Unknown error occurred while deleting certificate")
logger.error(e)
notify_email(
"Unable to delete certificate",
"""Lambda-LetsEncrypt failed to delete the certificate '{}'. You should manually do this yourself""".format(oldcert_name)
)
break
def iam_check_expiration(arn=None, cert_id=None):
allcerts = iam.list_server_certificates(PathPrefix="/cloudfront/")
expiration = None
cert = None
for c in allcerts['ServerCertificateMetadataList']:
if c['ServerCertificateId'] == cert_id or c['Arn'] == arn:
cert = c
break
if not cert:
# no expiration found?
return True
expiration = cert['Expiration']
time_left = expiration - datetime.datetime.now(tz=tzutc())
if time_left.days < 10:
logger.warn("Only {} days left on cert {}!".format(time_left.days, cert['ServerCertificateName']))
notify_email(
'Less than 10 days left on cert {}'.format(cert['ServerCertificateName']),
"""
There's less than 10 days left on your certificate for {}. This probably
means the lambda function that is supposed to be handling the renewal is
failing. Please check the logs for it. Attempting to renew now.
""".format(cert['ServerCertificateName'])
)
return True
elif time_left.days < 30:
logger.info("Only {} days remaining, will proceed with renewal for {}".format(time_left.days, cert['ServerCertificateName']))
return True
else:
logger.info("{} days remaining on cert, nothing to do for {}.".format(time_left.days, cert['ServerCertificateName']))
return False
def is_elb_cert_expiring(site):
try:
load_balancers = elb.describe_load_balancers(
Names=[site['ELB_NAME']],
)
except botocore.exceptions.ClientError as e:
logger.error("Error getting information about Elastic Load Balancer '{}'".format(site['ELB_NAME']))
logger.error(e)
raise
currentcert_arn = None
for lb in load_balancers['LoadBalancers']:
if lb['LoadBalancerName'] != site['ELB_NAME']:
continue
listeners = elb.describe_listeners(
LoadBalancerArn=lb['LoadBalancerArn']
)['Listeners']
for listener in listeners:
if listener['Port'] != site['ELB_PORT']:
continue
if len(listener['Certificates']) > 0:
currentcert_arn = listener['Certificates'][0]['CertificateArn']
if currentcert_arn is None:
logger.info("No certificate exists for elb name {}".format(site['ELB_NAME']))
return True
else:
return iam_check_expiration(arn=currentcert_arn)
def is_cf_cert_expiring(site):
cf_config = cloudfront.get_distribution_config(Id=site['CLOUDFRONT_ID'])
currentcert = cf_config['DistributionConfig']['ViewerCertificate'].get('IAMCertificateId', None)
if currentcert is None:
logger.info("No certificate exists for {}".format(site['CLOUDFRONT_ID']))
return True
return iam_check_expiration(cert_id=currentcert)
def is_domain_expiring(site):
if 'CLOUDFRONT_ID' in site:
return is_cf_cert_expiring(site)
if 'ELB_NAME' in site:
return is_elb_cert_expiring(site)
logger.error("Can't detect site type(ELB or CLOUDFRONT)")
return False
def configure_cert(site, cert, key, chain):
certname = "{}_{}".format(site_id(site), strftime("%Y%m%d_%H%M%S", gmtime()))
cert_id, cert_arn = iam_upload_cert(certname, cert, key, chain)
f = None
if 'CLOUDFRONT_ID' in site:
f = cloudfront_configure_cert
if 'ELB_NAME' in site:
f = elb_configure_cert
if f is None:
logger.error("Can't detect site type when configuring certificate(ELB or CLOUDFRONT)")
ret = False
retries = 5
while retries > 0:
retries -= 1
try:
ret = f(site, cert_id, cert_arn)
break
except botocore.exceptions.ClientError as e:
# we only retry if it said cert not found
if e.response['Error']['Code'] == 'CertificateNotFound':
logger.info("Cert not found when trying to configure ELB, retrying...")
sleep(5)
continue
logger.error("Unknown error occurred while updating certificate")
logger.error(e)
ret = False
break
return ret
def elb_configure_cert(site, cert_id, cert_arn):
# get the current certificate for the load balancer(if there is one)
load_balancers = elb.describe_load_balancers(
Names=[site['ELB_NAME']],
)
for lb in load_balancers['LoadBalancers']:
if lb['LoadBalancerName'] != site['ELB_NAME']:
continue
listeners = elb.describe_listeners(
LoadBalancerArn=lb['LoadBalancerArn']
)['Listeners']
for listener in listeners:
if listener['Port'] != site['ELB_PORT']:
continue
oldcert_arn = None
if len(listener['Certificates']) > 0:
oldcert_arn = listener['Certificates'][0]['CertificateArn']
if oldcert_arn:
# Set up the new certificate
elb.modify_listener(
ListenerArn=listener['ListenerArn'],
Certificates=[{
'CertificateArn': cert_arn
}]
)
# Delete the old certificate if it existed
iam_delete_cert(arn=oldcert_arn)
else:
logger.info("No listener exists for specified port")
logger.error("Creating new listeners not supported yet! Please create one first manually, or implement elbv2 version of the code below :)")
return False
# if there wasn't an old cert, we need to configure the elb for HTTPS
# logger.info("No listener exists for specified port, creating default")
# create a load balancer policy
# logger.debug("Creating load balancer policy")
# elb.create_load_balancer_policy(
# LoadBalancerName=site['ELB_NAME'],
# PolicyName="lambda-letsencrypt-default-ssl-policy",
# PolicyTypeName="SSLNegotiationPolicyType",
# PolicyAttributes=[{
# 'AttributeName': 'Reference-Security-Policy',
# 'AttributeValue': 'ELBSecurityPolicy-2015-05'
# }]
# )
# # create a load balancer listener
# logger.debug("Creating load balancer listener")
# elb.create_load_balancer_listeners(
# LoadBalancerName=site['ELB_NAME'],
# Listeners=[{
# 'Protocol': 'HTTPS',
# 'LoadBalancerPort': site['ELB_PORT'],
# 'InstanceProtocol': 'HTTP',
# 'InstancePort': 80,
# 'SSLCertificateId': cert_arn
# }]
# )
# # associate policy with the listener
# logger.debug("Setting load balancer listener policy")
# elb.set_load_balancer_policies_of_listener(
# LoadBalancerName=site['ELB_NAME'],
# LoadBalancerPort=site['ELB_PORT'],
# PolicyNames=['lambda-letsencrypt-default-ssl-policy']
# )
return True
def cloudfront_configure_cert(site, cert_id, cert_arn):
# get current cloudfront distribution settings
cf_config = cloudfront.get_distribution_config(Id=site['CLOUDFRONT_ID'])
oldcert_id = cf_config['DistributionConfig']['ViewerCertificate'].get('IAMCertificateId', None)
# Make sure the default cloudfront cert isn't being used
if 'CloudFrontDefaultCertificate' in cf_config['DistributionConfig']['ViewerCertificate']:
del cf_config['DistributionConfig']['ViewerCertificate']['CloudFrontDefaultCertificate']
# update it to point to the new cert
cf_config['DistributionConfig']['ViewerCertificate']['IAMCertificateId'] = cert_id
cf_config['DistributionConfig']['ViewerCertificate']['Certificate'] = cert_id
cf_config['DistributionConfig']['ViewerCertificate']['CertificateSource'] = 'iam'
# make sure we use SNI only(otherwise the bill can be quite large, $600/month or so)
cf_config['DistributionConfig']['ViewerCertificate']['MinimumProtocolVersion'] = 'TLSv1'
cf_config['DistributionConfig']['ViewerCertificate']['SSLSupportMethod'] = 'sni-only'
# actually update the distribution
cloudfront.update_distribution(
DistributionConfig=cf_config['DistributionConfig'],
Id=site['CLOUDFRONT_ID'],
IfMatch=cf_config['ETag']
)
# delete the old cert
iam_delete_cert(cert_id=oldcert_id)
return True
def configure_cloudfront(domain, s3bucket):
cf_config = cloudfront.get_distribution_config(Id=domain['CLOUDFRONT_ID'])
changed = False
# make sure we have the origin configured
origins = cf_config['DistributionConfig']['Origins']['Items']
# check for the right origin
challenge_origin = [x for x in origins if x['Id'] == 'lambda-letsencrypt-challenges']
if not challenge_origin:
changed = True
quantity = cf_config['DistributionConfig']['Origins'].get('Quantity', 0)
cf_config['DistributionConfig']['Origins']['Quantity'] = quantity + 1
cf_config['DistributionConfig']['Origins']['Items'].append({
'DomainName': '{}.s3.amazonaws.com'.format(s3bucket),
'Id': 'lambda-letsencrypt-challenges',
'OriginPath': "/{}".format(domain['CLOUDFRONT_ID']),
'CustomHeaders': {u'Quantity': 0},
'S3OriginConfig': {u'OriginAccessIdentity': ''}
})
# now check for the behavior rule
behaviors = cf_config['DistributionConfig']['CacheBehaviors'].get('Items', [])
challenge_behavior = [x for x in behaviors if x['PathPattern'] == '/.well-known/acme-challenge/*']
if not challenge_behavior:
changed = True
if 'Items' not in cf_config['DistributionConfig']['CacheBehaviors']:
cf_config['DistributionConfig']['CacheBehaviors']['Items'] = []
cf_config['DistributionConfig']['CacheBehaviors']['Items'].append({
'AllowedMethods': {
'CachedMethods': {
'Items': ['HEAD', 'GET'],
'Quantity': 2
},
'Items': ['HEAD', 'GET'],
'Quantity': 2
},
'DefaultTTL': 86400,
'ForwardedValues': {
u'Cookies': {u'Forward': 'none'},
'Headers': {'Quantity': 0},
'QueryString': False,
'QueryStringCacheKeys': {'Quantity': 0}
},
'LambdaFunctionAssociations': {'Quantity': 0},
'MaxTTL': 31536000,
'MinTTL': 0,
'PathPattern': '/.well-known/acme-challenge/*',
'SmoothStreaming': False,
'TargetOriginId': 'lambda-letsencrypt-challenges',
'TrustedSigners': {u'Enabled': False, 'Quantity': 0},
'ViewerProtocolPolicy': 'allow-all',
'Compress': False
})
quantity = cf_config['DistributionConfig']['CacheBehaviors'].get('Quantity', 0)
cf_config['DistributionConfig']['CacheBehaviors']['Quantity'] = quantity + 1
# make sure we use SNI and not dedicated IP($600/month)
ssl_method = cf_config['DistributionConfig']['ViewerCertificate'].get('SSLSupportMethod', None)
if ssl_method != 'sni-only':
changed = True
cf_config['DistributionConfig']['ViewerCertificate']['MinimumProtocolVersion'] = 'TLSv1'
cf_config['DistributionConfig']['ViewerCertificate']['SSLSupportMethod'] = 'sni-only'
if changed:
logger.info("Updating cloudfront distribution with additional origin for challenges")
# now save that config back
try:
cloudfront.update_distribution(
DistributionConfig=cf_config['DistributionConfig'],
Id=domain['CLOUDFRONT_ID'],
IfMatch=cf_config['ETag']
)
except Exception as e:
logger.error("Error updating cloudfront distribution")
logger.error(e)
def site_name(site):
if 'CLOUDFRONT_ID' in site:
return "CloudFront Distribution '{}'".format(site['CLOUDFRONT_ID'])
elif 'ELB_NAME' in site:
return "ELB Name '{}'".format(site['ELB_NAME'])
def site_id(site):
if 'CLOUDFRONT_ID' in site:
return "cfd-{}".format(site['CLOUDFRONT_ID'])
elif 'ELB_NAME' in site:
return 'elb-{}'.format(site['ELB_NAME'])
def lambda_handler(event, context):
action_needed = False
# Do a few sanity checks
if not check_bucket(cfg.S3CONFIGBUCKET):
logger.error("S3 configuration bucket does not exist")
notify_email(
"Lambda-LetsEncrypt config bucket missing {}".format(cfg.S3CONFIGBUCKET),
"S3 Configuration bucket {} required for managing certificates in {} is missing".format(cfg.S3CONFIGBUCKET, cfg.SITES)
)
return False
if (cfg.S3CHALLENGEBUCKET is not None) and (not check_bucket(cfg.S3CHALLENGEBUCKET)):
logger.error("S3 challenge bucket does not exist")
notify_email(
"Lambda-LetsEncrypt challenge bucket missing {}".format(cfg.S3CHALLENGEBUCKET),
"S3 Challenge bucket {} required for LetsEncrypt verifications in {} is missing".format(cfg.S3CHALLENGEBUCKET, cfg.SITES)
)
return False
# check the certificates we want issued
for site in cfg.SITES:
if not is_domain_expiring(site):
site['skip'] = True
continue
action_needed = True
# quit if there's nothing to do
if not action_needed:
return False
# get our user key to use with lets-encrypt
user = get_user()
# validate domains
my_domains = []
for domain in cfg.DOMAINS:
# make sure cloudfront is configured properly for http-01 challenge validation
if 'http-01' in domain['VALIDATION_METHODS']:
configure_cloudfront(domain, cfg.S3CHALLENGEBUCKET)
authzr = authorize_domain(user, domain)
if authzr:
my_domains.append(domain['DOMAIN'])
for site in cfg.SITES:
if 'skip' in site:
continue
# check that we are authed for all the domains for this site
if not set(site['DOMAINS']).issubset(my_domains):
logger.info("Can't get cert for {}, still waiting on domain authorizations".format(site_name(site)))
continue
try:
# Now that we're authorized to get certs for the domain(s), lets generate
# a private key and a csr, then use them to get a certificate
logger.info("Generate CSR and get cert for {}".format(site_name(site)))
pkey, csr = AcmeCert.generate_csr(cfg.CERT_BITS, site['DOMAINS'])
cert, cert_chain = AcmeCert.get_cert(user, csr)
# With our certificate in hand we can update the site configuration
ret = configure_cert(site, cert, pkey, cert_chain)
if ret:
notify_email("Certificate issued",
"The certificate for {} has been successfully updated".format(site_name(site)))
else:
notify_email("Error issuing cert",
"There was some sort of error configuring the site({}) with the certificate.".format(site_name(site)) +
"Please review the logs in cloudwatch.")
except Exception as e:
logger.warning(e)
raise
# Support running directly for testing
if __name__ == '__main__':
lambda_handler(None, None)