Commit 3b1a184a authored by Alexander's avatar Alexander

working create-user and reset-password

parent c81efe41
__author__ = 'Alexander L. de Goeij'
__version__ = '0.4.2'
__version__ = '0.4.3'
......@@ -2,12 +2,43 @@ import colorlog
import boto3
from botocore.exceptions import ClientError
import base64
import qrcode
import pyqrcode
import string
import random
logger = colorlog.getLogger(__name__)
def reset_password(args):
"""Create new IAM User, set or update temporary password and add to IAM Group."""
logger.debug("iam_reset_password called")
iam = boto3.resource('iam')
temp_password = ''.join(random.choice(string.ascii_uppercase +
string.ascii_lowercase +
string.digits) for _ in range(15))
try:
login_profile = iam.LoginProfile(args.user)
response = login_profile.update(
Password=temp_password,
PasswordResetRequired=True
)
logger.info("Password for %s reset to %s (one-time use only).",
args.user, temp_password)
except Exception as e:
logger.error(
"You tried to change password for user %s, but it failed, check user's name?", args.user)
logger.debug(e)
logger.debug("iam_reset_password finished")
pass
def create_user(args):
"""Create new IAM User, set or update temporary password and add to IAM Group."""
logger.debug("iam_create_user called")
......@@ -28,21 +59,24 @@ def create_user(args):
logger.warning("User %s already exists.", args.user)
logger.debug(e)
# Add temporary password to IAM User account, or update it with a new one
temp_password = ''.join(random.choice(string.ascii_uppercase +
string.ascii_lowercase +
string.digits) for _ in range(15))
try:
logger.debug("trying to create_login_profile")
response = client.create_login_profile(
UserName=args.user,
Password=args.password,
Password=temp_password,
PasswordResetRequired=True
)
logger.debug(response)
logger.info(
"Succesfully set new temporary password for IAM User '%s'", args.user)
"Succesfully set new temporary password for IAM User '%s' to: %s", args.user, temp_password)
except client.exceptions.PasswordPolicyViolationException as e:
logger.error(
"Password for user '%s' does not match policies, check in AWS Console.", args.user)
logger.critical(
"Password for user '%s' does not match policies, this is a problem, as we generate one as per policies.", args.user)
logger.debug(e)
except client.exceptions.EntityAlreadyExistsException as e:
......@@ -54,16 +88,16 @@ def create_user(args):
logger.debug("trying to update_login_profile")
response = client.update_login_profile(
UserName=args.user,
Password=args.password,
Password=temp_password,
PasswordResetRequired=True
)
logger.debug(response)
logger.info(
"Succesfully updated temporary password for IAM User '%s'", args.user)
"Succesfully updated temporary password for IAM User '%s' to %s", args.user, temp_password)
except client.exceptions.PasswordPolicyViolationException as e:
logger.error(
"Password for user '%s' does not match policies, check in AWS Console.", args.user)
"Password for user '%s' does not match policies, this is a problem, as we generate one as per policies.", args.user)
logger.debug(e)
# Add IAM User to IAM Group
......@@ -73,6 +107,7 @@ def create_user(args):
GroupName=args.group,
UserName=args.user
)
logger.info("Added user: %s to group: %s", args.user, args.group)
logger.debug(response)
except Exception as e:
......@@ -82,21 +117,41 @@ def create_user(args):
try:
logger.debug("trying to create_virtual_mfa_device")
response = client.create_virtual_mfa_device(
create = client.create_virtual_mfa_device(
Path='/',
VirtualMFADeviceName="vmfa--" + args.user
)
logger.debug(response)
print(response["VirtualMFADevice"]["QRCodePNG"])
logger.debug(create)
qr_url = "otpauth://totp/vmfa--%[email protected]%s?secret=%s" % (args.user, args.user, create[
"VirtualMFADevice"]["Base32StringSeed"].decode())
logger.debug("Created otpauth url: %s", qr_url)
img = qrcode.make(base64.b64decode(
response["VirtualMFADevice"]["QRCodePNG"]))
qr_code = pyqrcode.create(qr_url)
print(img)
print(qr_code.terminal())
print("After scanning the code please provide two (sequential) tokens:")
token1 = input("Token 1: ")
token2 = input("Token 2: ")
logger.debug("trying to enable_mfa_device")
enable = client.enable_mfa_device(
UserName=args.user,
SerialNumber=create["VirtualMFADevice"]["SerialNumber"],
AuthenticationCode1=token1,
AuthenticationCode2=token2
)
logger.info("Succesfully enabled MFA for user %s", args.user)
logger.debug(enable)
logger.info(
"User %s should now be able to perform first time login with password: %s", args.user, temp_password)
except client.exceptions.EntityAlreadyExistsException as e:
logger.warning(
"MFA device with same name '%s' already exists, will leave it alone.", ("vmfa--" + args.user))
"MFA device with same name '%s' already exists, please manually remove it using the AWS IAM Console.", ("vmfa--" + args.user))
logger.debug(e)
except Exception as e:
......
......@@ -526,16 +526,22 @@ def main():
'--user', '-u', type=str, required=True,
help="Name of the IAM User."
)
parser_iam_create_user.add_argument(
'--password', '-p', type=str, required=True,
help="Temporary password for the new IAM User."
)
parser_iam_create_user.add_argument(
'--group', '-g', type=str,
help="Optional name of the IAM Group to add the IAM User to."
)
parser_iam_create_user.set_defaults(func=iam.create_user)
parser_iam_reset_password = parser_iam_sub.add_parser(
'reset-password',
help="Reset password of existing IAM User to one-time, autogenerated one."
)
parser_iam_reset_password.add_argument(
'--user', '-u', type=str, required=True,
help="Name of the IAM User."
)
parser_iam_reset_password.set_defaults(func=iam.reset_password)
# Slack terminal chat related commands and parsers
parser_slack = subparsers.add_parser(
'slack',
......
......@@ -2,5 +2,6 @@ pylint
pydocstyle
flake8
autopep8
twine
Sphinx
sphinx_rtd_theme
\ No newline at end of file
......@@ -37,13 +37,14 @@ setup(
version=__version__,
author="Alexander L. de Goeij",
author_email="[email protected]",
description=("Terminal toolkit to make using Amazon Web Services (AWS) simpler and more secure (2FA / MFA)."),
description=(
"Terminal toolkit to make using Amazon Web Services (AWS) simpler and more secure (2FA / MFA)."),
license="BSD 3-Clause Revised",
keywords="aws aws-cli aws-sdk cli terminal mfa 2fa multi-factor-authentication iam-credentials login otp session token",
url="https://gitlab.com/qrmr/qrmr",
packages=find_packages(),
install_requires=['future', 'colorlog',
'boto3', 'configparser', 'requests'],
'boto3', 'configparser', 'requests', 'pyqrcode'],
long_description=open('README.rst').read(),
classifiers=[
"Development Status :: 4 - Beta",
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment