summaryrefslogtreecommitdiff
path: root/yubaws/yubaws.py
blob: 7370ce5a7104c081933113462f3212fd03bd97aa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#!/usr/bin/env python3

import argparse
import subprocess
import time
import os
from os.path import expanduser, exists
import boto3
import configparser


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("action", choices=["configure", "session", "otp"])
    args = parser.parse_args()
    return args


"""
Finds the name of a preconfigured MFA device
"""


def get_mfa_device():
    home = expanduser("~")
    mfa_device_file = home+"/.aws/.mfa_device"
    if not exists(mfa_device_file):
        print("You must configure an mfa device prior to using this function")
        exit(3)
    f = open(mfa_device_file, "r")
    mfa_device = f.read().strip("\n")
    f.close()
    return mfa_device


def is_exe(fpath):
    return os.path.isfile(fpath) and os.access(fpath, os.X_OK)


""" 
Checks if a binary is in the PATH 
and returns the full path if it is 
"""


def which(program):
    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None


def read_aws_config(file):
    config = configparser.ConfigParser()
    config.read(file)
    return config


def get_session_token():
    home = expanduser("~")
    credentials_file = home+"/.aws/credentials"
    orig_credentials_file = home+"/.aws/credentials.orig"
    if not exists(orig_credentials_file):
        print("Backing up your original credentials file")
        config = read_aws_config(credentials_file)
        with open(orig_credentials_file, 'w') as configfile:
            config.write(configfile)
    proc = subprocess.Popen(
        ['ykman', 'oath', 'accounts', 'code', get_mfa_device()], stdout=subprocess.PIPE)
    token = str(proc.communicate()[0].decode('utf-8').split()[-1])
    config = read_aws_config(credentials_file)
    orig_config = read_aws_config(orig_credentials_file)
    client = boto3.client('sts', aws_access_key_id=orig_config['default']['aws_access_key_id'],
                          aws_secret_access_key=orig_config['default']['aws_secret_access_key'])
    response = client.get_session_token(
        DurationSeconds=28800, SerialNumber=get_mfa_device(), TokenCode=token)
    config['default']['aws_access_key_id'] = response['Credentials']['AccessKeyId']
    config['default']['aws_secret_access_key'] = response['Credentials']['SecretAccessKey']
    config['default']['aws_session_token'] = response['Credentials']['SessionToken']
    with open(credentials_file, 'w') as configfile:
        config.write(configfile)
    return


"""
Used to configure a new yubikey as a virtual MFA
device for AWS. Produces an error if more than one yubikey is present
or if the yubikey doesn't support oath!
"""


def configure_new_device():
    f = filter(None, subprocess.run(
        ['ykman', 'list'], capture_output=True).stdout.decode('utf-8').split("\n"))
    keys = list(f)
    if len(keys) != 1:
        print("You must have exactly one yubikey inserted to configure a new virtual mfa device")
        exit(2)
    account_number = input("Enter your AWS account number: ")
    iam_username = input("Enter your IAM username: ")
    secret_key = input("Enter the secret key provided by AWS: ")
    oath_account_string = "arn:aws:iam::{account_number}:mfa/{iam_username}".format(
        account_number=account_number, iam_username=iam_username)
    subprocess.run(['ykman', 'oath', 'accounts', 'add',
                   '-t', oath_account_string, secret_key])
    print()
    print("We're going to generate a few OTPs now to pass back to AWS, please press your YubiKey when prompted")
    x = 0
    while x < 3:
        print()
        subprocess.run(['ykman', 'oath', 'accounts',
                       'code', oath_account_string])
        time.sleep(10)
        x = x + 1
        print()
    print("You should have at least two subsequent time based codes, go enter them in the AWS management console")
    print("To get an OTP on a one-off basis run 'ykman oath accounts code {oath_account_string}'".format(
        oath_account_string=oath_account_string))
    home = expanduser("~")
    f = open(home+"/.aws/.mfa_device", "w")
    f.write(oath_account_string)
    f.close()
    return


def get_otp():
    proc = subprocess.run(
        ['ykman', 'oath', 'accounts', 'code', get_mfa_device()])
    return


def main():
    args = parse_args()
    ykman = which('ykman')
    if ykman is None:
        print("You must have 'ykman' in your path prior to using this script")
        exit(1)
    if args.action == "configure":
        configure_new_device()
    elif args.action == "otp":
        get_otp()
    elif args.action == "session":
        get_session_token()
    return


if __name__ == '__main__':
    main()