-
Notifications
You must be signed in to change notification settings - Fork 187
/
__init__.py
executable file
·4108 lines (3451 loc) · 140 KB
/
__init__.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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright 2017-2018 Amazon.com, Inc. and its affiliates. All Rights Reserved.
#
# Licensed under the MIT License. See the LICENSE accompanying this file
# for the specific language governing permissions and limitations under
# the License.
#
#
# Copy this script to /sbin/mount.efs and make sure it is executable.
#
# You will be able to mount an EFS file system by its short name, by adding it
# to /etc/fstab. The syntax of an fstab entry is:
#
# [Device] [Mount Point] [File System Type] [Options] [Dump] [Pass]
#
# Add an entry like this:
#
# fs-deadbeef /mount_point efs _netdev 0 0
#
# Using the 'efs' type will cause '/sbin/mount.efs' to be called by 'mount -a'
# for this file system. The '_netdev' option tells the init system that the
# 'efs' type is a networked file system type. This has been tested with systemd
# (Amazon Linux 2, CentOS 7, RHEL 7, Debian 9, and Ubuntu 16.04), and upstart
# (Amazon Linux 2017.09).
#
# Once there is an entry in fstab, the file system can be mounted with:
#
# sudo mount /mount_point
#
# The script will add recommended mount options, if not provided in fstab.
import base64
import errno
import hashlib
import hmac
import json
import logging
import os
import platform
import pwd
import random
import re
import socket
import subprocess
import sys
import threading
import time
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from logging.handlers import RotatingFileHandler
try:
from configparser import ConfigParser, NoOptionError, NoSectionError
except ImportError:
import ConfigParser
from ConfigParser import NoOptionError, NoSectionError
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
try:
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
except ImportError:
from urllib import urlencode
from urllib2 import HTTPError, HTTPHandler, Request, URLError, build_opener, urlopen
try:
import botocore.config
import botocore.session
from botocore.exceptions import (
ClientError,
EndpointConnectionError,
NoCredentialsError,
ProfileNotFound,
)
BOTOCORE_PRESENT = True
except ImportError:
BOTOCORE_PRESENT = False
VERSION = "2.1.0"
SERVICE = "elasticfilesystem"
AMAZON_LINUX_2_RELEASE_ID = "Amazon Linux release 2 (Karoo)"
AMAZON_LINUX_2_PRETTY_NAME = "Amazon Linux 2"
AMAZON_LINUX_2_RELEASE_VERSIONS = [
AMAZON_LINUX_2_RELEASE_ID,
AMAZON_LINUX_2_PRETTY_NAME,
]
CLONE_NEWNET = 0x40000000
CONFIG_FILE = "/etc/amazon/efs/efs-utils.conf"
CONFIG_SECTION = "mount"
CLIENT_INFO_SECTION = "client-info"
CLIENT_SOURCE_STR_LEN_LIMIT = 100
# Cloudwatchlog agent dict includes cloudwatchlog botocore client, cloudwatchlog group name, cloudwatchlog stream name
CLOUDWATCHLOG_AGENT = None
CLOUDWATCH_LOG_SECTION = "cloudwatch-log"
DEFAULT_CLOUDWATCH_LOG_GROUP = "/aws/efs/utils"
DEFAULT_FALLBACK_ENABLED = True
DEFAULT_RETENTION_DAYS = 14
DEFAULT_UNKNOWN_VALUE = "unknown"
# 50ms
DEFAULT_TIMEOUT = 0.05
DEFAULT_MACOS_VALUE = "macos"
DEFAULT_GET_AWS_EC2_METADATA_TOKEN_RETRY_COUNT = 3
DEFAULT_NFS_MOUNT_COMMAND_RETRY_COUNT = 3
DEFAULT_NFS_MOUNT_COMMAND_TIMEOUT_SEC = 15
DISABLE_FETCH_EC2_METADATA_TOKEN_ITEM = "disable_fetch_ec2_metadata_token"
FALLBACK_TO_MOUNT_TARGET_IP_ADDRESS_ITEM = (
"fall_back_to_mount_target_ip_address_enabled"
)
INSTANCE_IDENTITY = None
INSTANCE_AZ_ID_METADATA = None
RETRYABLE_ERRORS = ["reset by peer"]
OPTIMIZE_READAHEAD_ITEM = "optimize_readahead"
LOG_DIR = "/var/log/amazon/efs"
LOG_FILE = "mount.log"
STATE_FILE_DIR = "/var/run/efs"
PRIVATE_KEY_FILE = "/etc/amazon/efs/privateKey.pem"
DATE_ONLY_FORMAT = "%Y%m%d"
SIGV4_DATETIME_FORMAT = "%Y%m%dT%H%M%SZ"
CERT_DATETIME_FORMAT = "%y%m%d%H%M%SZ"
AWS_CREDENTIALS_FILE = os.path.expanduser(
os.path.join("~" + pwd.getpwuid(os.getuid()).pw_name, ".aws", "credentials")
)
AWS_CONFIG_FILE = os.path.expanduser(
os.path.join("~" + pwd.getpwuid(os.getuid()).pw_name, ".aws", "config")
)
CA_CONFIG_BODY = """dir = %s
RANDFILE = $dir/database/.rand
[ ca ]
default_ca = local_ca
[ local_ca ]
database = $dir/database/index.txt
serial = $dir/database/serial
private_key = %s
cert = $dir/certificate.pem
new_certs_dir = $dir/certs
default_md = sha256
preserve = no
policy = efsPolicy
x509_extensions = v3_ca
[ efsPolicy ]
CN = supplied
[ req ]
prompt = no
distinguished_name = req_distinguished_name
[ req_distinguished_name ]
CN = %s
%s
%s
%s
"""
# SigV4 Auth
ALGORITHM = "AWS4-HMAC-SHA256"
AWS4_REQUEST = "aws4_request"
HTTP_REQUEST_METHOD = "GET"
CANONICAL_URI = "/"
CANONICAL_HEADERS_DICT = {"host": "%s"}
CANONICAL_HEADERS = "\n".join(
["%s:%s" % (k, v) for k, v in sorted(CANONICAL_HEADERS_DICT.items())]
)
SIGNED_HEADERS = ";".join(CANONICAL_HEADERS_DICT.keys())
REQUEST_PAYLOAD = ""
FS_ID_RE = re.compile("^(?P<fs_id>fs-[0-9a-f]+)$")
EFS_FQDN_RE = re.compile(
r"^((?P<az>[a-z0-9-]+)\.)?(?P<fs_id>fs-[0-9a-f]+)\.efs\."
r"(?P<region>[a-z0-9-]+)\.(?P<dns_name_suffix>[a-z0-9.]+)$"
)
AP_ID_RE = re.compile("^fsap-[0-9a-f]{17}$")
CREDENTIALS_KEYS = ["AccessKeyId", "SecretAccessKey", "Token"]
ECS_TASK_METADATA_API = "http://169.254.170.2"
STS_ENDPOINT_URL_FORMAT = "https://sts.{}.amazonaws.com/"
INSTANCE_METADATA_TOKEN_URL = "http://169.254.169.254/latest/api/token"
INSTANCE_METADATA_SERVICE_URL = (
"http://169.254.169.254/latest/dynamic/instance-identity/document/"
)
INSTANCE_METADATA_SERVICE_AZ_ID_URL = (
"http://169.254.169.254/latest/meta-data/placement/availability-zone-id"
)
INSTANCE_IAM_URL = "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
NAMED_PROFILE_HELP_URL = (
"https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html"
)
CONFIG_FILE_SETTINGS_HELP_URL = (
"https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html"
"#cli-configure-files-settings"
)
SECURITY_CREDS_ECS_URI_HELP_URL = (
"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html"
)
SECURITY_CREDS_WEBIDENTITY_HELP_URL = "https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html"
SECURITY_CREDS_IAM_ROLE_HELP_URL = (
"https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html"
)
DEFAULT_STUNNEL_VERIFY_LEVEL = 2
DEFAULT_STUNNEL_CAFILE = "/etc/amazon/efs/efs-utils.crt"
LEGACY_STUNNEL_MOUNT_OPTION = "stunnel"
NOT_BEFORE_MINS = 15
NOT_AFTER_HOURS = 3
EFS_PROXY_TLS_OPTION = "--tls"
EFS_ONLY_OPTIONS = [
"accesspoint",
"awscredsuri",
"awsprofile",
"az",
"cafile",
"iam",
"mounttargetip",
"netns",
"noocsp",
"notls",
"ocsp",
"region",
"tls",
"tlsport",
"verify",
"rolearn",
"jwtpath",
"fsap",
"crossaccount",
LEGACY_STUNNEL_MOUNT_OPTION,
]
UNSUPPORTED_OPTIONS = ["capath"]
STUNNEL_GLOBAL_CONFIG = {
"fips": "no",
"foreground": "yes",
"socket": [
"l:SO_REUSEADDR=yes",
"a:SO_BINDTODEVICE=lo",
],
}
STUNNEL_EFS_CONFIG = {
"client": "yes",
"accept": "127.0.0.1:%s",
"connect": "%s:2049",
"sslVersion": "TLSv1.2",
"renegotiation": "no",
"TIMEOUTbusy": "20",
"TIMEOUTclose": "0",
"TIMEOUTidle": "70",
"delay": "yes",
}
WATCHDOG_SERVICE = "amazon-efs-mount-watchdog"
# MacOS instances use plist files. This files needs to be loaded on launchctl (init system of MacOS)
WATCHDOG_SERVICE_PLIST_PATH = "/Library/LaunchAgents/amazon-efs-mount-watchdog.plist"
SYSTEM_RELEASE_PATH = "/etc/system-release"
OS_RELEASE_PATH = "/etc/os-release"
MACOS_BIG_SUR_RELEASE = "macOS-11"
MACOS_MONTEREY_RELEASE = "macOS-12"
MACOS_VENTURA_RELEASE = "macOS-13"
MACOS_SONOMA_RELEASE = "macOS-14"
# Multiplier for max read ahead buffer size
# Set default as 15 aligning with prior linux kernel 5.4
DEFAULT_NFS_MAX_READAHEAD_MULTIPLIER = 15
NFS_READAHEAD_CONFIG_PATH_FORMAT = "/sys/class/bdi/%s:%s/read_ahead_kb"
NFS_READAHEAD_OPTIMIZE_LINUX_KERNEL_MIN_VERSION = [5, 4]
# MacOS does not support the property of Socket SO_BINDTODEVICE in stunnel configuration
SKIP_NO_SO_BINDTODEVICE_RELEASES = [
MACOS_BIG_SUR_RELEASE,
MACOS_MONTEREY_RELEASE,
MACOS_VENTURA_RELEASE,
MACOS_SONOMA_RELEASE,
]
MAC_OS_PLATFORM_LIST = ["darwin"]
# MacOS Versions : Sonoma - 23.*, Ventura - 22.*, Monterey - 21.*, Big Sur - 20.*, Catalina - 19.*, Mojave - 18.*. Catalina and Mojave are not supported for now
MAC_OS_SUPPORTED_VERSION_LIST = ["20", "21", "22", "23"]
AWS_FIPS_ENDPOINT_CONFIG_ENV = "AWS_USE_FIPS_ENDPOINT"
ECS_URI_ENV = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"
WEB_IDENTITY_ROLE_ARN_ENV = "AWS_ROLE_ARN"
WEB_IDENTITY_TOKEN_FILE_ENV = "AWS_WEB_IDENTITY_TOKEN_FILE"
ECS_FARGATE_TASK_METADATA_ENDPOINT_ENV = "ECS_CONTAINER_METADATA_URI_V4"
ECS_FARGATE_TASK_METADATA_ENDPOINT_URL_EXTENSION = "/task"
ECS_FARGATE_CLIENT_IDENTIFIER = "ecs.fargate"
def errcheck(ret, func, args):
from ctypes import get_errno
if ret == -1:
e = get_errno()
raise OSError(e, os.strerror(e))
def setns(fd, nstype):
from ctypes import CDLL
libc = CDLL("libc.so.6", use_errno=True)
libc.setns.errcheck = errcheck
if hasattr(fd, "fileno"):
fd = fd.fileno()
return libc.setns(fd, nstype)
class NetNS(object):
# Open sockets from given network namespace: stackoverflow.com/questions/28846059
def __init__(self, nspath):
self.original_nspath = "/proc/%d/ns/net" % os.getpid()
self.target_nspath = nspath
def __enter__(self):
self.original_namespace = open(self.original_nspath)
with open(self.target_nspath) as fd:
setns(fd, CLONE_NEWNET)
def __exit__(self, *args):
setns(self.original_namespace, CLONE_NEWNET)
self.original_namespace.close()
class FallbackException(Exception):
"""Exception raised for errors happens when dns resolve and fallback to mount target ip address attempt both fail
Attributes:
message -- explanation of the error
"""
def __init__(self, message):
self.message = message
super().__init__(self.message)
def fatal_error(user_message, log_message=None, exit_code=1):
if log_message is None:
log_message = user_message
sys.stderr.write("%s\n" % user_message)
logging.error(log_message)
publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, "Mount failed, %s" % log_message)
sys.exit(exit_code)
def get_target_region(config, options):
def _fatal_error(message):
fatal_error(
'Error retrieving region. Please set the "region" parameter '
"in the efs-utils configuration file or specify it as a "
"mount option.",
message,
)
if "region" in options:
return options.get("region")
try:
return config.get(CONFIG_SECTION, "region")
except NoOptionError:
pass
try:
return get_region_from_instance_metadata(config)
except Exception as e:
metadata_exception = e
logging.warning(
"Region not found in config file and metadata service call failed, falling back "
'to legacy "dns_name_format" check'
)
try:
region = get_region_from_legacy_dns_format(config)
sys.stdout.write(
'Warning: region obtained from "dns_name_format" field. Please set the "region" '
"parameter in the efs-utils configuration file."
)
return region
except Exception:
logging.warning('Legacy check for region in "dns_name_format" failed')
_fatal_error(metadata_exception)
def get_target_az(config, options):
if "az" in options:
return options.get("az")
try:
return get_az_from_instance_metadata(config)
except Exception as e:
logging.warning("Get AZ via metadata service call failed, %s", e)
return None
def get_region_from_instance_metadata(config):
instance_identity = get_instance_identity_info_from_instance_metadata(
config, "region"
)
if not instance_identity:
raise Exception(
"Cannot retrieve region from instance_metadata. "
"Please set the 'region' parameter in the efs-utils configuration file."
)
return instance_identity
def get_az_from_instance_metadata(config):
instance_identity = get_instance_identity_info_from_instance_metadata(
config, "availabilityZone"
)
if not instance_identity:
raise Exception("Cannot retrieve az from instance_metadata")
return instance_identity
def get_az_id_from_instance_metadata(config, options):
az_id = get_az_id_info_from_instance_metadata(config, options)
if not az_id:
raise RuntimeError("Cannot retrieve az-id from instance_metadata")
return az_id
def get_az_id_info_from_instance_metadata(config, options):
logging.debug("Retrieve availability-zone-id from instance metadata")
instance_az_id_url = get_instance_az_id_metadata_url(config)
metadata_unsuccessful_resp = (
"Unsuccessful retrieval of metadata at %s." % instance_az_id_url
)
metadata_url_error_msg = (
"Unable to reach %s to retrieve instance metadata." % instance_az_id_url
)
global INSTANCE_AZ_ID_METADATA
if INSTANCE_AZ_ID_METADATA:
logging.debug(
"Instance az_id already retrieved in previous call, use the cached values."
)
az_id_metadata = INSTANCE_AZ_ID_METADATA
else:
az_id_metadata = url_request_helper(
config,
instance_az_id_url,
metadata_unsuccessful_resp,
metadata_url_error_msg,
)
INSTANCE_AZ_ID_METADATA = az_id_metadata
# ECS Fargate returns a json response with the AZ-name which we convert to AZ-ID
if az_id_metadata and is_ecs_fargate_client(config):
return get_az_id_from_ecs_fargate_response(config, options, az_id_metadata)
elif az_id_metadata:
return az_id_metadata
return None
def get_instance_az_id_metadata_url(config):
instance_az_id_url = INSTANCE_METADATA_SERVICE_AZ_ID_URL
if is_ecs_fargate_client(config):
# ECS-Fargate Metadata Endpoint must be used for ECS-Fargate clients.
logging.debug("ECS-Fargate client detected, use ECS-Fargate Metadata Endpoint")
try:
instance_az_id_url = (
os.getenv(ECS_FARGATE_TASK_METADATA_ENDPOINT_ENV)
+ ECS_FARGATE_TASK_METADATA_ENDPOINT_URL_EXTENSION
)
except Exception as e:
logging.warning("Unable to parse ECS-Fargate Metadata Endpoint: %s", e)
instance_az_id_url = None
return instance_az_id_url
def is_ecs_fargate_client(config):
client_info = get_client_info(config)
if client_info and client_info.get("source") == ECS_FARGATE_CLIENT_IDENTIFIER:
return True
return False
def get_az_id_from_ecs_fargate_response(config, options, az_id_metadata):
try:
property = "AvailabilityZone"
az_name = az_id_metadata[property]
ec2_client = get_botocore_client(config, "ec2", options)
az_id = get_az_id_by_az_name(ec2_client, az_name)
return az_id
except KeyError as e:
logging.warning("%s not present in %s: %s" % (property, az_id_metadata, e))
except TypeError as e:
logging.warning("response %s is not a json object: %s" % (az_id_metadata, e))
except FallbackException as e:
fatal_error(e.message)
return None
def get_instance_identity_info_from_instance_metadata(config, property):
logging.debug("Retrieve property %s from instance metadata", property)
ec2_metadata_unsuccessful_resp = (
"Unsuccessful retrieval of EC2 metadata at %s." % INSTANCE_METADATA_SERVICE_URL
)
ec2_metadata_url_error_msg = (
"Unable to reach %s to retrieve EC2 instance metadata."
% INSTANCE_METADATA_SERVICE_URL
)
global INSTANCE_IDENTITY
if INSTANCE_IDENTITY:
logging.debug(
"Instance metadata already retrieved in previous call, use the cached values."
)
instance_identity = INSTANCE_IDENTITY
else:
instance_identity = url_request_helper(
config,
INSTANCE_METADATA_SERVICE_URL,
ec2_metadata_unsuccessful_resp,
ec2_metadata_url_error_msg,
)
INSTANCE_IDENTITY = instance_identity
if instance_identity:
try:
return instance_identity[property]
except KeyError as e:
logging.warning(
"%s not present in %s: %s" % (property, instance_identity, e)
)
except TypeError as e:
logging.warning(
"response %s is not a json object: %s" % (instance_identity, e)
)
return None
def get_region_from_legacy_dns_format(config):
"""
For backwards compatibility check dns_name_format to obtain the target region. This functionality
should only be used if region is not present in the config file and metadata calls fail.
"""
dns_name_format = config.get(CONFIG_SECTION, "dns_name_format")
if "{region}" not in dns_name_format:
split_dns_name_format = dns_name_format.split(".")
if "{dns_name_suffix}" in dns_name_format:
return split_dns_name_format[-2]
elif "amazonaws.com" in dns_name_format:
return split_dns_name_format[-3]
raise Exception("Region not found in dns_name_format")
def get_boolean_config_item_value(
config, config_section, config_item, default_value, emit_warning_message=True
):
warning_message = None
if not config.has_section(config_section):
warning_message = (
"Warning: config file does not have section %s." % config_section
)
elif not config.has_option(config_section, config_item):
warning_message = (
"Warning: config file does not have %s item in section %s."
% (config_item, config_section)
)
if warning_message:
if emit_warning_message:
sys.stdout.write(
"%s. You should be able to find a new config file in the same folder as current config file %s. "
"Consider update the new config file to latest config file. Use the default value [%s = %s]."
% (warning_message, CONFIG_FILE, config_item, default_value)
)
return default_value
return config.getboolean(config_section, config_item)
def fetch_ec2_metadata_token_disabled(config):
return get_boolean_config_item_value(
config,
CONFIG_SECTION,
DISABLE_FETCH_EC2_METADATA_TOKEN_ITEM,
default_value=False,
)
def get_aws_ec2_metadata_token(
request_timeout=0.5,
max_retries=DEFAULT_GET_AWS_EC2_METADATA_TOKEN_RETRY_COUNT,
retry_delay=0.5,
):
"""
Retrieves the AWS EC2 metadata token. Typically, the token is fetched
within 10ms. We set a default timeout of 0.5 seconds to prevent mount
failures caused by slow requests.
Args:
max_retries (int): The maximum number of retries.
retry_delay (int): The delay in seconds between retries.
Returns:
The AWS EC2 metadata token str or None if it cannot be retrieved.
"""
def get_token(timeout):
try:
opener = build_opener(HTTPHandler)
request = Request(INSTANCE_METADATA_TOKEN_URL)
request.add_header("X-aws-ec2-metadata-token-ttl-seconds", "21600")
request.get_method = lambda: "PUT"
try:
response = opener.open(request, timeout=timeout)
return response.read()
finally:
opener.close()
except NameError:
headers = {"X-aws-ec2-metadata-token-ttl-seconds": "21600"}
request = Request(
INSTANCE_METADATA_TOKEN_URL, headers=headers, method="PUT"
)
response = urlopen(request, timeout=timeout)
return response.read()
retries = 0
while retries < max_retries:
try:
return get_token(timeout=request_timeout)
except socket.timeout:
logging.debug(
"Timeout when getting the aws ec2 metadata token. Attempt: %s/%s"
% (retries + 1, max_retries)
)
except HTTPError as e:
logging.debug(
"Failed to fetch token due to %s. Attempt: %s/%s"
% (e, retries + 1, max_retries)
)
except Exception as e:
logging.debug(
"Unknown error when fetching aws ec2 metadata token, %s. Attempt: %s/%s"
% (e, retries + 1, max_retries)
)
retries += 1
if retries < max_retries:
logging.debug("Retrying in %s seconds", retry_delay)
time.sleep(retry_delay)
else:
logging.debug(
"Unable to retrieve AWS EC2 metadata token. Maximum number of retries reached."
)
return None
def get_aws_security_credentials(
config,
use_iam,
region,
awsprofile=None,
aws_creds_uri=None,
jwt_path=None,
role_arn=None,
):
"""
Lookup AWS security credentials. Adapted credentials provider chain from:
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html and
https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html
If iam is enabled, this function will return two objects, credentials and credentials_source.
credentials is a dictionary with three keys, "AccessKeyId", "SecretAccessKey", and "Token".
credentials_source will be a string that describes the method by which the credentials were obtained.
"""
if not use_iam:
return None, None
# attempt to lookup AWS security credentials through the credentials URI the ECS agent generated
if aws_creds_uri:
return get_aws_security_credentials_from_ecs(config, aws_creds_uri, True)
# attempt to lookup AWS security credentials in AWS credentials file (~/.aws/credentials)
# and configs file (~/.aws/config) with given awsprofile
# if the credentials are not present in above filepath, and botocore is present, attempt to assume the given awsprofile
if awsprofile:
return get_aws_security_credentials_from_awsprofile(awsprofile, True)
# attempt to lookup AWS security credentials through AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable
if ECS_URI_ENV in os.environ:
credentials, credentials_source = get_aws_security_credentials_from_ecs(
config, os.environ[ECS_URI_ENV], False
)
if credentials and credentials_source:
return credentials, credentials_source
# attempt to lookup AWS security credentials through AssumeRoleWithWebIdentity
# (e.g. for IAM Role for Service Accounts (IRSA) approach on EKS)
if jwt_path and role_arn:
credentials, credentials_source = get_aws_security_credentials_from_webidentity(
config,
role_arn,
jwt_path,
region,
False,
)
if credentials and credentials_source:
return credentials, credentials_source
if (
WEB_IDENTITY_ROLE_ARN_ENV in os.environ
and WEB_IDENTITY_TOKEN_FILE_ENV in os.environ
):
credentials, credentials_source = get_aws_security_credentials_from_webidentity(
config,
os.environ[WEB_IDENTITY_ROLE_ARN_ENV],
os.environ[WEB_IDENTITY_TOKEN_FILE_ENV],
region,
False,
)
if credentials and credentials_source:
return credentials, credentials_source
# attempt to lookup AWS security credentials with IAM role name attached to instance
# through IAM role name security credentials lookup uri
iam_role_name = get_iam_role_name(config)
if iam_role_name:
(
credentials,
credentials_source,
) = get_aws_security_credentials_from_instance_metadata(config, iam_role_name)
if credentials and credentials_source:
return credentials, credentials_source
error_msg = (
"AWS Access Key ID and Secret Access Key are not found in AWS credentials file (%s), config file (%s), "
"from ECS credentials relative uri, or from the instance security credentials service"
% (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE)
)
fatal_error(error_msg, error_msg)
def get_aws_security_credentials_from_awsprofile(awsprofile, is_fatal=False):
for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]:
if os.path.exists(file_path):
credentials = credentials_file_helper(file_path, awsprofile)
if credentials["AccessKeyId"]:
logging.debug("Retrieved credentials from %s" % file_path)
return credentials, os.path.basename(file_path) + ":" + awsprofile
# If credentials are not defined in the aws credentials and config file, attempt to assume the named profile
credentials = botocore_credentials_helper(awsprofile)
if credentials["AccessKeyId"]:
logging.debug("Retrieved credentials from assumed profile %s" % awsprofile)
return credentials, "named_profile:" + awsprofile
# Fail if credentials cannot be fetched from the given awsprofile
if is_fatal:
log_message = (
"AWS security credentials not found in %s or %s under named profile [%s]"
% (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE, awsprofile)
)
fatal_error(log_message)
else:
return None, None
def get_aws_security_credentials_from_ecs(config, aws_creds_uri, is_fatal=False):
ecs_uri = ECS_TASK_METADATA_API + aws_creds_uri
ecs_unsuccessful_resp = (
"Unsuccessful retrieval of AWS security credentials at %s." % ecs_uri
)
ecs_url_error_msg = (
"Unable to reach %s to retrieve AWS security credentials. See %s for more info."
% (ecs_uri, SECURITY_CREDS_ECS_URI_HELP_URL)
)
ecs_security_dict = url_request_helper(
config, ecs_uri, ecs_unsuccessful_resp, ecs_url_error_msg
)
if ecs_security_dict and all(k in ecs_security_dict for k in CREDENTIALS_KEYS):
return ecs_security_dict, "ecs:" + aws_creds_uri
# Fail if credentials cannot be fetched from the given aws_creds_uri
if is_fatal:
fatal_error(ecs_unsuccessful_resp, ecs_unsuccessful_resp)
else:
return None, None
def get_aws_security_credentials_from_webidentity(
config, role_arn, token_file, region, is_fatal=False
):
try:
with open(token_file, "r") as f:
token = f.read()
except Exception as e:
if is_fatal:
unsuccessful_resp = "Error reading token file %s: %s" % (token_file, e)
fatal_error(unsuccessful_resp, unsuccessful_resp)
else:
return None, None
STS_ENDPOINT_URL = STS_ENDPOINT_URL_FORMAT.format(region)
webidentity_url = (
STS_ENDPOINT_URL
+ "?"
+ urlencode(
{
"Version": "2011-06-15",
"Action": "AssumeRoleWithWebIdentity",
"RoleArn": role_arn,
"RoleSessionName": "efs-mount-helper",
"WebIdentityToken": token,
}
)
)
unsuccessful_resp = (
"Unsuccessful retrieval of AWS security credentials at %s." % STS_ENDPOINT_URL
)
url_error_msg = (
"Unable to reach %s to retrieve AWS security credentials. See %s for more info."
% (STS_ENDPOINT_URL, SECURITY_CREDS_WEBIDENTITY_HELP_URL)
)
resp = url_request_helper(
config,
webidentity_url,
unsuccessful_resp,
url_error_msg,
headers={"Accept": "application/json"},
)
if resp:
creds = (
resp.get("AssumeRoleWithWebIdentityResponse", {})
.get("AssumeRoleWithWebIdentityResult", {})
.get("Credentials", {})
)
if all(k in creds for k in ["AccessKeyId", "SecretAccessKey", "SessionToken"]):
return {
"AccessKeyId": creds["AccessKeyId"],
"SecretAccessKey": creds["SecretAccessKey"],
"Token": creds["SessionToken"],
}, "webidentity:" + ",".join([role_arn, token_file])
# Fail if credentials cannot be fetched from the given aws_creds_uri
if is_fatal:
fatal_error(unsuccessful_resp, unsuccessful_resp)
else:
return None, None
def get_aws_security_credentials_from_instance_metadata(config, iam_role_name):
security_creds_lookup_url = INSTANCE_IAM_URL + iam_role_name
unsuccessful_resp = (
"Unsuccessful retrieval of AWS security credentials at %s."
% security_creds_lookup_url
)
url_error_msg = (
"Unable to reach %s to retrieve AWS security credentials. See %s for more info."
% (security_creds_lookup_url, SECURITY_CREDS_IAM_ROLE_HELP_URL)
)
iam_security_dict = url_request_helper(
config, security_creds_lookup_url, unsuccessful_resp, url_error_msg
)
if iam_security_dict and all(k in iam_security_dict for k in CREDENTIALS_KEYS):
return iam_security_dict, "metadata:"
else:
return None, None
def get_iam_role_name(config):
iam_role_unsuccessful_resp = (
"Unsuccessful retrieval of IAM role name at %s." % INSTANCE_IAM_URL
)
iam_role_url_error_msg = (
"Unable to reach %s to retrieve IAM role name. See %s for more info."
% (INSTANCE_IAM_URL, SECURITY_CREDS_IAM_ROLE_HELP_URL)
)
iam_role_name = url_request_helper(
config, INSTANCE_IAM_URL, iam_role_unsuccessful_resp, iam_role_url_error_msg
)
return iam_role_name
def credentials_file_helper(file_path, awsprofile):
aws_credentials_configs = read_config(file_path)
credentials = {"AccessKeyId": None, "SecretAccessKey": None, "Token": None}
try:
access_key = aws_credentials_configs.get(awsprofile, "aws_access_key_id")
secret_key = aws_credentials_configs.get(awsprofile, "aws_secret_access_key")
session_token = aws_credentials_configs.get(awsprofile, "aws_session_token")
credentials["AccessKeyId"] = access_key
credentials["SecretAccessKey"] = secret_key
credentials["Token"] = session_token
except NoOptionError as e:
if "aws_access_key_id" in str(e) or "aws_secret_access_key" in str(e):
logging.debug(
"aws_access_key_id or aws_secret_access_key not found in %s under named profile [%s]",
file_path,
awsprofile,
)
if "aws_session_token" in str(e):
logging.debug("aws_session_token not found in %s", file_path)
credentials["AccessKeyId"] = aws_credentials_configs.get(
awsprofile, "aws_access_key_id"
)
credentials["SecretAccessKey"] = aws_credentials_configs.get(
awsprofile, "aws_secret_access_key"
)
except NoSectionError:
logging.debug("No [%s] section found in config file %s", awsprofile, file_path)
return credentials
def botocore_credentials_helper(awsprofile):
# This method retrieves credentials from aws named profile using botocore, botocore will then assume that named profile, get
# and return the credentials
credentials = {"AccessKeyId": None, "SecretAccessKey": None, "Token": None}
if not BOTOCORE_PRESENT:
logging.error(
"Cannot find credentials for %s, to assume this profile, please install botocore first."
% awsprofile
)
return credentials
session = botocore.session.get_session()
session.set_config_variable("profile", awsprofile)
try:
frozen_credentials = session.get_credentials().get_frozen_credentials()
except ProfileNotFound as e:
fatal_error(
"%s, please add the [profile %s] section in the aws config file following %s and %s."
% (e, awsprofile, NAMED_PROFILE_HELP_URL, CONFIG_FILE_SETTINGS_HELP_URL)
)
credentials["AccessKeyId"] = frozen_credentials.access_key
credentials["SecretAccessKey"] = frozen_credentials.secret_key
credentials["Token"] = frozen_credentials.token
return credentials
def get_aws_profile(options, use_iam):
awsprofile = options.get("awsprofile")
if not awsprofile and use_iam:
for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]:
aws_credentials_configs = read_config(file_path)
# check if aws access key id is found under [default] section in current file and return 'default' if so
try:
access_key = aws_credentials_configs.get("default", "aws_access_key_id")
if access_key is not None:
return "default"
except (NoSectionError, NoOptionError):
continue
return awsprofile
def is_instance_metadata_url(url):
return url.startswith("http://169.254.169.254")