__init__.py 53.3 KB
Newer Older
Max Beckett's avatar
Max Beckett committed
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
#!/usr/bin/env python
#
# 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.

33
import base64
34
import errno
35
36
37
import hashlib
import hmac
import itertools
Max Beckett's avatar
Max Beckett committed
38
39
40
import json
import logging
import os
41
import pwd
Max Beckett's avatar
Max Beckett committed
42
43
44
45
46
47
import random
import re
import socket
import subprocess
import sys
import threading
48
import time
Max Beckett's avatar
Max Beckett committed
49
50

from contextlib import contextmanager
51
from datetime import datetime, timedelta
Max Beckett's avatar
Max Beckett committed
52
53
from logging.handlers import RotatingFileHandler

Yuan Gao's avatar
Yuan Gao committed
54
try:
55
56
57
58
    import ConfigParser
    from ConfigParser import NoOptionError, NoSectionError
except ImportError:
    from configparser import ConfigParser, NoOptionError, NoSectionError
Yuan Gao's avatar
Yuan Gao committed
59

Max Beckett's avatar
Max Beckett committed
60
try:
61
    from urllib.parse import quote_plus
Max Beckett's avatar
Max Beckett committed
62
except ImportError:
63
    from urllib import quote_plus
Max Beckett's avatar
Max Beckett committed
64
65

try:
66
    from urllib2 import URLError, HTTPError, build_opener, urlopen, Request, HTTPHandler
Max Beckett's avatar
Max Beckett committed
67
except ImportError:
68
69
    from urllib.request import urlopen, Request
    from urllib.error import URLError, HTTPError
Max Beckett's avatar
Max Beckett committed
70

71

72
VERSION = '1.23'
73
SERVICE = 'elasticfilesystem'
Max Beckett's avatar
Max Beckett committed
74
75
76
77
78
79
80
81
82

CONFIG_FILE = '/etc/amazon/efs/efs-utils.conf'
CONFIG_SECTION = 'mount'

LOG_DIR = '/var/log/amazon/efs'
LOG_FILE = 'mount.log'

STATE_FILE_DIR = '/var/run/efs'

83
84
85
86
87
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'

88
89
90
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'))

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
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
"""

# 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 = ''

136
FS_ID_RE = re.compile('^(?P<fs_id>fs-[0-9a-f]+)$')
137
EFS_FQDN_RE = re.compile(r'^(?P<fs_id>fs-[0-9a-f]+)\.efs\.(?P<region>[a-z0-9-]+)\.(?P<dns_name_suffix>[a-z0-9.]+)$')
138
AP_ID_RE = re.compile('^fsap-[0-9a-f]{17}$')
Max Beckett's avatar
Max Beckett committed
139

140
141
CREDENTIALS_KEYS = ['AccessKeyId', 'SecretAccessKey', 'Token']
ECS_URI_ENV = 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI'
142
143
ECS_TASK_METADATA_API = 'http://169.254.170.2'
INSTANCE_METADATA_TOKEN_URL = 'http://169.254.169.254/latest/api/token'
Max Beckett's avatar
Max Beckett committed
144
INSTANCE_METADATA_SERVICE_URL = 'http://169.254.169.254/latest/dynamic/instance-identity/document/'
145
146
147
INSTANCE_IAM_URL = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/'
SECURITY_CREDS_ECS_URI_HELP_URL = 'https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html'
SECURITY_CREDS_IAM_ROLE_HELP_URL = 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html'
Max Beckett's avatar
Max Beckett committed
148
149

DEFAULT_STUNNEL_VERIFY_LEVEL = 2
Ian Patel's avatar
Ian Patel committed
150
DEFAULT_STUNNEL_CAFILE = '/etc/amazon/efs/efs-utils.crt'
Max Beckett's avatar
Max Beckett committed
151

152
153
154
NOT_BEFORE_MINS = 15
NOT_AFTER_HOURS = 3

Max Beckett's avatar
Max Beckett committed
155
EFS_ONLY_OPTIONS = [
156
    'accesspoint',
157
    'awscredsuri',
158
159
    'awsprofile',
    'cafile',
160
161
162
163
    'iam',
    'netns',
    'noocsp',
    'ocsp',
Max Beckett's avatar
Max Beckett committed
164
165
    'tls',
    'tlsport',
166
    'verify'
Max Beckett's avatar
Max Beckett committed
167
168
]

169
UNSUPPORTED_OPTIONS = [
170
    'capath'
171
172
]

Max Beckett's avatar
Max Beckett committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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',
189
    'TIMEOUTclose': '0',
Max Beckett's avatar
Max Beckett committed
190
    'TIMEOUTidle': '70',
Ian Patel's avatar
Ian Patel committed
191
    'delay': 'yes',
Max Beckett's avatar
Max Beckett committed
192
193
194
}

WATCHDOG_SERVICE = 'amazon-efs-mount-watchdog'
Max Beckett's avatar
Max Beckett committed
195
196
SYSTEM_RELEASE_PATH = '/etc/system-release'
RHEL8_RELEASE_NAME = 'Red Hat Enterprise Linux release 8'
Max Beckett's avatar
Max Beckett committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213


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)
    sys.exit(exit_code)


def get_region():
    """Return this instance's region via the instance metadata service."""
    def _fatal_error(message):
        fatal_error('Error retrieving region', message)

    try:
214
215
216
217
218
        token = get_aws_ec2_metadata_token()
        headers = {}
        if token:
            headers = {'X-aws-ec2-metadata-token': token}
        instance_identity = get_aws_ec2_metadata(headers)
Max Beckett's avatar
Max Beckett committed
219
220

        return instance_identity['region']
221
222
223
    except HTTPError as e:
        _fatal_error('Unable to reach instance metadata service at %s: status=%d'
                     % (INSTANCE_METADATA_SERVICE_URL, e.code))
Max Beckett's avatar
Max Beckett committed
224
    except URLError as e:
225
226
227
228
        _fatal_error('Unable to reach the instance metadata service at %s. If this is an on-premises instance, replace '
                     '"{region}" in the "dns_name_format" option in %s with the region of the EFS file system you are mounting.\n'
                     'See %s for more detail. %s'
                     % (INSTANCE_METADATA_SERVICE_URL, CONFIG_FILE, 'https://docs.aws.amazon.com/console/efs/direct-connect', e))
Max Beckett's avatar
Max Beckett committed
229
230
231
232
233
234
    except ValueError as e:
        _fatal_error('Error parsing json: %s' % (e,))
    except KeyError as e:
        _fatal_error('Region not present in %s: %s' % (instance_identity, e))


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
def get_aws_ec2_metadata_token():
    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'
        res = opener.open(request)
        return res.read()
    except NameError:
        headers = {'X-aws-ec2-metadata-token-ttl-seconds': 21600}
        req = Request(INSTANCE_METADATA_TOKEN_URL, headers=headers, method='PUT')
        res = urlopen(req)
        return res.read()


def get_aws_ec2_metadata(headers):
    request = Request(INSTANCE_METADATA_SERVICE_URL, headers=headers)
    response = urlopen(request, timeout=1)
    data = response.read()
    if type(data) is str:
        instance_identity = json.loads(data)
    else:
        instance_identity = json.loads(data.decode(response.headers.get_content_charset() or 'us-ascii'))
    return instance_identity


261
262
263
264
265
266
267
268
def get_region_helper(config):
    dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format')
    if '{region}' in dns_name_format:
        return get_region()
    else:
        return dns_name_format.split('.')[-3]


269
def get_aws_security_credentials(use_iam, awsprofile=None, aws_creds_uri=None):
270
271
272
273
274
    """
    Lookup AWS security credentials (access key ID and secret access key). 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
    """
275
276
277
    if not use_iam:
        return None, None

278
279
280
281
282
283
    # 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(aws_creds_uri, True)

    # attempt to lookup AWS security credentials in AWS credentials file (~/.aws/credentials)
    # and configs file (~/.aws/config) with given awsprofile
284
    if awsprofile:
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
        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(os.environ[ECS_URI_ENV], 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()
    if iam_role_name:
        credentials, credentials_source = get_aws_security_credentials_from_instance_metadata(iam_role_name)
        if credentials and credentials_source:
            return credentials, credentials_source
300

301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    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']:
                return credentials, os.path.basename(file_path) + ':' + awsprofile

    # Fail if credentials cannot be fetched from the given awsprofile
    if is_fatal:
316
        log_message = 'AWS security credentials not found in %s or %s under named profile [%s]' % \
317
                    (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE, awsprofile)
318
        fatal_error(log_message)
319
320
    else:
        return None, None
321

322

323
324
325
326
327
328
def get_aws_security_credentials_from_ecs(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(ecs_uri, ecs_unsuccessful_resp, ecs_url_error_msg)
329

330
331
    if ecs_security_dict and all(k in ecs_security_dict for k in CREDENTIALS_KEYS):
        return ecs_security_dict, 'ecs:' + aws_creds_uri
332

333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
    # 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_instance_metadata(iam_role_name):
    security_creds_lookup_url = INSTANCE_IAM_URL + str(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(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():
354
355
356
357
    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(INSTANCE_IAM_URL, iam_role_unsuccessful_resp, iam_role_url_error_msg)
358
    return iam_role_name
359
360


361
def credentials_file_helper(file_path, awsprofile):
362
363
364
365
    aws_credentials_configs = read_config(file_path)
    credentials = {'AccessKeyId': None, 'SecretAccessKey': None, 'Token': None}

    try:
366
367
368
        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')
369
370
371
372
373
374

        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):
375
376
            logging.debug('aws_access_key_id or aws_secret_access_key not found in %s under named profile [%s]', file_path,
                          awsprofile)
377
378
        if 'aws_session_token' in str(e):
            logging.debug('aws_session_token not found in %s', file_path)
379
380
            credentials['AccessKeyId'] = aws_credentials_configs.get(awsprofile, 'aws_access_key_id')
            credentials['SecretAccessKey'] = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key')
381
    except NoSectionError:
382
        logging.debug('No [%s] section found in config file %s', awsprofile, file_path)
383
384
385
386
387
388
389
390
391
392
393
394
395
396

    return credentials


def get_correct_default_case_combination(aws_credentials_configs):
    default_str = 'default'
    for perm in map(''.join, itertools.product(*zip(default_str.upper(), default_str.lower()))):
        try:
            access_key = aws_credentials_configs.get(perm, 'aws_access_key_id')
            if access_key is not None:
                return perm
        except (NoSectionError, NoOptionError):
            continue

397
398
399
400
401
402
403
404
405
406
407
408
409
    return None


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)
            awsprofile = get_correct_default_case_combination(aws_credentials_configs)
            if awsprofile:
                break

    return awsprofile
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


def url_request_helper(url, unsuccessful_resp, url_error_msg):
    try:
        request_resp = urlopen(url, timeout=1)

        if request_resp.getcode() != 200:
            logging.debug(unsuccessful_resp + ' %s: ResponseCode=%d', url, request_resp.getcode())
            return None

        resp_body = request_resp.read()
        try:
            if type(resp_body) is str:
                resp_dict = json.loads(resp_body)
            else:
                resp_dict = json.loads(resp_body.decode(request_resp.headers.get_content_charset() or 'us-ascii'))

            return resp_dict
        except ValueError as e:
            logging.debug('Error parsing json: %s, returning raw response body: %s' % (e, str(resp_body)))
            return resp_body
    except URLError as e:
        logging.debug('%s %s', url_error_msg, e)
        return None


Max Beckett's avatar
Max Beckett committed
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
def parse_options(options):
    opts = {}
    for o in options.split(','):
        if '=' in o:
            k, v = o.split('=')
            opts[k] = v
        else:
            opts[o] = None
    return opts


def get_tls_port_range(config):
    lower_bound = config.getint(CONFIG_SECTION, 'port_range_lower_bound')
    upper_bound = config.getint(CONFIG_SECTION, 'port_range_upper_bound')

    if lower_bound >= upper_bound:
        fatal_error('Configuration option "port_range_upper_bound" defined as %d '
                    'must be strictly greater than "port_range_lower_bound" defined as %d.'
                    % (upper_bound, lower_bound))

    return lower_bound, upper_bound


459
460
def choose_tls_port(config, options):
    if 'tlsport' in options:
461
        ports_to_try = [int(options['tlsport'])]
462
463
    else:
        lower_bound, upper_bound = get_tls_port_range(config)
Max Beckett's avatar
Max Beckett committed
464

465
        tls_ports = list(range(lower_bound, upper_bound))
Max Beckett's avatar
Max Beckett committed
466

467
468
        # Choose a random midpoint, and then try ports in-order from there
        mid = random.randrange(len(tls_ports))
Max Beckett's avatar
Max Beckett committed
469

470
471
        ports_to_try = tls_ports[mid:] + tls_ports[:mid]
        assert len(tls_ports) == len(ports_to_try)
Max Beckett's avatar
Max Beckett committed
472

473
    sock = socket.socket()
Max Beckett's avatar
Max Beckett committed
474
475
476
477
478
479
480
481
    for tls_port in ports_to_try:
        try:
            sock.bind(('localhost', tls_port))
            sock.close()
            return tls_port
        except socket.error:
            continue

482
483
    sock.close()

484
485
486
487
488
489
490
491
    if 'tlsport' in options:
        fatal_error('Specified port [%s] is unavailable. Try selecting a different port.' % options['tlsport'])
    else:
        fatal_error('Failed to locate an available port in the range [%d, %d], try specifying a different port range in %s'
                    % (lower_bound, upper_bound, CONFIG_FILE))


def is_ocsp_enabled(config, options):
492
    if 'ocsp' in options:
493
494
495
496
497
        return True
    elif 'noocsp' in options:
        return False
    else:
        return config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_validity')
Max Beckett's avatar
Max Beckett committed
498
499
500


def get_mount_specific_filename(fs_id, mountpoint, tls_port):
Ian Patel's avatar
Ian Patel committed
501
    return '%s.%s.%d' % (fs_id, os.path.abspath(mountpoint).replace(os.sep, '.').lstrip('.'), tls_port)
Max Beckett's avatar
Max Beckett committed
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519


def serialize_stunnel_config(config, header=None):
    lines = []

    if header:
        lines.append('[%s]' % header)

    for k, v in config.items():
        if type(v) is list:
            for item in v:
                lines.append('%s = %s' % (k, item))
        else:
            lines.append('%s = %s' % (k, v))

    return lines


520
521
522
523
524
525
526
527
528
529
def add_stunnel_ca_options(efs_config, config, options):
    if 'cafile' in options:
        stunnel_cafile = options['cafile']
    else:
        try:
            stunnel_cafile = config.get(CONFIG_SECTION, 'stunnel_cafile')
        except NoOptionError:
            logging.debug('No CA file configured, using default CA file %s', DEFAULT_STUNNEL_CAFILE)
            stunnel_cafile = DEFAULT_STUNNEL_CAFILE

Ian Patel's avatar
Ian Patel committed
530
    if not os.path.exists(stunnel_cafile):
531
532
533
        fatal_error('Failed to find certificate authority file for verification',
                    'Failed to find CAfile "%s"' % stunnel_cafile)

Ian Patel's avatar
Ian Patel committed
534
535
536
537
538
539
540
541
542
543
544
    efs_config['CAfile'] = stunnel_cafile


def is_stunnel_option_supported(stunnel_output, stunnel_option_name):
    supported = False
    for line in stunnel_output:
        if line.startswith(stunnel_option_name):
            supported = True
            break

    if not supported:
Yuan Gao's avatar
Yuan Gao committed
545
        logging.warning('stunnel does not support "%s"', stunnel_option_name)
Ian Patel's avatar
Ian Patel committed
546
547
548
549
550

    return supported


def get_version_specific_stunnel_options(config):
551
    proc = subprocess.Popen(['stunnel', '-help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
Ian Patel's avatar
Ian Patel committed
552
553
    proc.wait()
    _, err = proc.communicate()
Max Beckett's avatar
Max Beckett committed
554

Ian Patel's avatar
Ian Patel committed
555
    stunnel_output = err.splitlines()
Max Beckett's avatar
Max Beckett committed
556

Ian Patel's avatar
Ian Patel committed
557
    check_host_supported = is_stunnel_option_supported(stunnel_output, 'checkHost')
558
    ocsp_aia_supported = is_stunnel_option_supported(stunnel_output, 'OCSPaia')
Ian Patel's avatar
Ian Patel committed
559

560
    return check_host_supported, ocsp_aia_supported
Ian Patel's avatar
Ian Patel committed
561
562


Max Beckett's avatar
Max Beckett committed
563
564
565
566
567
568
569
570
571
572
573
def get_system_release_version():
    system_release_version = 'unknown'
    try:
        with open(SYSTEM_RELEASE_PATH) as f:
            system_release_version = f.read().strip()
    except IOError:
        logging.debug('Unable to read %s', SYSTEM_RELEASE_PATH)

    return system_release_version


574
def write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level, ocsp_enabled,
575
                              options, log_dir=LOG_DIR, cert_details=None):
Max Beckett's avatar
Max Beckett committed
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
    """
    Serializes stunnel configuration to a file. Unfortunately this does not conform to Python's config file format, so we have to
    hand-serialize it.
    """

    mount_filename = get_mount_specific_filename(fs_id, mountpoint, tls_port)

    global_config = dict(STUNNEL_GLOBAL_CONFIG)
    if config.getboolean(CONFIG_SECTION, 'stunnel_debug_enabled'):
        global_config['debug'] = 'debug'
        global_config['output'] = os.path.join(log_dir, '%s.stunnel.log' % mount_filename)

    efs_config = dict(STUNNEL_EFS_CONFIG)
    efs_config['accept'] = efs_config['accept'] % tls_port
    efs_config['connect'] = efs_config['connect'] % dns_name
Ian Patel's avatar
Ian Patel committed
591
592
    efs_config['verify'] = verify_level
    if verify_level > 0:
593
594
595
596
597
        add_stunnel_ca_options(efs_config, config, options)

    if cert_details:
        efs_config['cert'] = cert_details['certificate']
        efs_config['key'] = cert_details['privateKey']
Ian Patel's avatar
Ian Patel committed
598

599
    check_host_supported, ocsp_aia_supported = get_version_specific_stunnel_options(config)
Ian Patel's avatar
Ian Patel committed
600
601
602
603

    tls_controls_message = 'WARNING: Your client lacks sufficient controls to properly enforce TLS. Please upgrade stunnel, ' \
        'or disable "%%s" in %s.\nSee %s for more detail.' % (CONFIG_FILE,
                                                              'https://docs.aws.amazon.com/console/efs/troubleshooting-tls')
Max Beckett's avatar
Max Beckett committed
604

605
606
607
608
609
    if config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_hostname'):
        if check_host_supported:
            efs_config['checkHost'] = dns_name
        else:
            fatal_error(tls_controls_message % 'stunnel_check_cert_hostname')
Max Beckett's avatar
Max Beckett committed
610

611
612
    # Only use the config setting if the override is not set
    if ocsp_enabled:
613
614
615
616
        if ocsp_aia_supported:
            efs_config['OCSPaia'] = 'yes'
        else:
            fatal_error(tls_controls_message % 'stunnel_check_cert_validity')
Max Beckett's avatar
Max Beckett committed
617

Max Beckett's avatar
Max Beckett committed
618
619
620
    if RHEL8_RELEASE_NAME not in get_system_release_version():
        efs_config['libwrap'] = 'no'

Max Beckett's avatar
Max Beckett committed
621
622
623
624
625
626
627
628
629
630
631
    stunnel_config = '\n'.join(serialize_stunnel_config(global_config) + serialize_stunnel_config(efs_config, 'efs'))
    logging.debug('Writing stunnel configuration:\n%s', stunnel_config)

    stunnel_config_file = os.path.join(state_file_dir, 'stunnel-config.%s' % mount_filename)

    with open(stunnel_config_file, 'w') as f:
        f.write(stunnel_config)

    return stunnel_config_file


632
def write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_pid, command, files, state_file_dir, cert_details=None):
Max Beckett's avatar
Max Beckett committed
633
634
635
636
637
638
639
640
641
642
643
644
    """
    Return the name of the temporary file containing TLS tunnel state, prefixed with a '~'. This file needs to be renamed to a
    non-temporary version following a successful mount.
    """
    state_file = '~' + get_mount_specific_filename(fs_id, mountpoint, tls_port)

    state = {
        'pid': tunnel_pid,
        'cmd': command,
        'files': files,
    }

645
646
647
    if cert_details:
        state.update(cert_details)

Max Beckett's avatar
Max Beckett committed
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
    with open(os.path.join(state_file_dir, state_file), 'w') as f:
        json.dump(state, f)

    return state_file


def test_tunnel_process(tunnel_proc, fs_id):
    tunnel_proc.poll()
    if tunnel_proc.returncode is not None:
        out, err = tunnel_proc.communicate()
        fatal_error('Failed to initialize TLS tunnel for %s' % fs_id,
                    'Failed to start TLS tunnel (errno=%d). stdout="%s" stderr="%s"'
                    % (tunnel_proc.returncode, out.strip(), err.strip()))


def poll_tunnel_process(tunnel_proc, fs_id, mount_completed):
    """
    poll the tunnel process health every .5s during the mount attempt to fail fast if the tunnel dies - since this is not called
    from the main thread, if the tunnel fails, exit uncleanly with os._exit
    """
    while not mount_completed.is_set():
        try:
            test_tunnel_process(tunnel_proc, fs_id)
        except SystemExit as e:
            os._exit(e.code)
        mount_completed.wait(.5)


def get_init_system(comm_file='/proc/1/comm'):
    init_system = 'unknown'
    try:
        with open(comm_file) as f:
            init_system = f.read().strip()
    except IOError:
        logging.warning('Unable to read %s', comm_file)

    logging.debug('Identified init system: %s', init_system)
    return init_system


Yuan Gao's avatar
Yuan Gao committed
688
def check_network_target(fs_id):
Max Beckett's avatar
Max Beckett committed
689
    with open(os.devnull, 'w') as devnull:
690
        rc = subprocess.call(['systemctl', 'status', 'network.target'], stdout=devnull, stderr=devnull, close_fds=True)
Max Beckett's avatar
Max Beckett committed
691
692
693
694
695
696

    if rc != 0:
        fatal_error('Failed to mount %s because the network was not yet available, add "_netdev" to your mount options' % fs_id,
                    exit_code=0)


Yuan Gao's avatar
Yuan Gao committed
697
698
699
700
701
702
703
704
def check_network_status(fs_id, init_system):
    if init_system != 'systemd':
        logging.debug('Not testing network on non-systemd init systems')
        return

    check_network_target(fs_id)


Max Beckett's avatar
Max Beckett committed
705
706
def start_watchdog(init_system):
    if init_system == 'init':
707
708
        proc = subprocess.Popen(
                ['/sbin/status', WATCHDOG_SERVICE], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
Ian Patel's avatar
Ian Patel committed
709
        status, _ = proc.communicate()
Max Beckett's avatar
Max Beckett committed
710
711
        if 'stop' in status:
            with open(os.devnull, 'w') as devnull:
712
                subprocess.Popen(['/sbin/start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True)
Max Beckett's avatar
Max Beckett committed
713
714
715
716
        elif 'start' in status:
            logging.debug('%s is already running', WATCHDOG_SERVICE)

    elif init_system == 'systemd':
717
        rc = subprocess.call(['systemctl', 'is-active', '--quiet', WATCHDOG_SERVICE], close_fds=True)
Max Beckett's avatar
Max Beckett committed
718
719
        if rc != 0:
            with open(os.devnull, 'w') as devnull:
720
                subprocess.Popen(['systemctl', 'start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True)
Max Beckett's avatar
Max Beckett committed
721
722
723
724
725
726
727
728
729
        else:
            logging.debug('%s is already running', WATCHDOG_SERVICE)

    else:
        error_message = 'Could not start %s, unrecognized init system "%s"' % (WATCHDOG_SERVICE, init_system)
        sys.stderr.write('%s\n' % error_message)
        logging.warning(error_message)


730
def create_required_directory(config, directory):
731
732
733
734
735
736
    mode = 0o750
    try:
        mode_str = config.get(CONFIG_SECTION, 'state_file_dir_mode')
        try:
            mode = int(mode_str, 8)
        except ValueError:
Yuan Gao's avatar
Yuan Gao committed
737
738
            logging.warning('Bad state_file_dir_mode "%s" in config file "%s"', mode_str, CONFIG_FILE)
    except NoOptionError:
739
740
        pass

741
    try:
742
        os.makedirs(directory, mode)
743
    except OSError as e:
744
        if errno.EEXIST != e.errno or not os.path.isdir(directory):
745
            raise
746
747


Max Beckett's avatar
Max Beckett committed
748
@contextmanager
749
def bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options, state_file_dir=STATE_FILE_DIR):
750
751
752
    tls_port = choose_tls_port(config, options)
    # override the tlsport option so that we can later override the port the NFS client uses to connect to stunnel.
    # if the user has specified tlsport=X at the command line this will just re-set tlsport to X.
Max Beckett's avatar
Max Beckett committed
753
    options['tlsport'] = tls_port
754

755
    use_iam = 'iam' in options
756
    ap_id = options.get('accesspoint')
757
758
759
    cert_details = {}

    if use_iam or ap_id:
760
761
762
763
764
765
766
        aws_creds_uri = options.get('awscredsuri')
        if aws_creds_uri:
            kwargs = {'aws_creds_uri': aws_creds_uri}
        else:
            kwargs = {'awsprofile': get_aws_profile(options, use_iam)}

        security_credentials, credentials_source = get_aws_security_credentials(use_iam, **kwargs)
767

768
769
770
771
772
773
774
        # additional symbol appended to avoid naming collisions
        cert_details['mountStateDir'] = get_mount_specific_filename(fs_id, mountpoint, tls_port) + '+'
        # common name for certificate signing request is max 64 characters
        cert_details['commonName'] = socket.gethostname()[0:64]
        cert_details['region'] = get_region_helper(config)
        cert_details['certificateCreationTime'] = create_certificate(config, cert_details['mountStateDir'],
                                                                     cert_details['commonName'], cert_details['region'], fs_id,
775
                                                                     security_credentials, ap_id=ap_id, base_path=state_file_dir)
776
777
778
779
        cert_details['certificate'] = os.path.join(state_file_dir, cert_details['mountStateDir'], 'certificate.pem')
        cert_details['privateKey'] = get_private_key_path()
        cert_details['fsId'] = fs_id

780
781
        if credentials_source:
            cert_details['awsCredentialsMethod'] = credentials_source
782

783
784
        if ap_id:
            cert_details['accessPoint'] = ap_id
785
786
787
788
789
790

    start_watchdog(init_system)

    if not os.path.exists(state_file_dir):
        create_required_directory(config, state_file_dir)

Ian Patel's avatar
Ian Patel committed
791
    verify_level = int(options.get('verify', DEFAULT_STUNNEL_VERIFY_LEVEL))
792
    ocsp_enabled = is_ocsp_enabled(config, options)
Max Beckett's avatar
Max Beckett committed
793

794
    stunnel_config_file = write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level,
795
                                                    ocsp_enabled, options, cert_details=cert_details)
Max Beckett's avatar
Max Beckett committed
796
    tunnel_args = ['stunnel', stunnel_config_file]
797
798
    if 'netns' in options:
        tunnel_args = ['nsenter', '--net=' + options['netns']] + tunnel_args
Max Beckett's avatar
Max Beckett committed
799
800
801

    # launch the tunnel in a process group so if it has any child processes, they can be killed easily by the mount watchdog
    logging.info('Starting TLS tunnel: "%s"', ' '.join(tunnel_args))
802
803
    tunnel_proc = subprocess.Popen(
            tunnel_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid, close_fds=True)
Max Beckett's avatar
Max Beckett committed
804
805
806
    logging.info('Started TLS tunnel, pid: %d', tunnel_proc.pid)

    temp_tls_state_file = write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_proc.pid, tunnel_args,
807
                                                      [stunnel_config_file], state_file_dir, cert_details=cert_details)
Max Beckett's avatar
Max Beckett committed
808
809
810
811
812
813
814
815

    try:
        yield tunnel_proc
    finally:
        os.rename(os.path.join(state_file_dir, temp_tls_state_file), os.path.join(state_file_dir, temp_tls_state_file[1:]))


def get_nfs_mount_options(options):
816
    # If you change these options, update the man page as well at man/mount.efs.8
Max Beckett's avatar
Max Beckett committed
817
818
819
820
821
822
823
824
825
826
827
828
    if 'nfsvers' not in options and 'vers' not in options:
        options['nfsvers'] = '4.1'
    if 'rsize' not in options:
        options['rsize'] = '1048576'
    if 'wsize' not in options:
        options['wsize'] = '1048576'
    if 'soft' not in options and 'hard' not in options:
        options['hard'] = None
    if 'timeo' not in options:
        options['timeo'] = '600'
    if 'retrans' not in options:
        options['retrans'] = '2'
829
830
    if 'noresvport' not in options:
        options['noresvport'] = None
Max Beckett's avatar
Max Beckett committed
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845

    if 'tls' in options:
        options['port'] = options['tlsport']

    def to_nfs_option(k, v):
        if v is None:
            return k
        return '%s=%s' % (str(k), str(v))

    nfs_options = [to_nfs_option(k, v) for k, v in options.items() if k not in EFS_ONLY_OPTIONS]

    return ','.join(nfs_options)


def mount_nfs(dns_name, path, mountpoint, options):
846

Max Beckett's avatar
Max Beckett committed
847
848
849
850
851
    if 'tls' in options:
        mount_path = '127.0.0.1:%s' % path
    else:
        mount_path = '%s:%s' % (dns_name, path)

Ian Patel's avatar
Ian Patel committed
852
    command = ['/sbin/mount.nfs4', mount_path, mountpoint, '-o', get_nfs_mount_options(options)]
Max Beckett's avatar
Max Beckett committed
853

854
855
856
    if 'netns' in options:
        command = ['nsenter', '--net=' + options['netns']] + command

Max Beckett's avatar
Max Beckett committed
857
858
    logging.info('Executing: "%s"', ' '.join(command))

859
    proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
Ian Patel's avatar
Ian Patel committed
860
    out, err = proc.communicate()
Max Beckett's avatar
Max Beckett committed
861

Ian Patel's avatar
Ian Patel committed
862
    if proc.returncode == 0:
Max Beckett's avatar
Max Beckett committed
863
864
        logging.info('Successfully mounted %s at %s', dns_name, mountpoint)
    else:
Ian Patel's avatar
Ian Patel committed
865
866
        message = 'Failed to mount %s at %s: returncode=%d, stderr="%s"' % (dns_name, mountpoint, proc.returncode, err.strip())
        fatal_error(err.strip(), message, proc.returncode)
Max Beckett's avatar
Max Beckett committed
867
868


Ian Patel's avatar
Ian Patel committed
869
870
871
872
873
874
875
def usage(out, exit_code=1):
    out.write('Usage: mount.efs [--version] [-h|--help] <fsname> <mountpoint> [-o <options>]\n')
    sys.exit(exit_code)


def parse_arguments_early_exit(args=None):
    """Parse arguments, checking for early exit conditions only"""
Max Beckett's avatar
Max Beckett committed
876
877
878
879
880
881
882
    if args is None:
        args = sys.argv

    if '-h' in args[1:] or '--help' in args[1:]:
        usage(out=sys.stdout, exit_code=0)

    if '--version' in args[1:]:
Ian Patel's avatar
Ian Patel committed
883
        sys.stdout.write('%s Version: %s\n' % (args[0], VERSION))
Max Beckett's avatar
Max Beckett committed
884
885
        sys.exit(0)

Ian Patel's avatar
Ian Patel committed
886
887
888
889
890
891

def parse_arguments(config, args=None):
    """Parse arguments, return (fsid, path, mountpoint, options)"""
    if args is None:
        args = sys.argv

Max Beckett's avatar
Max Beckett committed
892
893
894
895
896
897
898
899
    fsname = None
    mountpoint = None
    options = {}

    if len(args) > 1:
        fsname = args[1]
    if len(args) > 2:
        mountpoint = args[2]
900
901
902
    if len(args) > 4 and '-o' in args[:-1]:
        options_index = args.index('-o') + 1
        options = parse_options(args[options_index])
Max Beckett's avatar
Max Beckett committed
903
904

    if not fsname or not mountpoint:
Ian Patel's avatar
Ian Patel committed
905
        usage(out=sys.stderr)
Max Beckett's avatar
Max Beckett committed
906

907
    fs_id, path = match_device(config, fsname)
Max Beckett's avatar
Max Beckett committed
908
909
910
911

    return fs_id, path, mountpoint, options


912
def create_certificate(config, mount_name, common_name, region, fs_id, security_credentials, ap_id, base_path=STATE_FILE_DIR):
913
914
915
916
917
918
919
920
921
922
923
924
    current_time = get_utc_now()
    tls_paths = tls_paths_dictionary(mount_name, base_path)

    certificate_config = os.path.join(tls_paths['mount_dir'], 'config.conf')
    certificate_signing_request = os.path.join(tls_paths['mount_dir'], 'request.csr')
    certificate = os.path.join(tls_paths['mount_dir'], 'certificate.pem')

    ca_dirs_check(config, tls_paths['database_dir'], tls_paths['certs_dir'])
    ca_supporting_files_check(tls_paths['index'], tls_paths['index_attr'], tls_paths['serial'], tls_paths['rand'])

    private_key = check_and_create_private_key(base_path)

925
    if security_credentials:
926
927
928
        public_key = os.path.join(tls_paths['mount_dir'], 'publicKey.pem')
        create_public_key(private_key, public_key)

929
930
    create_ca_conf(certificate_config, common_name, tls_paths['mount_dir'], private_key, current_time, region, fs_id,
                   security_credentials, ap_id)
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
    create_certificate_signing_request(certificate_config, private_key, certificate_signing_request)

    not_before = get_certificate_timestamp(current_time, minutes=-NOT_BEFORE_MINS)
    not_after = get_certificate_timestamp(current_time, hours=NOT_AFTER_HOURS)

    cmd = 'openssl ca -startdate %s -enddate %s -selfsign -batch -notext -config %s -in %s -out %s' % \
          (not_before, not_after, certificate_config, certificate_signing_request, certificate)
    subprocess_call(cmd, 'Failed to create self-signed client-side certificate')
    return current_time.strftime(CERT_DATETIME_FORMAT)


def get_private_key_path():
    """Wrapped for mocking purposes in unit tests"""
    return PRIVATE_KEY_FILE


def check_and_create_private_key(base_path=STATE_FILE_DIR):
    # Creating RSA private keys is slow, so we will create one private key and allow mounts to share it.
    # This means, however, that we have to include a locking mechanism to ensure that the private key is
    # atomically created, as mounts occurring in parallel may try to create the key simultaneously.
    key = get_private_key_path()

    @contextmanager
    def open_lock_file():
        lock_file = os.path.join(base_path, 'efs-utils-lock')
        f = os.open(lock_file, os.O_CREAT | os.O_DSYNC | os.O_EXCL | os.O_RDWR)
        try:
            lock_file_contents = 'PID: %s' % os.getpid()
            os.write(f, lock_file_contents.encode('utf-8'))
            yield f
        finally:
            os.close(f)
            os.remove(lock_file)

    def do_with_lock(function):
        while True:
            try:
                with open_lock_file():
                    return function()
            except OSError as e:
                if e.errno == errno.EEXIST:
                    logging.info('Failed to take out private key creation lock, sleeping 50 ms')
                    time.sleep(0.05)
                else:
                    raise

    def generate_key():
        if os.path.isfile(key):
            return

        cmd = 'openssl genpkey -algorithm RSA -out %s -pkeyopt rsa_keygen_bits:3072' % key
        subprocess_call(cmd, 'Failed to create private key')
        read_only_mode = 0o400
        os.chmod(key, read_only_mode)

    do_with_lock(generate_key)
    return key


def create_certificate_signing_request(config_path, private_key, csr_path):
    cmd = 'openssl req -new -config %s -key %s -out %s' % (config_path, private_key, csr_path)
    subprocess_call(cmd, 'Failed to create certificate signing request (csr)')


995
def create_ca_conf(config_path, common_name, directory, private_key, date, region, fs_id, security_credentials, ap_id):
996
997
    """Populate ca/req configuration file with fresh configurations at every mount since SigV4 signature can change"""
    public_key_path = os.path.join(directory, 'publicKey.pem')
998
999
1000
1001
    ca_extension_body = ca_extension_builder(ap_id, security_credentials, fs_id) if security_credentials or ap_id else ''
    efs_client_auth_body = efs_client_auth_builder(public_key_path, security_credentials['AccessKeyId'],
                                                   security_credentials['SecretAccessKey'], date, region, fs_id,
                                                   security_credentials['Token']) if security_credentials else ''
1002
1003
1004
1005
1006
1007
1008
1009
    full_config_body = CA_CONFIG_BODY % (directory, private_key, common_name, ca_extension_body, efs_client_auth_body)

    with open(config_path, 'w') as f:
        f.write(full_config_body)

    return full_config_body


1010
def ca_extension_builder(ap_id, security_credentials, fs_id):
1011
1012
1013
    ca_extension_str = '[ v3_ca ]\nsubjectKeyIdentifier = hash'
    if ap_id:
        ca_extension_str += '\n1.3.6.1.4.1.4843.7.1 = ASN1:UTF8String:' + ap_id
1014
    if security_credentials:
1015
        ca_extension_str += '\n1.3.6.1.4.1.4843.7.2 = ASN1:SEQUENCE:efs_client_auth'
1016
1017

    ca_extension_str += '\n1.3.6.1.4.1.4843.7.3 = ASN1:UTF8String:' + fs_id
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089

    return ca_extension_str


def efs_client_auth_builder(public_key_path, access_key_id, secret_access_key, date, region, fs_id, session_token=None):
    public_key_hash = get_public_key_sha1(public_key_path)
    canonical_request = create_canonical_request(public_key_hash, date, access_key_id, region, fs_id, session_token)
    string_to_sign = create_string_to_sign(canonical_request, date, region)
    signature = calculate_signature(string_to_sign, date, secret_access_key, region)
    efs_client_auth_str = '[ efs_client_auth ]'
    efs_client_auth_str += '\naccessKeyId = UTF8String:' + access_key_id
    efs_client_auth_str += '\nsignature = OCTETSTRING:' + signature
    efs_client_auth_str += '\nsigv4DateTime = UTCTIME:' + date.strftime(CERT_DATETIME_FORMAT)

    if session_token:
        efs_client_auth_str += '\nsessionToken = EXPLICIT:0,UTF8String:' + session_token

    return efs_client_auth_str


def create_public_key(private_key, public_key):
    cmd = 'openssl rsa -in %s -outform PEM -pubout -out %s' % (private_key, public_key)
    subprocess_call(cmd, 'Failed to create public key')


def subprocess_call(cmd, error_message):
    """Helper method to run shell openssl command and to handle response error messages"""
    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
    (output, err) = process.communicate()
    rc = process.poll()
    if rc != 0:
        logging.error('Command %s failed, rc=%s, stdout="%s", stderr="%s"' % (cmd, rc, output, err))
        fatal_error(error_message, error_message)
    else:
        return output, err


def ca_dirs_check(config, database_dir, certs_dir):
    """Check if mount's database and certs directories exist and if not, create directories (also create all intermediate
    directories if they don't exist)."""
    if not os.path.exists(database_dir):
        create_required_directory(config, database_dir)
    if not os.path.exists(certs_dir):
        create_required_directory(config, certs_dir)


def ca_supporting_files_check(index_path, index_attr_path, serial_path, rand_path):
    """Recreate all supporting openssl ca and req files if they're not present in their respective directories"""
    if not os.path.isfile(index_path):
        open(index_path, 'w').close()
    if not os.path.isfile(index_attr_path):
        with open(index_attr_path, 'w+') as f:
            f.write('unique_subject = no')
    if not os.path.isfile(serial_path):
        with open(serial_path, 'w+') as f:
            f.write('00')
    if not os.path.isfile(rand_path):
        open(rand_path, 'w').close()


def get_certificate_timestamp(current_time, **kwargs):
    updated_time = current_time + timedelta(**kwargs)
    return updated_time.strftime(CERT_DATETIME_FORMAT)


def get_utc_now():
    """
    Wrapped for patching purposes in unit tests
    """
    return datetime.utcnow()


Max Beckett's avatar
Max Beckett committed
1090
def assert_root():
Ian Patel's avatar
Ian Patel committed
1091
    if os.geteuid() != 0:
Max Beckett's avatar
Max Beckett committed
1092
1093
1094
1095
1096
        sys.stderr.write('only root can run mount.efs\n')
        sys.exit(1)


def read_config(config_file=CONFIG_FILE):
Yuan Gao's avatar
Yuan Gao committed
1097
1098
1099
1100
    try:
        p = ConfigParser.SafeConfigParser()
    except AttributeError:
        p = ConfigParser()
Max Beckett's avatar
Max Beckett committed
1101
1102
1103
1104
1105
    p.read(config_file)
    return p


def bootstrap_logging(config, log_dir=LOG_DIR):
Ian Patel's avatar
Ian Patel committed
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
    raw_level = config.get(CONFIG_SECTION, 'logging_level')
    levels = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }
    level = levels.get(raw_level.lower())
    level_error = False

    if not level:
        # delay logging error about malformed log level until after logging is configured
        level_error = True
        level = logging.INFO

Max Beckett's avatar
Max Beckett committed
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
    max_bytes = config.getint(CONFIG_SECTION, 'logging_max_bytes')
    file_count = config.getint(CONFIG_SECTION, 'logging_file_count')

    handler = RotatingFileHandler(os.path.join(log_dir, LOG_FILE), maxBytes=max_bytes, backupCount=file_count)
    handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s'))

    logger = logging.getLogger()
    logger.setLevel(level)
    logger.addHandler(handler)

Ian Patel's avatar
Ian Patel committed
1132
1133
1134
    if level_error:
        logging.error('Malformed logging level "%s", setting logging level to %s', raw_level, level)

Max Beckett's avatar
Max Beckett committed
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147

def get_dns_name(config, fs_id):
    def _validate_replacement_field_count(format_str, expected_ct):
        if format_str.count('{') != expected_ct or format_str.count('}') != expected_ct:
            raise ValueError('DNS name format has an incorrect number of replacement fields')

    dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format')

    if '{fs_id}' not in dns_name_format:
        raise ValueError('DNS name format must include {fs_id}')

    format_args = {'fs_id': fs_id}

1148
1149
    expected_replacement_field_ct = 1

Max Beckett's avatar
Max Beckett committed
1150
    if '{region}' in dns_name_format:
1151
        expected_replacement_field_ct += 1
Max Beckett's avatar
Max Beckett committed
1152
        format_args['region'] = get_region()
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168

    if '{dns_name_suffix}' in dns_name_format:
        expected_replacement_field_ct += 1
        config_section = CONFIG_SECTION
        region = format_args.get('region')

        if region:
            region_specific_config_section = '%s.%s' % (CONFIG_SECTION, region)
            if config.has_section(region_specific_config_section):
                config_section = region_specific_config_section

        format_args['dns_name_suffix'] = config.get(config_section, 'dns_name_suffix')

        logging.debug("Using dns_name_suffix %s in config section [%s]", format_args.get('dns_name_suffix'), config_section)

    _validate_replacement_field_count(dns_name_format, expected_replacement_field_ct)
Max Beckett's avatar
Max Beckett committed
1169
1170
1171
1172
1173
1174
1175

    dns_name = dns_name_format.format(**format_args)

    try:
        socket.gethostbyname(dns_name)
    except socket.gaierror:
        fatal_error('Failed to resolve "%s" - check that your file system ID is correct.\nSee %s for more detail.'
Ian Patel's avatar
Ian Patel committed
1176
                    % (dns_name, 'https://docs.aws.amazon.com/console/efs/mount-dns-name'),
Max Beckett's avatar
Max Beckett committed
1177
1178
1179
1180
1181
                    'Failed to resolve "%s"' % dns_name)

    return dns_name


1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
def tls_paths_dictionary(mount_name, base_path=STATE_FILE_DIR):
    tls_dict = {
        'mount_dir': os.path.join(base_path, mount_name),
        # every mount will have its own ca mode assets due to lack of multi-threading support in openssl
        'database_dir': os.path.join(base_path, mount_name, 'database'),
        'certs_dir': os.path.join(base_path, mount_name, 'certs'),
        'index': os.path.join(base_path, mount_name, 'database/index.txt'),
        'index_attr': os.path.join(base_path, mount_name, 'database/index.txt.attr'),
        'serial': os.path.join(base_path, mount_name, 'database/serial'),
        'rand': os.path.join(base_path, mount_name, 'database/.rand')
    }

    return tls_dict


def get_public_key_sha1(public_key):
    # truncating public key to remove the header and footer '-----(BEGIN|END) PUBLIC KEY-----'
    with open(public_key, 'r') as f:
        lines = f.readlines()
        lines = lines[1:-1]

    key = ''.join(lines)
    key = bytearray(base64.b64decode(key))

    # Parse the public key to pull out the actual key material by looking for the key BIT STRING
    # Example:
    #     0:d=0  hl=4 l= 418 cons: SEQUENCE
    #     4:d=1  hl=2 l=  13 cons: SEQUENCE
    #     6:d=2  hl=2 l=   9 prim: OBJECT            :rsaEncryption
    #    17:d=2  hl=2 l=   0 prim: NULL
    #    19:d=1  hl=4 l= 399 prim: BIT STRING
    cmd = 'openssl asn1parse -inform PEM -in %s' % public_key
    output, err = subprocess_call(cmd, 'Unable to ASN1 parse public key file, %s, correctly' % public_key)

    key_line = ''
    for line in output.splitlines():
        if 'BIT STRING' in line.decode('utf-8'):
            key_line = line.decode('utf-8')

    if not key_line:
        err_msg = 'Public key file, %s, is incorrectly formatted' % public_key
        fatal_error(err_msg, err_msg)

    key_line = key_line.replace(' ', '')

    # DER encoding TLV (Tag, Length, Value)
    # - the first octet (byte) is the tag (type)
    # - the next octets are the length - "definite form"
    #   - the first octet always has the high order bit (8) set to 1
    #   - the remaining 127 bits are used to encode the number of octets that follow
    #   - the following octets encode, as big-endian, the length (which may be 0) as a number of octets
    # - the remaining octets are the "value" aka content
    #
    # For a BIT STRING, the first octet of the value is used to signify the number of unused bits that exist in the last
    # content byte. Note that this is explicitly excluded from the SubjectKeyIdentifier hash, per
    # https://tools.ietf.org/html/rfc5280#section-4.2.1.2
    #
    # Example:
    #   0382018f00...<subjectPublicKey>
    #   - 03 - BIT STRING tag
    #   - 82 - 2 length octets to follow (ignore high order bit)
    #   - 018f - length of 399
    #   - 00 - no unused bits in the last content byte
    offset = int(key_line.split(':')[0])
    key = key[offset:]

    num_length_octets = key[1] & 0b01111111

    # Exclude the tag (1), length (1 + num_length_octets), and number of unused bits (1)
    offset = 1 + 1 + num_length_octets + 1
    key = key[offset:]

    sha1 = hashlib.sha1()
    sha1.update(key)

    return sha1.hexdigest()


def create_canonical_request(public_key_hash, date, access_key, region, fs_id, session_token=None):
    """
    Create a Canonical Request - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
    """
    formatted_datetime = date.strftime(SIGV4_DATETIME_FORMAT)
    credential = quote_plus(access_key + '/' + get_credential_scope(date, region))

    request = HTTP_REQUEST_METHOD + '\n'
    request += CANONICAL_URI + '\n'
    request += create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token) + '\n'
    request += CANONICAL_HEADERS % fs_id + '\n'
    request += SIGNED_HEADERS + '\n'

    sha256 = hashlib.sha256()
    sha256.update(REQUEST_PAYLOAD.encode())
    request += sha256.hexdigest()

    return request


def create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token=None):
    canonical_query_params = {
        'Action': 'Connect',
        # Public key hash is included in canonical request to tie the signature to a specific key pair to avoid replay attacks
        'PublicKeyHash': quote_plus(public_key_hash),
        'X-Amz-Algorithm': ALGORITHM,
        'X-Amz-Credential': credential,
        'X-Amz-Date': quote_plus(formatted_datetime),
        'X-Amz-Expires': 86400,
        'X-Amz-SignedHeaders': SIGNED_HEADERS,
    }

    if session_token:
        canonical_query_params['X-Amz-Security-Token'] = quote_plus(session_token)

    # Cannot use urllib.urlencode because it replaces the %s's
    return '&'.join(['%s=%s' % (k, v) for k, v in sorted(canonical_query_params.items())])


def create_string_to_sign(canonical_request, date, region):
    """
    Create a String to Sign - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html
    """
    string_to_sign = ALGORITHM + '\n'
    string_to_sign += date.strftime(SIGV4_DATETIME_FORMAT) + '\n'
    string_to_sign += get_credential_scope(date, region) + '\n'

    sha256 = hashlib.sha256()
    sha256.update(canonical_request.encode())
    string_to_sign += sha256.hexdigest()

    return string_to_sign


def calculate_signature(string_to_sign, date, secret_access_key, region):
    """
    Calculate the Signature - https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html
    """
    def _sign(key, msg):
        return hmac.new(key, msg.encode('utf-8'), hashlib.sha256)

    key_date = _sign(('AWS4' + secret_access_key).encode('utf-8'), date.strftime(DATE_ONLY_FORMAT)).digest()
    add_region = _sign(key_date, region).digest()
    add_service = _sign(add_region, SERVICE).digest()
    signing_key = _sign(add_service, 'aws4_request').digest()

    return _sign(signing_key, string_to_sign).hexdigest()


def get_credential_scope(date, region):
    return '/'.join([date.strftime(DATE_ONLY_FORMAT), region, SERVICE, AWS4_REQUEST])


1333
def match_device(config, device):
1334
    """Return the EFS id and the remote path to mount"""
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346

    try:
        remote, path = device.split(':', 1)
    except ValueError:
        remote = device
        path = '/'

    if FS_ID_RE.match(remote):
        return remote, path

    try:
        primary, secondaries, _ = socket.gethostbyname_ex(remote)
Yuan Gao's avatar
Yuan Gao committed
1347
        hostnames = list(filter(lambda e: e is not None, [primary] + secondaries))
1348
1349
1350
1351
1352
1353
1354
1355
1356
    except socket.gaierror:
        fatal_error(
            'Failed to resolve "%s" - check that the specified DNS name is a CNAME record resolving to a valid EFS DNS '
            'name' % remote,
            'Failed to resolve "%s"' % remote
        )

    if not hostnames:
        fatal_error(
1357
            'The specified domain name "%s" did not resolve to an EFS mount target' % remote
1358
1359
1360
1361
        )

    for hostname in hostnames:
        efs_fqdn_match = EFS_FQDN_RE.match(hostname)
1362

1363
1364
1365
        if efs_fqdn_match:
            fs_id = efs_fqdn_match.group('fs_id')
            expected_dns_name = get_dns_name(config, fs_id)
1366

1367
            # check that the DNS name of the mount target matches exactly the DNS name the CNAME resolves to
1368
1369
1370
            if hostname == expected_dns_name:
                return fs_id, path
    else:
1371
        fatal_error('The specified CNAME "%s" did not resolve to a valid DNS name for an EFS mount target. '
Pit Kleyersburg's avatar
Pit Kleyersburg committed
1372
1373
                    'Please refer to the EFS documentation for mounting with DNS names for examples: %s'
                    % (remote, 'https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html'))
1374
1375


1376
1377
def mount_tls(config, init_system, dns_name, path, fs_id, mountpoint, options):
    with bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options) as tunnel_proc:
Max Beckett's avatar
Max Beckett committed
1378
1379
        mount_completed = threading.Event()
        t = threading.Thread(target=poll_tunnel_process, args=(tunnel_proc, fs_id, mount_completed))
1380
        t.daemon = True
Max Beckett's avatar
Max Beckett committed
1381
1382
1383
1384
1385
1386
        t.start()
        mount_nfs(dns_name, path, mountpoint, options)
        mount_completed.set()
        t.join()


1387
1388
1389
1390
1391
1392
def check_unsupported_options(options):
    for unsupported_option in UNSUPPORTED_OPTIONS:
        if unsupported_option in options:
            warn_message = 'The "%s" option is not supported and has been ignored, as amazon-efs-utils relies on a built-in ' \
                           'trust store.' % unsupported_option
            sys.stderr.write('WARN: %s\n' % warn_message)
Yuan Gao's avatar
Yuan Gao committed
1393
            logging.warning(warn_message)
1394
1395
1396
            del options[unsupported_option]


1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
def check_options_validity(options):
    if 'tls' in options:
        if 'port' in options:
            fatal_error('The "port" and "tls" options are mutually exclusive')

        if 'tlsport' in options:
            try:
                int(options['tlsport'])
            except ValueError:
                fatal_error('tlsport option [%s] is not an integer' % options['tlsport'])

        if 'ocsp' in options and 'noocsp' in options:
            fatal_error('The "ocsp" and "noocsp" options are mutually exclusive')

    if 'accesspoint' in options:
        if 'tls' not in options:
            fatal_error('The "tls" option is required when mounting via "accesspoint"')
        if not AP_ID_RE.match(options['accesspoint']):
            fatal_error('Access Point ID %s is malformed' % options['accesspoint'])

    if 'iam' in options and 'tls' not in options:
        fatal_error('The "tls" option is required when mounting via "iam"')

    if 'awsprofile' in options and 'iam' not in options:
        fatal_error('The "iam" option is required when mounting with named profile option, "awsprofile"')

1423
1424
1425
1426
1427
1428
    if 'awscredsuri' in options and 'iam' not in options:
        fatal_error('The "iam" option is required when mounting with "awscredsuri"')

    if 'awscredsuri' in options and 'awsprofile' in options:
        fatal_error('The "awscredsuri" and "awsprofile" options are mutually exclusive')

1429

Max Beckett's avatar
Max Beckett committed
1430
def main():
Ian Patel's avatar
Ian Patel committed
1431
1432
    parse_arguments_early_exit()

Max Beckett's avatar
Max Beckett committed
1433
1434
1435
1436
1437
    assert_root()

    config = read_config()
    bootstrap_logging(config)

1438
1439
    fs_id, path, mountpoint, options = parse_arguments(config)

Ian Patel's avatar
Ian Patel committed
1440
    logging.info('version=%s options=%s', VERSION, options)
1441
    check_unsupported_options(options)
1442
    check_options_validity(options)
Max Beckett's avatar
Max Beckett committed
1443
1444
1445
1446
1447
1448
1449

    init_system = get_init_system()
    check_network_status(fs_id, init_system)

    dns_name = get_dns_name(config, fs_id)

    if 'tls' in options:
1450
        mount_tls(config, init_system, dns_name, path, fs_id, mountpoint, options)
Max Beckett's avatar
Max Beckett committed
1451
1452
1453
1454
1455
1456
    else:
        mount_nfs(dns_name, path, mountpoint, options)


if '__main__' == __name__:
    main()