broamski / aws-mfa Goto Github PK
View Code? Open in Web Editor NEWManage AWS MFA Security Credentials
License: MIT License
Manage AWS MFA Security Credentials
License: MIT License
Install via pip fails with the following error on windows 10 pro:
WARNING: Failed to write executable - trying to use .deleteme logic
ERROR: Could not install packages due to an EnvironmentError: [WinError 2] The system cannot find the file specified: 'c:\python38\Scripts\aws-mfa.exe' -> 'c:\python38\Scripts\aws-mfa.exe.deleteme'
I've been using mfa.py fine without problem. Its been about 2 week since last used and now running python3 mfa.py --profile wpfc01-usgovwest1 --region us-gov-west-1
I'm getting following error
INFO:modules.logger:Validating credentials for profile: wpfc01-usgovwest1 INFO:modules.logger:Short term credentials section wpfc01-usgovwest1 is missing, obtaining new credentials. WARNING:modules.logger:Your existing credentials are missing or invalid, obtaining new credentials. Failed to get a session with STSThe config profile (dummy) could not be found Traceback (most recent call last): File "/Users/jperez/vtdev/aws-mfa/mfa.py", line 113, in <module> main() File "/Users/jperez/vtdev/aws-mfa/mfa.py", line 104, in main client = vtmfa.get_sts_client(config_settings[1],config_settings[2],args.region, args) File "/Users/jperez/vtdev/aws-mfa/modules/mfa.py", line 88, in get_sts_client return client UnboundLocalError: local variable 'client' referenced before assignment
I tried running with --log-level DEBUG --force
hoping for clues but none found.
My ~/.aws/credentials
still has
[wpfc01-usgovwest1-long-term] aws_access_key_id = REDACTED aws_secret_access_key = REDACTED aws_mfa_device = REDACTED
Any help/clues would be greatly appreciated
python setup.py install
failed because urllib3 failed. The error message is:
Searching for urllib3<1.26,>=1.20
Reading https://pypi.python.org/simple/urllib3/
Best match: urllib3 1.25.3
Downloading https://files.pythonhosted.org/packages/4c/13/2386233f7ee40aa8444b47f7463338f3cbdf00c316627558784e3f542f07/urllib3-1.25.3.tar.gz#sha256=dbe59173209418ae49d485b87d1681aefa36252ee85884c31346debd19463232
Processing urllib3-1.25.3.tar.gz
Writing /var/folders/kh/60500gcx7pb0qymlrb05fjlh0000gp/T/easy_install-alupQF/urllib3-1.25.3/setup.cfg
Running urllib3-1.25.3/setup.py -q bdist_egg --dist-dir /var/folders/kh/60500gcx7pb0qymlrb05fjlh0000gp/T/easy_install-alupQF/urllib3-1.25.3/egg-dist-tmp-0ZSEUl
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'python_requires'
warnings.warn(msg)
error: Setup script exited with error in urllib3 setup command: 'extras_require' must be a dictionary whose values are strings or lists of strings containing valid project/version requirement specifiers.
Env: macOS Mojave 10.14.5
Python 2.7.10 (system default)
It is only presented the second time when being read from the config file. This will need to be read from args
first.
Thank you for this great tool. I'm wondering if it's reasonable to implement a feature that will allow for reading password protected encrypted credentials files for the long-term keys?
The user would implement their own encryption (e.g. gpg, openPgp, etc.) and aws-mfa would only ask for a password to decrypt in order to gain access to the long term keys (in addition to mfa).
Would this be fairly do-able? I'm also wondering if this can be done without a code change? Could I pipe the results of my decrypted long-term keys into aws-mfa somehow?
My reason for wanting this is because storing long-term access keys unencrypted on my hard disk is a security threat. I'm okay storing temporary credentials. I've already chmod'd my .aws files to 600, but still it would be nice to have them password protected in case of a phishing incident where someone was logged in as me.
Thanks again for this tool. Interested in hearing your thoughts about this added redundancy. There's a similar tool that encrypts the file too I should add: https://github.com/realestate-com-au/credulous
Upon debugging the issue, if we are not passing region explicitly - enpoint URL gets resolved for global.
#endpoint_url = 'https://sts.cn-north-1.amazonaws.com.cn'
region_name = 'cn-north-1'
If we provide region_name in boto3, it was able to resolve the url. So region_name should be provided by the dev explicitly or region should be pulled from profile before hitting sts request.
client = boto3.client(
'sts',
aws_access_key_id=lt_key_id,
aws_secret_access_key=lt_access_key,
#endpoint_url = 'https://sts.cn-north-1.amazonaws.com.cn'
region_name = 'cn-north-1'
)
I would like to do:
aws-mfa --one-time-pass 123456
Is this possible?
When I run aws-mfa it strips out comments that are in the AWS credentials file. I use those comments to perform other actions outside of aws-mfa. From what I understand the credentials file follows the INI format and a comment line starts with a ; and some implementations allow #.
With AWS CLI, arguments override env vars. At the moment, aws-mfa
seems to crash when AWS_PROFILE
is set to an undefined profile, it should simply be ignored when --profile
is specified.
$ echo $AWS_PROFILE
weaveworks-mfa
$ aws-mfa --profile weaveworks
INFO - Validating credentials for profile: weaveworks
INFO - Short term credentials section weaveworks is missing, obtaining new credentials.
Enter AWS MFA code for device [arn:aws:iam::<SNIP>] (renewing for 43200 seconds):<SNIP>
Traceback (most recent call last):
File "/Users/ilya/Library/Local/Homebrew/bin/aws-mfa", line 11, in <module>
sys.exit(main())
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/awsmfa/__init__.py", line 105, in main
validate(args, config)
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/awsmfa/__init__.py", line 272, in validate
get_credentials(short_term_name, key_id, access_key, args, config)
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/awsmfa/__init__.py", line 284, in get_credentials
aws_secret_access_key=lt_access_key
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/boto3/__init__.py", line 79, in client
return _get_default_session().client(*args, **kwargs)
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/boto3/__init__.py", line 69, in _get_default_session
setup_default_session()
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/boto3/__init__.py", line 33, in setup_default_session
DEFAULT_SESSION = Session(**kwargs)
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/boto3/session.py", line 80, in __init__
self._setup_loader()
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/boto3/session.py", line 112, in _setup_loader
self._loader = self._session.get_component('data_loader')
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/botocore/session.py", line 690, in get_component
return self._components.get_component(name)
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/botocore/session.py", line 871, in get_component
self._components[name] = factory()
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/botocore/session.py", line 178, in <lambda>
lambda: create_loader(self.get_config_variable('data_path')))
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/botocore/session.py", line 258, in get_config_variable
elif self._found_in_config_file(methods, var_config):
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/botocore/session.py", line 279, in _found_in_config_file
return var_config[0] in self.get_scoped_config()
File "/Users/ilya/Library/Local/Homebrew/lib/python2.7/site-packages/botocore/session.py", line 351, in get_scoped_config
raise ProfileNotFound(profile=profile_name)
botocore.exceptions.ProfileNotFound: The config profile (weaveworks-mfa) could not be found
$ unset AWS_PROFILE
$ aws-mfa --profile weaveworks
INFO - Validating credentials for profile: weaveworks
INFO - Short term credentials section weaveworks is missing, obtaining new credentials.
Enter AWS MFA code for device [arn:aws:iam::<SNIP>] (renewing for 43200 seconds):<SNIP>
INFO - Fetching Credentials - Profile: weaveworks, Duration: 43200
INFO - Success! Your credentials will expire in 43200 seconds at: 2018-06-07 19:17:02+00:00
$
I did aws-mfa --setup
created a test profile (in the key/secret you are unable to see what is entered)
I then did:
aws-mfa --duration 1800 --device arn:aws:iam::000000000000000:user/user.name --profile test
INFO - Validating credentials for profile: test
**INFO - Short term credentials section test is missing, obtaining new credentials.**
Enter AWS MFA code for device [arn:aws:iam::000000000000000:user/user.name] (renewing for 1800 seconds):000000
INFO - Fetching Credentials - Profile: test, Duration: 1800
ERROR - An error occured while calling assume role: An error occurred (AccessDenied) when calling the GetSessionToken operation: MultiFactorAuthentication failed, unable to validate MFA code. Please verify your MFA serial number is valid and associated with this user.
`
Ive tried various combinations, I logged into the console with the MFA codes so I know it works manually.
I am using aws-mfa.
When i run aws-mfa with profile name with long-term credentials in my ~/.aws/credentials, it is always reaching to
https://sts.amazonaws.com as my machine is in private network so not able to resolve it and failing to have temporary creds in my file.
Installed aws-mfa today to get aws-cdk finally working with mfa support.
Windows 10 1803
Python 3.8.3
PiP 20.1.1
[development.sap-long-term] aws_access_key_id = myaccessKey aws_secret_access_key = SecretAcessKey [development.sap] aws_access_key_id = <POPULATED_BY_AWS-MFA> aws_secret_access_key = <POPULATED_BY_AWS-MFA> aws_security_token = <POPULATED_BY_AWS-MFA>
I execute aws-mfa --profile development.sap --device arn:aws:iam::772769262746:mfa/christian.pfisterer
INFO - Validating credentials for profile: development.sap with assumed role: arn:aws:iam::876701326593:role/HSEAdminRole WARNING - Your existing credentials are missing or invalid, obtaining new credentials. INFO - Obtaining credentials for a new role or profile. Enter AWS MFA code for device [arn:aws:iam::772769262746:mfa/christian.pfisterer] (renewing for 3600 seconds): INFO - Assuming Role - Profile: development.sap, Role: arn:aws:iam::876701326593:role/HSEAdminRole, Duration: 3600 ERROR - An error occured while calling assume role: An error occurred (InvalidClientTokenId) when calling the AssumeRole operation: The security token included in the request is invalid.
Any one else have this problem?
We intend to use this tool for role assumption. For role assumption, we want our dev and ops folks to be able to assume role for 12 hours. It would be nice if we can set the duration value in config file or credential file instead of in --duration or in environment variables.
Thanks.
After upgrading Python from 2.7.x to 3.8.x (on macOS) I get the following error:
Traceback (most recent call last):
File "/usr/local/bin/aws-mfa", line 6, in <module>
from awsmfa import main
ModuleNotFoundError: No module named 'awsmfa'
I did uninstall aws-mfa, relinked Python, installed aws-mfa again but it didn't help.
The token should be generated for 36 hours but it is instead generated for an hour. I'm in the IST timezone. This has worked flawlessly in the past. Is there a setting that I'm missing?
❯ date
Tue May 4 10:40:53 IST 2021
❯ date -u
Tue May 4 05:10:55 UTC 2021
❯ aws-mfa --force --duration 129600
INFO - Validating credentials for profile: default
INFO - Forcing refresh of credentials.
Enter AWS MFA code for device [arn:aws:iam::xxxx:mfa/xxxx] (renewing for 129600 seconds):119525
INFO - Fetching Credentials - Profile: default, Duration: 129600
INFO - Success! Your credentials will expire in 129600 seconds at: 2021-05-04 06:11:33+00:00
❯ date
Tue May 4 10:41:09 IST 2021
❯ date -u
Tue May 4 05:11:11 UTC 2021
I used this command pip install aws-mfa --upgrade to install aws-mfa successfully and verified the installation as below but still got "command not found" error.
huiyas-mbp:~ [email protected]$ pip freeze | grep aws-mfa
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
WARNING: Could not generate requirement for distribution -irtualenv 20.0.18 (/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages): Parse error at "'-irtuale'": Expected W:(abcd...)
aws-mfa==0.0.12
huiyas-mbp:~ [email protected]$ aws-mfa --profile default
-bash: aws-mfa: command not found
Can you please help check what's wrong? Thanks.
I am receiving the error message:
ERROR - Token must be six digits
when using the command:
aws-mfa --duration 60 --profile default
INFO - Validating credentials for profile: default
INFO - Your credentials have expired, renewing.
Enter AWS MFA code for device [arn:aws:iam::1234567890:mfa/tom] (renewing for 60 seconds):123456
INFO - Fetching Credentials - Profile: default, Duration: 60
ERROR - Token must be six digits
Since clearly my MFA token is 6 digits, and since this had worked for me before, I got suspicious and started to change the duration value:
aws-mfa --duration 100 --profile default
ERROR - Token must be six digits
aws-mfa --duration 1000 --profile default
INFO - Success! Your credentials will expire in 1000 seconds at: 2018-10-15 17:13:02+00:00
So it appears the duration value being less than 4 digits is causing this error. I'll try to look at the code and submit a PR with a fix.
My understanding is that this is installed only for my local user, and not 'globally'. I do not know if it is possible to install this kind of python dependency for all users on macOS. If not, then I assume that I have to manually add this item to my PATH.
If this is correct, then suggest adding a comment to the readme to test the installation by typing aws-mfa in the console.
aws-mfa is great thank you but is missing one feature that'd allow me to rely solely on it, the ability to get a federated, short-term authenticated console url/login. In the similar tool aws-vault that happens with aws-vault login <profile name>
and it opens the AWS console for that account. Without that, cli access works great but there's no way to get console access via aws-mfa alone.
The package support aws_mfa_device
in the credentials file, but we were wondering why it didn't use the parameter AWS documented here called mfa_serial
?
Are the two equivalent, except for one being in config
and the other in credentials
?
In our environment, we auto generate a number of profiles and we use a comment
To separate out the generated profiles from the non-generated one. Unfortunately, everytime we run the aws-mfa tool, it removes that comment.
The latest AWS CLI bumps the boto library shared with aws-mfa and causes calls to STS to fail because the profile is taken from the environment instead of the explicitly provided --profile
parameter passed to aws-mfa
Hello,
Is there a way to only check if my credential is still valid or expire ?
It is to add to my (oh my) zsh prompt.
Thanks.
Maybe it's possible, but I'm not seeing it from the documentation.
It would be nice to be able to have a single long-term that can assume roles into multiple accounts with multiple permissions.
default-long-term, but can easily assume
aws-mfa --assume-role admin --account dev
aws-mfa --assume-role admin --account qa
aws-mfa --assume-role readonly --account dev
This is an issue I fixed for myself, but definitely something that should be implemented if not already in the works. I only added a region flag, but could be pulling from long-term config credentials.
The code base has the argument --token
that allows receiving the token as an argument rather than prompting for one,
this is very handy, but not included in the latest release, thus, the pip install
installation doesn't have this.
Can a version be released also to pypi?
Thanks.
It would be nice to have an option to iterate over all the profiles for MFA instead of typing the command again and again.
There seems to be a bug in version 0.0.11. I'm getting following error,
Traceback (most recent call last):
File "/usr/local/bin/aws-mfa", line 7, in <module>
from awsmfa import main
File "/usr/local/lib/python3.6/site-packages/awsmfa/__init__.py", line 16, in <module>
from config import initial_setup
ModuleNotFoundError: No module named 'config'
Version 0.0.10 is working fine for me. Please check.
I am using Python 3.6.5.
Would be nice to clear or pre-expire the token. This is more for testing policies, profiles and such, so may not be a common use case.
The workaround is to manually delete the entries in the ~/.aws/credentials file.
Hey there, thanks for your awesome little script, it's helping us a lot.
I notice you mention that a maximum duration of 3600 is enforced but this doesn't seem to be the case in the code. I've also seen other tools stating you can keep sessions open for many hours.
In our case, we'd like to keep sessions open for 12 hours or longer to make it easier to work.
Can you kindly clarify the 3600 second duration limit?
Thanks so much!
Fotis
Hi,
AWS recently announced that Yubikeys can now be used as MFA solution, sadly aws-mfa
does not support it yet.
Is someone already working on that ?
At on 2022-05-11 at 16:43 GMT+1
I received
INFO - Your credentials are still valid for 1813.178155 seconds they will expire at 2022-05-11 16:11:37
Which of course makes no sense since Your credentials are still valid
contradicts expire at 2022-05-11 16:11:37
where at this point its over 30 mins in the past.
Line 263 in 5334deb
I'm assuming the issue is that exp
is datetime naive and the exp
iration is returned in UTC
. Which is used to calculate the seconds left correctly but forgets to use the client's timezone before logging.
I cannot explain why this:
especially since my timezone didn't change recently
Getting the following error after updating Botocore to the latest version:
Traceback (most recent call last):
return self._endpoint.make_request(operation_model, request_dict)
while self._needs_retry(
return self._emitter.emit(aliased_event_name, **kwargs)
File "/home/joseph/.local/lib/python3.10/site-packages/botocore/hooks.py", line 256, in emit
return self._emit(event_name, kwargs)
File "/home/joseph/.local/lib/python3.10/site-packages/botocore/hooks.py", line 239, in _emit
response = handler(**kwargs)
File "/home/joseph/.local/lib/python3.10/site-packages/botocore/retryhandler.py", line 207, in __call__
if self._checker(**checker_kwargs):
File "/home/joseph/.local/lib/python3.10/site-packages/botocore/retryhandler.py", line 284, in __call__
should_retry = self._should_retry(
File "/home/joseph/.local/lib/python3.10/site-packages/botocore/retryhandler.py", line 307, in _should_retry
return self._checker(
File "/home/joseph/.local/lib/python3.10/site-packages/botocore/retryhandler.py", line 363, in __call__
checker_response = checker(
File "/home/joseph/.local/lib/python3.10/site-packages/botocore/retryhandler.py", line 247, in __call__
return self._check_caught_exception(
File "/home/joseph/.local/lib/python3.10/site-packages/botocore/retryhandler.py", line 416, in _check_caught_exception raise caught_exception
File "/home/joseph/.local/lib/python3.10/site-packages/botocore/endpoint.py", line 281, in _do_get_response
http_response = self._send(request)
File "/home/joseph/.local/lib/python3.10/site-packages/botocore/endpoint.py", line 377, in _send
return self.http_session.send(request)
File "/home/joseph/.local/lib/python3.10/site-packages/botocore/httpsession.py", line 509, in send
raise HTTPClientError(error=e)
botocore.exceptions.HTTPClientError: An HTTP Client raised an unhandled exception: Failed to parse: https://sts.us-east-1.amazonaws.com/
Just rubber ducking this here, seems like some Python package updates maybe broke aws-mfa
.
importlib.metadata.PackageNotFoundError: No package metadata was found for aws-mfa
.aws directory not created after install with pip or git clone install
jon@jon-Inspiron-7391-2n1:~$ aws-mfa
Could not locate credentials file at /home/jon/.aws/credentials, would you like to create one? [y/n]y
Traceback (most recent call last):
File "/home/jon/domusoenv/bin/aws-mfa", line 11, in <module>
load_entry_point('aws-mfa==0.0.12', 'console_scripts', 'aws-mfa')()
File "/home/jon/domusoenv/lib/python3.8/site-packages/aws_mfa-0.0.12-py3.8.egg/awsmfa/__init__.py", line 97, in main
FileNotFoundError: [Errno 2] No such file or directory: '/home/jon/.aws/credentials'
I manually create it
(domusoenv) jon@jon-Inspiron-7391-2n1:~$ mkdir ~/.aws
(domusoenv) jon@jon-Inspiron-7391-2n1:~$ aws-mfa
Could not locate credentials file at /home/jon/.aws/credentials, would you like to create one? [y/n]y
INFO - Validating credentials for profile: default
ERROR - Long term credentials session '[default-long-term]' is missing. You must add this section to your credentials file along with your long term 'aws_access_key_id' and 'aws_secret_access_key'
When using mfa for an IAM user access tokens there is only one device; the only result in session.client('iam').list_mfa_devices()
. Would be worthwhile to try to default to that if not configured otherwise.
It appears there is no way to specify an external ID when assuming a role. An attempt made on #51 but it would be nicer to support this directly from profile configuration.
If the current credentials are that of an assumed role and have not expired, you are unable to assume the role of a different account. This is because the the application begins with validation that only checks the expiration date. You'll need to add logic to check and see if a current role is assumed and if the provided role is different, in which case you'll need to fetch new credentials.
Hi!
Is there any way to get this working with AWS CLI credential_process
?
Basically this tool should first execute the command defined in credential_process
to get the access key id & secret.
More information: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sourcing-external.html
This is the second time I installed and using aws-mfa. For the first all worked great, now in this new setup I can't set my device.
All the time I run:
aws-mfa --device arn:aws:iam::xxxxxxxxxxxxxx:user/xxxxxxxx
And then type the token I get:
INFO - Validating credentials for profile: default
INFO - Short term credentials section default is missing, obtaining new credentials.
Enter AWS MFA code for device [arn:aws:iam::xxxxxxxxxxxxxx:user/xxxxxxxx] (renewing for 43200 seconds):311772
INFO - Fetching Credentials - Profile: default, Duration: 43200
ERROR - An error occured while calling assume role: An error occurred (AccessDenied) when calling the GetSessionToken operation: MultiFactorAuthentication failed, unable to validate MFA code. Please verify your MFA serial number is valid and associated with this user
The device arn is okay, long term keys are okay, instalation is okay too.
What's the problem here?
Receive...
No handlers could be found for logger "botomfa"
when issues with credentials file, not found, perms, etc.
Adding...
logging.basicConfig()
Before...
logger = logging.getLogger('botomfa')
Provides better error handling and visibility of the actual problem.
Cheers,
Marty
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.