├── docs ├── README.md ├── Windows.md ├── ChangeLog.md └── Options.md ├── source ├── Rakefile ├── lib │ ├── assumer │ │ └── version.rb │ ├── mfa.rb │ └── assumer.rb ├── exe │ ├── .rubocop.yml │ └── assumer ├── Gemfile ├── bin │ ├── setup │ └── console └── assumer.gemspec ├── .gitignore ├── README.md └── LICENSE /docs/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /source/Rakefile: -------------------------------------------------------------------------------- 1 | require 'bundler/gem_tasks' 2 | -------------------------------------------------------------------------------- /source/lib/assumer/version.rb: -------------------------------------------------------------------------------- 1 | module Assumer 2 | VERSION = '0.4.3'.freeze 3 | end 4 | -------------------------------------------------------------------------------- /source/exe/.rubocop.yml: -------------------------------------------------------------------------------- 1 | AllCops: 2 | TargetRubyVersion: 2.1 3 | LineLength: 4 | Max: 100 5 | -------------------------------------------------------------------------------- /source/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # Specify your gem's dependencies in assumer.gemspec 4 | gemspec 5 | -------------------------------------------------------------------------------- /source/bin/setup: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | 5 | bundle install 6 | 7 | # Do any other automated setup that you need to do here 8 | -------------------------------------------------------------------------------- /source/bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require 'bundler/setup' 4 | require 'assumer' 5 | 6 | # You can add fixtures and/or initialization code here to make experimenting 7 | # with your gem easier. You can also use a different console, if you like. 8 | 9 | # (If you use this, don't forget to add pry to your Gemfile!) 10 | require 'pry' 11 | Pry.start 12 | 13 | # require "irb" 14 | # IRB.start 15 | -------------------------------------------------------------------------------- /source/lib/mfa.rb: -------------------------------------------------------------------------------- 1 | module Assumer 2 | ## 3 | # A class to manage methods of obtaining OTP codes for MFA 4 | class MFA 5 | attr_reader :otp 6 | ## 7 | # A method to prompt for the user's OTP MFA code on the CLI 8 | # @return [String] The MFA code entered by the user 9 | def request_one_time_code 10 | until @otp =~ /\d{6}/ 11 | print 'Enter MFA: ' 12 | $stdout.flush 13 | @otp = $stdin.gets(7).chomp 14 | $stderr.puts 'MFA code should be 6 digits' if @otp !~ /\d{6}/ 15 | end 16 | @otp # return the MFA code 17 | rescue SystemExit, Interrupt 18 | exit -1 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.gem 2 | *.rbc 3 | /.config 4 | /coverage/ 5 | /InstalledFiles 6 | /pkg/ 7 | /spec/reports/ 8 | /spec/examples.txt 9 | /test/tmp/ 10 | /test/version_tmp/ 11 | /tmp/ 12 | 13 | ## Specific to RubyMotion: 14 | .dat* 15 | .repl_history 16 | build/ 17 | 18 | ## Documentation cache and generated files: 19 | /.yardoc/ 20 | /_yardoc/ 21 | /doc/ 22 | /rdoc/ 23 | 24 | ## Environment normalization: 25 | /.bundle/ 26 | /vendor/bundle 27 | /lib/bundler/man/ 28 | 29 | # for a library or gem, you might want to ignore these files since the code is 30 | # intended to run in multiple environments; otherwise, check them in: 31 | # Gemfile.lock 32 | # .ruby-version 33 | # .ruby-gemset 34 | 35 | # unless supporting rvm < 1.11.0 or doing something fancy, ignore this: 36 | .rvmrc 37 | 38 | # Folder view configuration files 39 | .DS_Store 40 | Desktop.ini 41 | 42 | # Thumbnail cache files 43 | ._* 44 | Thumbs.db 45 | 46 | # Files that might appear on external disks 47 | .Spotlight-V100 48 | .Trashes 49 | 50 | -------------------------------------------------------------------------------- /source/assumer.gemspec: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | lib = File.expand_path('../lib', __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require 'assumer/version' 5 | 6 | Gem::Specification.new do |spec| 7 | spec.name = 'assumer' 8 | spec.version = Assumer::VERSION 9 | spec.authors = ['Brandon Sherman'] 10 | spec.email = ['mechcozmo@gmail.com'] 11 | 12 | spec.summary = 'This gem provides the functionality to Assume Role in AWS' 13 | spec.description = 'Allows for single or double-jumps through AWS accounts in order to assume a role in a target account' 14 | spec.homepage = 'https://github.com/devsecops/assumer' 15 | 16 | spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } 17 | spec.bindir = 'exe' 18 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } 19 | spec.executables.reject! { |f| f == '.rubocop.yml' } 20 | spec.require_paths = ['lib'] 21 | 22 | spec.add_development_dependency 'bundler', '~> 1.10' 23 | spec.add_development_dependency 'rake', '~> 10.0' 24 | # Requires Ruby 2.1 or higher; 2.0 is buggy 25 | spec.required_ruby_version = '>= 2.1' 26 | spec.add_dependency 'aws-sdk-core', '~> 3' 27 | spec.add_dependency 'pry', '~>0' 28 | spec.add_dependency 'trollop', '2.1.2' 29 | end 30 | -------------------------------------------------------------------------------- /docs/Windows.md: -------------------------------------------------------------------------------- 1 | # Running Assumer on Windows # 2 | 3 | *This document is a work in progress* 4 | 5 | 6 | 1. Download Ruby 2.2.* from http://rubyinstaller.org/downloads/ 7 | 1. Build the Assumer gem 8 | 1. Install the gem. Open a cmd.exe window and type `gem install `, then drag-and-drop the gem file into the window and press enter. 9 | * If the required gems are not installed, here is a list of dependencies that can be downloaded and installed individually: 10 | * https://rubygems.org/downloads/pry-0.10.3.gem 11 | * https://rubygems.org/downloads/trollop-2.1.2.gem 12 | * https://rubygems.org/downloads/coderay-1.1.1.gem 13 | * https://rubygems.org/downloads/method_source-0.8.2.gem 14 | * https://rubygems.org/downloads/slop-3.4.0.gem 15 | * https://rubygems.org/downloads/aws-sdk-core-2.2.20.gem 16 | * https://rubygems.org/downloads/jmespath-1.1.3.gem 17 | 1. Download CACERT.PEM to allow SSL communications from http://curl.haxx.se/ca/cacert.pem 18 | 1. Open Command Prompt and run 19 | * `set AWS_ACCESS_KEY_ID=AKIA_ACCESS_KEY_HERE` 20 | * `set AWS_SECRET_ACCESS_KEY=5_SECRET_KEY_HERE_J` 21 | * `set SSL_CERT_FILE=c:\path\to\where\you\saved\cacert.pem` 22 | 1. Now you can run assumer commands in the terminal window 23 | 24 | If you do not need to use the GUI, you can skip the steps involving `cacert.pem` and enable the [AWS bundled certificates](/docs 25 | /Options.md#enable-aws-bundled-ca-certificate) 26 | -------------------------------------------------------------------------------- /docs/ChangeLog.md: -------------------------------------------------------------------------------- 1 | # Assumer Change Log # 2 | 3 | ## Version 0.4.2 ## 4 | 5 | * Better error handling all around. `assumer` is less likely to dump a backtrace out when something happens and instead return just the message 6 | * Using `^C` to stop execution at the MFA prompt doesn't dump a backtrace out, the gem exits cleanly 7 | 8 | 9 | ## Version 0.4.1 ## 10 | 11 | * Brought the role validation regex in-line with the one used by Amazon. 12 | 13 | ## Version 0.4.0 ## 14 | 15 | * First public release 16 | 17 | ## Version 0.3.0 ## 18 | 19 | * Lots of small tweaks to work around the various issues that Windows has. 20 | * Did you know that Windows treats `''` and `""` differently? The more you know... 21 | * Users on Windows can use their default browser 22 | * Documentation updates 23 | 24 | ## Version 0.2.9 ## 25 | 26 | ** Unreleased, used for debugging only ** 27 | 28 | ## Version 0.2.8 ## 29 | 30 | * Provide an option for using the CA Certificate store bundled with the AWS SDK. The default is to use the system's certificate, but this is sometimes misconfigured. 31 | * Write the temporary credentials in a manner that allows for easy use on Windows 32 | 33 | ## Version 0.2.7 ## 34 | 35 | * Addition of `--debug` flag 36 | * Fixes to web browser opening; now works on Windows and Linux 37 | * Documentation [addition](Options.md): Explanation of all flags and options when invoked 38 | 39 | ## Version 0.2.6 ## 40 | 41 | * First public release! 42 | * Introduction of `-p` flag to optionally drop into a pry prompt. `-p` and `-g` can be combined for a console login link and pry shell, or both can be omitted for just the temporary credential file generation. 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Assumer # 2 | 3 | ## Overview ## 4 | The Assumer gem is an interface allowing the user to assume role into an account. Credentials can be loaded anywhere the AWS STS Client knows to load credentials from (ENV, profile, etc.) 5 | 6 | ## Content ## 7 | Assumer will assume-role on a target account and generate temporary API keys for that account. It can optionally drop you into a pry session or load the AWS console in the context of the role assumed in the target account depending on how Assumer was called. 8 | 9 | ## Installation ## 10 | 11 | Assumer requires a Ruby version >= 2.1 12 | 13 | Install with `gem install assumer` 14 | 15 | ### Build from Source ### 16 | 17 | 1. Clone the repository 18 | 1. Change directory into the newly-cloned repository 19 | * `cd assumer` 20 | 1. Change directory into the `source` folder, where the gem's source code lives 21 | * `cd source` 22 | 1. Build the gem 23 | * `gem build assumer.gemspec` 24 | 1. Install the gem 25 | * `gem install assumer-0.4.2.gem` 26 | 27 | ## Usage ## 28 | 29 | **Having trouble running Assumer on Windows? Please see our [document](/docs/Windows.md) with some troubleshooting steps.** 30 | 31 | You can use the gem on the command line. For an in-depth explanation of options, see [this file](/docs/Options.md); what follows is a simplistic overview. 32 | 33 | To see help text: 34 | * `assumer -h` To see help text 35 | 36 | Standard usage: 37 | * `assumer -a 123456789012 -r "target/role-name" -A 987654321098 -R "control/role-name" ` 38 | 39 | To request a console, pass the `-g` flag: 40 | * `assumer -a 123456789012 -r "target_role/target_path" -A 987654321098 -R "control_role/control_path" -g` 41 | 42 | To request a pry console, pass the `-p` flag: 43 | * `assumer -a 123456789012 -r "target_role/target_path" -A 987654321098 -R "control_role/control_path" -p` 44 | 45 | Why not both? 46 | * `assumer -a 123456789012 -r "target_role/target_path" -A 987654321098 -R "control_role/control_path" -p -g` 47 | 48 | Or use the gem in your code: 49 | ```ruby 50 | require 'assumer' 51 | # First Jump 52 | control_creds = Assumer::Assumer.new( 53 | region: aws_region, 54 | account: control_plane_account_number, 55 | role: control_plane_role, 56 | serial_number: serial_number, # if you are using MFA, this will be the ARN for the device 57 | profile: credential_profile_name # if you don't want to use environment variables or the default credentials in your ~/.aws/credentials file 58 | ) 59 | # Second jump 60 | target_creds = Assumer::Assumer.new( 61 | region: aws_region, 62 | account: target_plane_account_number, 63 | role: target_account_role, 64 | credentials: control_creds 65 | ) 66 | ``` 67 | 68 | 69 | ## Notes ## 70 | 1. To be able to use this utility you will need to have permission to assume-role against the role you specify! 71 | -------------------------------------------------------------------------------- /source/lib/assumer.rb: -------------------------------------------------------------------------------- 1 | require 'assumer/version' 2 | require 'aws-sdk-core' 3 | require 'mfa' 4 | 5 | module Assumer 6 | # The regex that AWS uses to verify if a role's ARN is valid 7 | AWS_ROLE_REGEX = %r{arn:aws:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+} 8 | class AssumerError < StandardError; end 9 | # This class provides the main functionallity to the Assumer gem 10 | 11 | class Assumer 12 | # This is the only thing clients are allowed to access 13 | # It will be an STS::AssumeRoleCredentials object created by AWS 14 | attr_accessor :assume_role_credentials 15 | 16 | ## 17 | # Creates the Assumer object 18 | # 19 | # @param [String] region The AWS region to establish a connection from (if left nil, Assumer will try and use it's current region) 20 | # @param [String] account The AWS account number without dashes 21 | # @param [String] role The ARN for the role to assume 22 | # @param [String] serial_number The Serial Number of an MFA device 23 | # @param [Assumer] credentials An assumer object (to support double-jumps) 24 | 25 | def initialize(region: nil, account: nil, role: nil, serial_number: nil, credentials: nil, profile: nil) 26 | @region = region ? region : my_region # if region is passed in, use it, otherwise find what region we're in and use that 27 | @account = account 28 | @role = verify_role(role: role) 29 | # If we are being passed credentials, it's an Assumer instance, and we can 30 | # get the creds from it. Otherwise, establish an STS connection 31 | @sts_client = establish_sts( 32 | region: @region, 33 | passed_credentials: credentials, 34 | credentials_profile: profile 35 | ) 36 | @serial_number = serial_number # ARN for the user's MFA serial number 37 | 38 | opts = { 39 | client: @sts_client, 40 | role_arn: @role, 41 | role_session_name: 'AssumedRole' 42 | } 43 | # Don't specify MFA serial number or token code if they aren't needed 44 | unless @serial_number.nil? 45 | opts[:serial_number] = @serial_number 46 | opts[:token_code] = MFA.new.request_one_time_code 47 | end 48 | @assume_role_credentials = Aws::AssumeRoleCredentials.new(opts) 49 | 50 | rescue Aws::STS::Errors::AccessDenied => e 51 | raise AssumerError, "Access Denied: #{e.message}" 52 | end 53 | 54 | ## 55 | # Verifies the requested role is valid 56 | # Only checks syntax, does not guarantee the role exists or can be assumed into 57 | # @param [String] role The ARN of the role to be verified 58 | # @return [String] The ARN of a valid role 59 | # @raise [AssumerError] If the ARN is invalid, an exception is raised 60 | def verify_role(role:) 61 | raise AssumerError, "Invalid ARN for role #{role}" unless role =~ AWS_ROLE_REGEX 62 | role 63 | end 64 | 65 | private 66 | 67 | ## 68 | # Establish an AWS STS connection to retrieve tokens 69 | # @param [String] region An AWS region to establish a connection in 70 | # @param [Assumer] passed_credentials An Assumer object that has established a connection to an account. Used for double-jumps. 71 | # @param [String] credentials_profile The credentials profile to load from the user's .aws/credentials file 72 | # @return [Aws::STS::Client] The Secure Token Service client 73 | def establish_sts(region: nil, passed_credentials: nil, credentials_profile: nil) 74 | throw AssumerError.new('No region provided') if region.nil? 75 | opts = { region: region } 76 | 77 | # If credentials were passed in, use those to build the STS client 78 | opts.merge!( 79 | access_key_id: passed_credentials.assume_role_credentials.credentials.access_key_id, 80 | secret_access_key: passed_credentials.assume_role_credentials.credentials.secret_access_key, 81 | session_token: passed_credentials.assume_role_credentials.credentials.session_token 82 | ) unless passed_credentials.nil? 83 | 84 | # If a profile is specified, read those from the ~/.aws/credentials file 85 | # Or anywhere AWS STS Client knows where to load them from 86 | opts[:profile] = credentials_profile unless credentials_profile.nil? 87 | @sts_client = Aws::STS::Client.new(opts) 88 | end 89 | 90 | ## 91 | # Determine the region this code is being called in by contacting the AWS 92 | # metadata service 93 | # @return [String] AWS Region Assumer is being called in OR 'us-east-1' if unable to be determined 94 | # @raise [AssumerError] If the region cannot be determined, an exception is raised 95 | def my_region 96 | require 'net/http' 97 | require 'json' 98 | metadata_uri = URI('http://169.254.169.254/latest/dynamic/instance-identity/document/') 99 | request = Net::HTTP::Get.new(metadata_uri.path) 100 | response = Net::HTTP.start(metadata_uri.host, metadata_uri.port) do |http| 101 | http.read_timeout = 10 102 | http.open_timeout = 10 103 | http.request(request) 104 | end 105 | JSON.parse(response).fetch('region', 'us-east-1') 106 | rescue => e 107 | raise AssumerError, "Could not determine region (are you running in AWS?): #{e.message}" 108 | end 109 | end 110 | end 111 | -------------------------------------------------------------------------------- /docs/Options.md: -------------------------------------------------------------------------------- 1 | # Assumer Options # 2 | 3 | This document is an in-depth explanation of the various options (or flags) that Assumer supports. 4 | 5 | ## Command Line Tool ## 6 | 7 | The `assumer` gem includes an executable Ruby script that automates the process of double-jumping and assuming a role within a target account. This script can optionally use those temporary credentials to open a web browser so that the AWS Console can be accessed, drop into a Pry shell, or both. 8 | 9 | As of Assumer v0.4.2, the flags available are: 10 | ``` 11 | $ assumer -h 12 | Parameters: 13 | -a, --target-account= Target AWS account to assume into 14 | -r, --target-role= The role in the target account 15 | -A, --control-account= Control Plane AWS account 16 | -R, --control-role= The role in the control account 17 | These parameters are optional: 18 | -e, --region= AWS region to operate in 19 | -u, --username= Your IAM username (default: Output of `whoami`) 20 | -o, --profile= Profile name from ~/.aws/credentials 21 | -g, --gui Open a web browser to the AWS console with these credentials 22 | -p, --pry Open a pry shell with these credentials 23 | -n, --enable-aws-bundled-ca-cert Option to enable the certificate store bundled with the AWS SDK 24 | -d, --debug Output debugging information 25 | -v, --version Print version and exit 26 | -h, --help Show this message 27 | ``` 28 | 29 | ### Required Parameters ### 30 | 31 | #### Target Account #### 32 | 33 | * Short: `-a` 34 | * Long: `--target-account=` 35 | 36 | This parameter specifies the AWS account that you will ultimately assume a role into; this is the second jump in the 'double-jump'. 37 | 38 | Example: `123456789012` 39 | 40 | This parameter requires a 12-digit AWS account number. If the provided account number is invalid, assumer will output an error message: 41 | 42 | `Error: argument --target-account Must be a 12-digit AWS account number.` 43 | 44 | #### Target Role #### 45 | 46 | * Short: `-r` 47 | * Long: `--target-role=` 48 | 49 | This parameter specifies the role that will be assumed in the target account. The assumer tool will build the ARN from the account number and knowledge of AWS syntax, leaving just the role path and name to be specified. 50 | 51 | Example: `my-role-path/my-target-role-name` 52 | 53 | This parameter requires the ultimate rolename be syntactically valid. There is no way to verify a role is valid from the start, just that it *appears* to be a valid role. The error message is: 54 | 55 | `Error: argument --target-role Invalid target role.` 56 | 57 | #### Control Account #### 58 | 59 | * Short: `-A` 60 | * Long: `--control-account=` 61 | 62 | This parameter specifies the AWS account acting as a control plane to the account you want to assume-role into; this is the first jump in the 'double-jump'. 63 | 64 | Example: `123456789012` 65 | 66 | This parameter requires a 12-digit AWS account number. If the provided account number is invalid, assumer will output an error message: 67 | 68 | `Error: argument --control-account Must be a 12-digit AWS account number.` 69 | 70 | #### Control Role #### 71 | 72 | * Short: `-R` 73 | * Long: `--control-role=` 74 | 75 | This parameter specifies the role that will be assumed in the control plane account. The assumer tool will build the ARN from the account number and knowledge of AWS syntax, leaving just the role path and name to be specified. 76 | 77 | Example: `my-role-path/my-control-role-name` 78 | 79 | This parameter requires the ultimate rolename be syntactically valid. There is no way to verify a role is valid from the start, just that it *appears* to be a valid role. The error message is: 80 | 81 | `Error: argument --control-role Invalid target role.` 82 | 83 | ### Optional Flags ### 84 | 85 | #### Region #### 86 | 87 | * Short: `-e` 88 | * Long: `--region=` 89 | 90 | This parameter allows specifying the AWS region to operate in. The default is `us-west-2`. Any AWS region name can be specified. 91 | 92 | Example: `us-east-1` 93 | 94 | #### Username #### 95 | 96 | * Short: `-u` 97 | * Long: `--username=` 98 | 99 | This parameter allows overriding the host operating system reported username for the IAM username associated with your MFA device. 100 | 101 | The default is to query the host operating system for `whoami` and use that value. 102 | 103 | #### Profile #### 104 | * Short: `-o` 105 | * Long: `--profile=` 106 | 107 | This parameter allows the user to set which credential profile to use from their `.aws/credentials` file. 108 | 109 | **Note:** The AWS SDK looks for credentials in this order: 110 | 1. ENV['AWS_ACCESS_KEY_ID'] and ENV['AWS_SECRET_ACCESS_KEY'] 111 | 1. The shared credentials ini file at ~/.aws/credentials (more information) 112 | 1. From an instance profile (when running on EC2) 113 | 114 | If you are having unexpected access denied errors, it may be from credentials that have been previously loaded into your shell's environment, *or* specifying an incorrect profile. 115 | 116 | #### GUI #### 117 | * Short: `-g` 118 | * Long: `--gui` 119 | 120 | This parameter requests Assumer to build a URL for access to the AWS console with the final assumed credentials, and open it with the default web browser. 121 | 122 | #### Prompt #### 123 | * Short: `-p` 124 | * Long: `--pry` 125 | 126 | This parameter requests Assumer to spawn a Pry shell with the final assumed credentials made available within the shell. This allows for interactive usage of the AWS Ruby SDK with the assume-role credentials. 127 | 128 | ## Enable AWS Bundled CA Certificate ## 129 | 130 | * Short: **this option does not have a guaranteed short option** 131 | * Long: `--enable-aws-bundled-ca-cert` 132 | 133 | This parameter is used to signal to the SDK that it should use the certificate store bundled with the SDK instead of relying on the system's CA store. This can manifest itself as an error that looks like: `Seahorse::Client::Http::Error: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed from...` When this happens, a user can fix their installation of certificates, configure their system with certificates (such as the ones from [cURL](https://curl.haxx.se/docs/caextract.html)), or pass this option to use the bundled certificates. This option *only* applies to HTTPS requests made by the AWS SDK, and not any other HTTPS requests made by the gem. 134 | 135 | #### Debug #### 136 | * Long: `--debug` 137 | 138 | This option will output a lot of debugging information about options set and internal going-ons of Assumer. 139 | 140 | #### Version #### 141 | * Short: `-v` 142 | * Long: `--version` 143 | 144 | This flag will cause Assumer to print it's version string *and exit*. Not compatible with other options. 145 | 146 | #### Help #### 147 | * Short: `-h` 148 | * Long: `--help` 149 | 150 | This flag will cause Assumer to print it's help text, including summarized information for all these flags, *and exit*. Not compatible with other options. 151 | 152 | 153 | 154 | ## Ruby Gem ## 155 | -------------------------------------------------------------------------------- /source/exe/assumer: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env ruby 2 | require 'pry' # External gem 3 | require 'trollop' # External gem 4 | 5 | require 'tempfile' # Ruby core 6 | require 'net/http' # Ruby core 7 | require 'rbconfig' # Ruby core 8 | 9 | require 'assumer' # This gem 10 | 11 | parsed_options = Trollop::options do 12 | version "Assumer v#{Assumer::VERSION}" 13 | banner 'Parameters:' 14 | opt :target_account, 'Target AWS account to assume into', short: '-a', type: :string 15 | opt :target_role, 'The role in the target account', short: '-r', type: :string 16 | opt :control_account, 'Control Plane AWS account', short: '-A', type: :string 17 | opt :control_role, 'The role in the control account', short: '-R', type: :string 18 | banner 'These parameters are optional:' 19 | opt :region, 'AWS region to operate in', default: 'us-east-1', type: :string 20 | opt :username, 'Your IAM username', short: '-u', default: `whoami`.chomp, type: :string 21 | opt :profile, 'Profile name from ~/.aws/credentials', short: '-o', type: :string 22 | opt :gui, 'Open a web browser to the AWS console with these credentials' 23 | opt :pry, 'Open a pry shell with these credentials', short: '-p' 24 | opt :enable_aws_bundled_ca_cert, 'Option to enable the certificate store bundled with the AWS SDK' 25 | opt :debug, 'Output debugging information' 26 | end 27 | 28 | DEBUG_FLAG = parsed_options[:debug] 29 | warn "Options understood to be the following:\n#{parsed_options}" if DEBUG_FLAG 30 | 31 | Trollop::die :target_account, 'Must be a 12-digit AWS account number' unless parsed_options[:target_account] =~ /\d{12}/ 32 | Trollop::die :control_account, 'Must be a 12-digit AWS account number' unless parsed_options[:control_account] =~ /\d{12}/ 33 | 34 | mfa_serial_number = "arn:aws:iam::#{parsed_options[:control_account]}:mfa/#{parsed_options[:username]}" 35 | control_plane_role = "arn:aws:iam::#{parsed_options[:control_account]}:role/#{parsed_options[:control_role]}" 36 | target_account_role = "arn:aws:iam::#{parsed_options[:target_account]}:role/#{parsed_options[:target_role]}" 37 | 38 | warn "MFA Serial Number: #{mfa_serial_number}" if DEBUG_FLAG 39 | warn "Control Plane Role: #{control_plane_role}" if DEBUG_FLAG 40 | warn "Target Account Role: #{target_account_role}" if DEBUG_FLAG 41 | 42 | puts <>> AWS bunled CA certificate enabled <<< ' if DEBUG_FLAG 55 | Aws.use_bundled_cert! 56 | end 57 | 58 | def debug_credential_output(credentials:) 59 | " Access Key Id: #{credentials.access_key_id[0..5]}...#{credentials.access_key_id[-4..-1]} 60 | Secret Access Key: #{credentials.secret_access_key[0..5]}...#{credentials.secret_access_key[-4..-1]} 61 | Session Token: #{credentials.session_token[0..5]}...#{credentials.session_token[-4..-1]}" 62 | end 63 | 64 | # First jump 65 | begin 66 | control_creds = Assumer::Assumer.new( 67 | region: parsed_options[:region], 68 | account: parsed_options[:control_account], 69 | role: control_plane_role, 70 | serial_number: mfa_serial_number, 71 | profile: parsed_options[:profile] 72 | ) 73 | rescue Assumer::AssumerError => e 74 | puts "Error in first jump: #{e.message}" 75 | puts "#{e.cause.class}: #{e.cause}" if DEBUG_FLAG 76 | puts e.backtrace if DEBUG_FLAG 77 | exit -1 78 | end 79 | 80 | if DEBUG_FLAG 81 | warn 'First Jump Credentials:' 82 | warn debug_credential_output(credentials: control_creds.assume_role_credentials.credentials) 83 | end 84 | 85 | # Second jump 86 | begin 87 | target_creds = Assumer::Assumer.new( 88 | region: parsed_options[:region], 89 | account: parsed_options[:target_account], 90 | role: target_account_role, 91 | credentials: control_creds 92 | ) 93 | rescue Assumer::AssumerError => e 94 | puts "Error in second jump: #{e.message}" 95 | puts "#{e.cause.class}: #{e.cause}" if DEBUG_FLAG 96 | puts e.backtrace if DEBUG_FLAG 97 | exit -1 98 | end 99 | 100 | if DEBUG_FLAG 101 | warn 'Second Jump Credentials:' 102 | warn debug_credential_output(credentials: target_creds.assume_role_credentials.credentials) 103 | end 104 | 105 | region = parsed_options[:region] 106 | aws_access_key_id = target_creds.assume_role_credentials.credentials.access_key_id 107 | aws_secret_access_key = target_creds.assume_role_credentials.credentials.secret_access_key 108 | aws_session_token = target_creds.assume_role_credentials.credentials.session_token 109 | 110 | # Write to a file for the user to pull into their own shell if they'd like 111 | file = Tempfile.new('assumer') 112 | warn "Writing temp file #{file.path}" if DEBUG_FLAG 113 | # Prevents tempfile from being deleted when the Ruby object is garbage collected 114 | ObjectSpace.undefine_finalizer(file) 115 | 116 | # Write a different file depending on UNIX or Windows 117 | if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/ 118 | output = <<-EOF.gsub(/^ {2}/, '') 119 | set AWS_REGION=#{region} 120 | set AWS_ACCESS_KEY_ID=#{aws_access_key_id} 121 | set AWS_SECRET_ACCESS_KEY=#{aws_secret_access_key} 122 | set AWS_SESSION_TOKEN=#{aws_session_token} 123 | EOF 124 | puts "To import these values into the shell, execute .\\'#{file.path}'\n" 125 | elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd|darwin/ 126 | output = <<-EOF.gsub(/^ {2}/, '') 127 | export AWS_REGION=#{region} 128 | export AWS_ACCESS_KEY_ID=#{aws_access_key_id} 129 | export AWS_SECRET_ACCESS_KEY=#{aws_secret_access_key} 130 | export AWS_SESSION_TOKEN=#{aws_session_token} 131 | EOF 132 | puts "To import these values into the shell, source '#{file.path}'\n" 133 | end 134 | 135 | file.write(output) 136 | file.close 137 | warn "File '#{file.path}' closed" if DEBUG_FLAG 138 | 139 | # If GUI option was set, open default browser with creds into the account 140 | if parsed_options[:gui] 141 | print "Generating signin URL to #{parsed_options[:target_account]}..." 142 | issuer_url = 'assumer' 143 | console_url = 'https://console.aws.amazon.com/' 144 | signin_url = 'https://signin.aws.amazon.com/federation' 145 | # Compose credential block used to request login token 146 | session_json = { 147 | sessionId: aws_access_key_id, 148 | sessionKey: aws_secret_access_key, 149 | sessionToken: aws_session_token 150 | }.to_json 151 | 152 | # Request signin token from Federation endpoint (valid for 15 minutes) 153 | signin_token_url = <<-EOF.gsub(/^ {2}/, '') 154 | #{signin_url}?Action=getSigninToken&SessionType=json&Session=#{CGI.escape(session_json)} 155 | EOF 156 | returned_content = Net::HTTP.get(URI.parse(signin_token_url)) 157 | 158 | # Extract the signin token from the information returned by the federation endpoint. 159 | signin_token = JSON.parse(returned_content).fetch('SigninToken', {}) 160 | 161 | signin_token_param = "&SigninToken=#{CGI.escape(signin_token)}" 162 | 163 | # Create the URL to give to the user, which includes the 164 | # signin token and the URL of the console to open. 165 | # The 'issuer' parameter is optional but recommended. 166 | issuer_param = "&Issuer=#{CGI.escape(issuer_url)}" 167 | destination_param = "&Destination=#{CGI.escape(console_url)}" 168 | # Generate the signin URL, clean up the string 169 | login_url = <<-EOF.gsub(/^ {2}/, '').chomp 170 | #{signin_url}?Action=login#{signin_token_param}#{issuer_param}#{destination_param} 171 | EOF 172 | puts "Login URL is:\n#{login_url}" 173 | 174 | # Depending on the system we are running on, use the appropriate 175 | # system command to launch the default browser 176 | if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/ 177 | # On Windows, it matters what kind of quotes you use... 178 | warn "System command is: 'start \"\" \"#{login_url}\"'" if DEBUG_FLAG 179 | system "start \"\" \"#{login_url}\"" 180 | elsif RbConfig::CONFIG['host_os'] =~ /darwin/ 181 | warn 'System command is: ' + "open '#{login_url}'" if DEBUG_FLAG 182 | system "open '#{login_url}'" 183 | elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/ 184 | warn 'System command is: ' + "xdg-open '#{login_url}'" if DEBUG_FLAG 185 | system "xdg-open '#{login_url}'" 186 | end 187 | # If a pry shell was requested, deliver one with credentials available 188 | elsif parsed_options[:pry] 189 | puts "Your Assumer object within pry is 'target_creds'" 190 | binding.pry(quiet: true) 191 | end 192 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------