__init__.py 25 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 errno
Max Beckett's avatar
Max Beckett committed
34
35
36
37
38
39
40
41
42
43
44
45
46
import json
import logging
import os
import random
import re
import socket
import subprocess
import sys
import threading

from contextlib import contextmanager
from logging.handlers import RotatingFileHandler

Yuan Gao's avatar
Yuan Gao committed
47
48
49
50
51
try:
    from ConfigParser import NoOptionError
except Exception:
    from configparser import NoOptionError

Max Beckett's avatar
Max Beckett committed
52
53
54
55
56
57
58
59
60
61
62
try:
    import ConfigParser
except ImportError:
    from configparser import ConfigParser

try:
    from urllib2 import urlopen, URLError
except ImportError:
    from urllib.error import URLError
    from urllib.request import urlopen

Yuan Gao's avatar
Yuan Gao committed
63
VERSION = '1.17'
Max Beckett's avatar
Max Beckett committed
64
65
66
67
68
69
70
71
72

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'

73
FS_ID_RE = re.compile('^(?P<fs_id>fs-[0-9a-f]+)$')
Yuan Gao's avatar
Yuan Gao committed
74
EFS_FQDN_RE = re.compile(r'^(?P<fs_id>fs-[0-9a-f]+)\.efs\.(?P<region>[a-z0-9-]+)\.amazonaws.com$')
Max Beckett's avatar
Max Beckett committed
75
76
77
78

INSTANCE_METADATA_SERVICE_URL = 'http://169.254.169.254/latest/dynamic/instance-identity/document/'

DEFAULT_STUNNEL_VERIFY_LEVEL = 2
Ian Patel's avatar
Ian Patel committed
79
DEFAULT_STUNNEL_CAFILE = '/etc/amazon/efs/efs-utils.crt'
Max Beckett's avatar
Max Beckett committed
80
81
82
83

EFS_ONLY_OPTIONS = [
    'tls',
    'tlsport',
maxbecke's avatar
maxbecke committed
84
85
86
    'verify',
    'ocsp',
    'noocsp'
Max Beckett's avatar
Max Beckett committed
87
88
]

89
90
91
92
93
UNSUPPORTED_OPTIONS = [
    'cafile',
    'capath',
]

Max Beckett's avatar
Max Beckett committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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',
110
    'TIMEOUTclose': '0',
Max Beckett's avatar
Max Beckett committed
111
    'TIMEOUTidle': '70',
Ian Patel's avatar
Ian Patel committed
112
    'delay': 'yes',
Max Beckett's avatar
Max Beckett committed
113
114
115
}

WATCHDOG_SERVICE = 'amazon-efs-mount-watchdog'
Max Beckett's avatar
Max Beckett committed
116
117
SYSTEM_RELEASE_PATH = '/etc/system-release'
RHEL8_RELEASE_NAME = 'Red Hat Enterprise Linux release 8'
Max Beckett's avatar
Max Beckett committed
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


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:
        resource = urlopen(INSTANCE_METADATA_SERVICE_URL, timeout=1)

        if resource.getcode() != 200:
            _fatal_error('Unable to reach instance metadata service at %s: status=%d'
                         % (INSTANCE_METADATA_SERVICE_URL, resource.getcode()))

        data = resource.read()
        if type(data) is str:
            instance_identity = json.loads(data)
        else:
            instance_identity = json.loads(data.decode(resource.headers.get_content_charset() or 'us-ascii'))

        return instance_identity['region']
    except URLError as e:
149
150
151
152
        _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
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
    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))


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


182
183
184
185
186
187
188
189
def choose_tls_port(config, options):
    if 'tlsport' in options:
        try:
            ports_to_try = [int(options['tlsport'])]
        except ValueError:
            fatal_error('tlsport option [%s] is not an integer' % options['tlsport'])
    else:
        lower_bound, upper_bound = get_tls_port_range(config)
Max Beckett's avatar
Max Beckett committed
190

191
        tls_ports = list(range(lower_bound, upper_bound))
Max Beckett's avatar
Max Beckett committed
192

193
194
        # 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
195

196
197
        ports_to_try = tls_ports[mid:] + tls_ports[:mid]
        assert len(tls_ports) == len(ports_to_try)
Max Beckett's avatar
Max Beckett committed
198

199
    sock = socket.socket()
Max Beckett's avatar
Max Beckett committed
200
201
202
203
204
205
206
207
    for tls_port in ports_to_try:
        try:
            sock.bind(('localhost', tls_port))
            sock.close()
            return tls_port
        except socket.error:
            continue

208
209
    sock.close()

210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    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):
    if 'ocsp' in options and 'noocsp' in options:
        fatal_error('The "ocsp" and "noocsp" options are mutually exclusive')
    elif 'ocsp' in options:
        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
226
227
228


def get_mount_specific_filename(fs_id, mountpoint, tls_port):
Ian Patel's avatar
Ian Patel committed
229
    return '%s.%s.%d' % (fs_id, os.path.abspath(mountpoint).replace(os.sep, '.').lstrip('.'), tls_port)
Max Beckett's avatar
Max Beckett committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247


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


Ian Patel's avatar
Ian Patel committed
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def add_stunnel_ca_options(efs_config, stunnel_cafile=DEFAULT_STUNNEL_CAFILE):
    if not os.path.exists(stunnel_cafile):
        fatal_error('Failed to find the EFS certificate authority file for verification',
                    'Failed to find the EFS CAfile "%s"' % stunnel_cafile)
    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
263
        logging.warning('stunnel does not support "%s"', stunnel_option_name)
Ian Patel's avatar
Ian Patel committed
264
265
266
267
268

    return supported


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

Ian Patel's avatar
Ian Patel committed
273
    stunnel_output = err.splitlines()
Max Beckett's avatar
Max Beckett committed
274

Ian Patel's avatar
Ian Patel committed
275
    check_host_supported = is_stunnel_option_supported(stunnel_output, 'checkHost')
276
    ocsp_aia_supported = is_stunnel_option_supported(stunnel_output, 'OCSPaia')
Ian Patel's avatar
Ian Patel committed
277

278
    return check_host_supported, ocsp_aia_supported
Ian Patel's avatar
Ian Patel committed
279
280


Max Beckett's avatar
Max Beckett committed
281
282
283
284
285
286
287
288
289
290
291
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


292
293
def write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level, ocsp_enabled,
                              log_dir=LOG_DIR):
Max Beckett's avatar
Max Beckett committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
    """
    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
309
310
311
312
    efs_config['verify'] = verify_level
    if verify_level > 0:
        add_stunnel_ca_options(efs_config)

313
    check_host_supported, ocsp_aia_supported = get_version_specific_stunnel_options(config)
Ian Patel's avatar
Ian Patel committed
314
315
316
317

    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
318

319
320
321
322
323
    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
324

325
326
    # Only use the config setting if the override is not set
    if ocsp_enabled:
327
328
329
330
        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
331

Max Beckett's avatar
Max Beckett committed
332
333
334
    if RHEL8_RELEASE_NAME not in get_system_release_version():
        efs_config['libwrap'] = 'no'

Max Beckett's avatar
Max Beckett committed
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
    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


def write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_pid, command, files, state_file_dir):
    """
    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,
    }

    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
399
def check_network_target(fs_id):
Max Beckett's avatar
Max Beckett committed
400
    with open(os.devnull, 'w') as devnull:
401
        rc = subprocess.call(['systemctl', 'status', 'network.target'], stdout=devnull, stderr=devnull, close_fds=True)
Max Beckett's avatar
Max Beckett committed
402
403
404
405
406
407

    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
408
409
410
411
412
413
414
415
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
416
417
def start_watchdog(init_system):
    if init_system == 'init':
418
419
        proc = subprocess.Popen(
                ['/sbin/status', WATCHDOG_SERVICE], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
Ian Patel's avatar
Ian Patel committed
420
        status, _ = proc.communicate()
Max Beckett's avatar
Max Beckett committed
421
422
        if 'stop' in status:
            with open(os.devnull, 'w') as devnull:
423
                subprocess.Popen(['/sbin/start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True)
Max Beckett's avatar
Max Beckett committed
424
425
426
427
        elif 'start' in status:
            logging.debug('%s is already running', WATCHDOG_SERVICE)

    elif init_system == 'systemd':
428
        rc = subprocess.call(['systemctl', 'is-active', '--quiet', WATCHDOG_SERVICE], close_fds=True)
Max Beckett's avatar
Max Beckett committed
429
430
        if rc != 0:
            with open(os.devnull, 'w') as devnull:
431
                subprocess.Popen(['systemctl', 'start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True)
Max Beckett's avatar
Max Beckett committed
432
433
434
435
436
437
438
439
440
        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)


441
442
443
444
445
446
447
def create_state_file_dir(config, state_file_dir):
    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
448
449
            logging.warning('Bad state_file_dir_mode "%s" in config file "%s"', mode_str, CONFIG_FILE)
    except NoOptionError:
450
451
        pass

452
453
454
455
456
    try:
        os.makedirs(state_file_dir, mode)
    except OSError as e:
        if errno.EEXIST != e.errno or not os.path.isdir(state_file_dir):
            raise
457
458


Max Beckett's avatar
Max Beckett committed
459
460
461
462
463
@contextmanager
def bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options, state_file_dir=STATE_FILE_DIR):
    start_watchdog(init_system)

    if not os.path.exists(state_file_dir):
464
        create_state_file_dir(config, state_file_dir)
Max Beckett's avatar
Max Beckett committed
465

466
467
468
469
    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
470
    options['tlsport'] = tls_port
471

Ian Patel's avatar
Ian Patel committed
472
    verify_level = int(options.get('verify', DEFAULT_STUNNEL_VERIFY_LEVEL))
473
    ocsp_enabled = is_ocsp_enabled(config, options)
Max Beckett's avatar
Max Beckett committed
474

475
476
    stunnel_config_file = write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level,
                                                    ocsp_enabled)
Max Beckett's avatar
Max Beckett committed
477
478
479
480
481

    tunnel_args = ['stunnel', stunnel_config_file]

    # 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))
482
483
    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
484
485
486
487
488
489
490
491
492
493
494
495
    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,
                                                      [stunnel_config_file], state_file_dir)

    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):
496
    # If you change these options, update the man page as well at man/mount.efs.8
Max Beckett's avatar
Max Beckett committed
497
498
499
500
501
502
503
504
505
506
507
508
    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'
509
510
    if 'noresvport' not in options:
        options['noresvport'] = None
Max Beckett's avatar
Max Beckett committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532

    if 'tls' in options:
        if 'port' in options:
            fatal_error('The "port" and "tls" options are mutually exclusive')
        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):
    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
533
    command = ['/sbin/mount.nfs4', mount_path, mountpoint, '-o', get_nfs_mount_options(options)]
Max Beckett's avatar
Max Beckett committed
534
535
536

    logging.info('Executing: "%s"', ' '.join(command))

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

Ian Patel's avatar
Ian Patel committed
540
    if proc.returncode == 0:
Max Beckett's avatar
Max Beckett committed
541
542
        logging.info('Successfully mounted %s at %s', dns_name, mountpoint)
    else:
Ian Patel's avatar
Ian Patel committed
543
544
        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
545
546


Ian Patel's avatar
Ian Patel committed
547
548
549
550
551
552
553
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
554
555
556
557
558
559
560
    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
561
        sys.stdout.write('%s Version: %s\n' % (args[0], VERSION))
Max Beckett's avatar
Max Beckett committed
562
563
        sys.exit(0)

Ian Patel's avatar
Ian Patel committed
564
565
566
567
568
569

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
570
571
572
573
574
575
576
577
    fsname = None
    mountpoint = None
    options = {}

    if len(args) > 1:
        fsname = args[1]
    if len(args) > 2:
        mountpoint = args[2]
578
579
580
    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
581
582

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

585
    fs_id, path = match_device(config, fsname)
Max Beckett's avatar
Max Beckett committed
586
587
588
589
590

    return fs_id, path, mountpoint, options


def assert_root():
Ian Patel's avatar
Ian Patel committed
591
    if os.geteuid() != 0:
Max Beckett's avatar
Max Beckett committed
592
593
594
595
596
        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
597
598
599
600
    try:
        p = ConfigParser.SafeConfigParser()
    except AttributeError:
        p = ConfigParser()
Max Beckett's avatar
Max Beckett committed
601
602
603
604
605
    p.read(config_file)
    return p


def bootstrap_logging(config, log_dir=LOG_DIR):
Ian Patel's avatar
Ian Patel committed
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
    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
622
623
624
625
626
627
628
629
630
631
    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
632
633
634
    if level_error:
        logging.error('Malformed logging level "%s", setting logging level to %s', raw_level, level)

Max Beckett's avatar
Max Beckett committed
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

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}

    if '{region}' in dns_name_format:
        _validate_replacement_field_count(dns_name_format, 2)
        format_args['region'] = get_region()
    else:
        _validate_replacement_field_count(dns_name_format, 1)

    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
660
                    % (dns_name, 'https://docs.aws.amazon.com/console/efs/mount-dns-name'),
Max Beckett's avatar
Max Beckett committed
661
662
663
664
665
                    'Failed to resolve "%s"' % dns_name)

    return dns_name


666
def match_device(config, device):
667
    """Return the EFS id and the remote path to mount"""
668
669
670
671
672
673
674
675
676
677
678
679

    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
680
        hostnames = list(filter(lambda e: e is not None, [primary] + secondaries))
681
682
683
684
685
686
687
688
689
    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(
690
            'The specified domain name "%s" did not resolve to an EFS mount target' % remote
691
692
693
694
        )

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

696
697
698
        if efs_fqdn_match:
            fs_id = efs_fqdn_match.group('fs_id')
            expected_dns_name = get_dns_name(config, fs_id)
699

700
            # check that the DNS name of the mount target matches exactly the DNS name the CNAME resolves to
701
702
703
            if hostname == expected_dns_name:
                return fs_id, path
    else:
704
        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
705
706
                    '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'))
707
708


Max Beckett's avatar
Max Beckett committed
709
710
711
712
713
714
715
716
717
718
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:
        mount_completed = threading.Event()
        t = threading.Thread(target=poll_tunnel_process, args=(tunnel_proc, fs_id, mount_completed))
        t.start()
        mount_nfs(dns_name, path, mountpoint, options)
        mount_completed.set()
        t.join()


719
720
721
722
723
724
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
725
            logging.warning(warn_message)
726
727
728
            del options[unsupported_option]


Max Beckett's avatar
Max Beckett committed
729
def main():
Ian Patel's avatar
Ian Patel committed
730
731
    parse_arguments_early_exit()

Max Beckett's avatar
Max Beckett committed
732
733
734
735
736
    assert_root()

    config = read_config()
    bootstrap_logging(config)

737
738
    fs_id, path, mountpoint, options = parse_arguments(config)

Ian Patel's avatar
Ian Patel committed
739
    logging.info('version=%s options=%s', VERSION, options)
740
    check_unsupported_options(options)
Max Beckett's avatar
Max Beckett committed
741
742
743
744
745
746
747
748
749
750
751
752
753
754

    init_system = get_init_system()
    check_network_status(fs_id, init_system)

    dns_name = get_dns_name(config, fs_id)

    if 'tls' in options:
        mount_tls(config, init_system, dns_name, path, fs_id, mountpoint, options)
    else:
        mount_nfs(dns_name, path, mountpoint, options)


if '__main__' == __name__:
    main()