├── .github
├── ISSUE_TEMPLATE.md
├── PULL_REQUEST_TEMPLATE.md
└── workflows
│ ├── build.yml
│ ├── release.yml
│ └── test.yml
├── .gitignore
├── .goreleaser.yml
├── CHANGELOG.md
├── LICENSE
├── Makefile
├── README.md
├── awsu.go
├── command
├── command.go
├── console.go
├── register.go
├── root.go
├── token.go
├── unregister.go
└── version.go
├── config
├── .awsu
├── config.go
├── config_test.go
├── console.go
├── profile.go
├── profiles.go
├── register.go
└── testdata
│ ├── config
│ ├── config-merged
│ ├── credentials
│ └── merged
├── console
└── console.go
├── go.mod
├── go.sum
├── log
├── log.go
└── log_test.go
├── source
├── manual
│ └── manual.go
├── source.go
└── yubikey
│ └── yubikey.go
├── strategy
├── assume_role.go
├── credentials
│ └── credentials.go
├── long_term.go
├── session_token.go
└── strategy.go
└── target
└── mfa
├── mfa.go
├── name.go
└── name_test.go
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## Expected Behavior
5 |
6 | {Please write here}
7 |
8 |
9 | ## Actual Behavior
10 |
11 | {Please write here}
12 |
13 |
14 | ## Steps to Reproduce (including precondition)
15 |
16 | {Please write here}
17 |
18 |
19 | ## Screenshot on This Problem (if possible)
20 |
21 | {Please write here}
22 |
23 |
24 | ## Your Environment
25 |
26 | - OS: {Please write here}
27 | - passgen version: {Please write here}
28 |
29 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## What does this do / why do we need it?
5 |
6 | {Please write here}
7 |
8 |
9 | ## How this PR fixes the problem?
10 |
11 | {Please write here}
12 |
13 |
14 | ## What should your reviewer look out for in this PR?
15 |
16 | {Please write here}
17 |
18 |
19 | ## Check lists
20 |
21 | * [ ] Test passed
22 | * [ ] Coding style (indentation, etc)
23 |
24 |
25 | ## Additional Comments (if any)
26 |
27 | {Please write here}
28 |
29 |
30 | ## Which issue(s) does this PR fix?
31 |
32 |
36 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: build
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | pull_request:
8 | types: ['opened', 'synchronize']
9 | paths:
10 | - '**.go'
11 | - go.mod
12 | - '.github/workflows/**'
13 |
14 | jobs:
15 | artifact-build:
16 | runs-on: ${{ matrix.os }}
17 | strategy:
18 | fail-fast: false
19 | matrix:
20 | os: [ubuntu-latest, macos-latest]
21 | steps:
22 | - name: Checkout
23 | uses: actions/checkout@v3
24 | with:
25 | fetch-depth: 0
26 | - name: Set up Go
27 | uses: actions/setup-go@v3
28 | with:
29 | go-version: 1.19
30 | - name: Setup dependencies
31 | if: matrix.os == 'ubuntu-latest'
32 | run: |
33 | sudo apt-get update -q
34 | sudo apt-get install -qqy build-essential software-properties-common pkg-config wget libpcsclite-dev
35 | - name: Build darwin
36 | if: matrix.os == 'macos-latest'
37 | run: |
38 | make build/awsu-darwin-amd64
39 | mv build/awsu-darwin-amd64 build/awsu-macos-latest-amd64
40 | - name: Build linux
41 | if: matrix.os == 'ubuntu-latest'
42 | run: |
43 | make build/awsu-linux-amd64
44 | mv build/awsu-linux-amd64 build/awsu-ubuntu-latest-amd64
45 | - uses: actions/upload-artifact@v3
46 | with:
47 | name: awsu-${{ matrix.os }}-amd64
48 | path: build/awsu-${{ matrix.os }}-amd64
49 |
50 | release-test:
51 | runs-on: ubuntu-latest
52 | needs: [artifact-build]
53 | steps:
54 | - name: Checkout
55 | uses: actions/checkout@v3
56 | with:
57 | fetch-depth: 0
58 | # need to setup to avoid https://goreleaser.com/deprecations/#builds-for-darwinarm64
59 | - name: Set up Go
60 | uses: actions/setup-go@v3
61 | with:
62 | go-version: 1.19
63 | - name: Download macos
64 | uses: actions/download-artifact@v3
65 | with:
66 | name: awsu-macos-latest-amd64
67 | path: build
68 | - name: Download linux
69 | uses: actions/download-artifact@v3
70 | with:
71 | name: awsu-ubuntu-latest-amd64
72 | path: build
73 | - name: Correct goreleaser prebuilt path
74 | run: |
75 | # as it is the format goreleaser expects. See .goreleaser.yml -> prebuilt -> path
76 | # we need at least an arm url for brew: https://github.com/kreuzwerker/homebrew-taps/issues/11
77 | cp build/awsu-ubuntu-latest-amd64 build/awsu_linux_amd64
78 | cp build/awsu-ubuntu-latest-amd64 build/awsu_linux_arm64
79 | cp build/awsu-macos-latest-amd64 build/awsu_darwin_amd64
80 | cp build/awsu-macos-latest-amd64 build/awsu_darwin_arm64
81 | ls -lash build
82 | - name: Run GoReleaser
83 | uses: goreleaser/goreleaser-action@v4
84 | with:
85 | distribution: goreleaser-pro
86 | version: latest
87 | args: release --clean --skip-publish --snapshot --skip-sign --debug
88 | env:
89 | GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}
90 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
91 | GORELEASER_TOKEN: ${{ secrets.GORELEASER_TOKEN }}
92 | - name: List goreleaser dist folder contents
93 | run: |
94 | ls -lash dist
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: goreleaser
2 |
3 | on:
4 | push:
5 | tags:
6 | - '*'
7 |
8 | jobs:
9 | artifact-build:
10 | runs-on: ${{ matrix.os }}
11 | strategy:
12 | fail-fast: false
13 | matrix:
14 | os: [ubuntu-latest, macos-latest]
15 | steps:
16 | - name: Checkout
17 | uses: actions/checkout@v3
18 | with:
19 | fetch-depth: 0
20 | - name: Set up Go
21 | uses: actions/setup-go@v3
22 | with:
23 | go-version: 1.19
24 | - name: Setup dependencies
25 | if: matrix.os == 'ubuntu-latest'
26 | run: |
27 | sudo apt-get update -q
28 | sudo apt-get install -qqy build-essential software-properties-common pkg-config wget libpcsclite-dev
29 | - name: Build darwin
30 | if: matrix.os == 'macos-latest'
31 | run: |
32 | make build/awsu-darwin-amd64
33 | mv build/awsu-darwin-amd64 build/awsu-macos-latest-amd64
34 | - name: Build linux
35 | if: matrix.os == 'ubuntu-latest'
36 | run: |
37 | make build/awsu-linux-amd64
38 | mv build/awsu-linux-amd64 build/awsu-ubuntu-latest-amd64
39 | - uses: actions/upload-artifact@v3
40 | with:
41 | name: awsu-${{ matrix.os }}-amd64
42 | path: build/awsu-${{ matrix.os }}-amd64
43 |
44 | release:
45 | runs-on: ubuntu-latest
46 | needs: [artifact-build]
47 | steps:
48 | - name: Checkout
49 | uses: actions/checkout@v3
50 | with:
51 | fetch-depth: 0
52 | # need to setup to avoid https://goreleaser.com/deprecations/#builds-for-darwinarm64
53 | - name: Set up Go
54 | uses: actions/setup-go@v3
55 | with:
56 | go-version: 1.19
57 | - name: Download macos
58 | uses: actions/download-artifact@v3
59 | with:
60 | name: awsu-macos-latest-amd64
61 | path: build
62 | - name: Download linux
63 | uses: actions/download-artifact@v3
64 | with:
65 | name: awsu-ubuntu-latest-amd64
66 | path: build
67 | - name: Correct goreleaser prebuilt path
68 | run: |
69 | # as it is the format goreleaser expects. See .goreleaser.yml -> prebuilt -> path
70 | # we need at least an arm url for brew: https://github.com/kreuzwerker/homebrew-taps/issues/11
71 | cp build/awsu-ubuntu-latest-amd64 build/awsu_linux_amd64
72 | cp build/awsu-ubuntu-latest-amd64 build/awsu_linux_arm64
73 | cp build/awsu-macos-latest-amd64 build/awsu_darwin_amd64
74 | cp build/awsu-macos-latest-amd64 build/awsu_darwin_arm64
75 | ls -lash build
76 | - name: Run GoReleaser
77 | uses: goreleaser/goreleaser-action@v4
78 | with:
79 | distribution: goreleaser-pro
80 | version: latest
81 | args: release --clean
82 | env:
83 | GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}
84 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
85 | GORELEASER_TOKEN: ${{ secrets.GORELEASER_TOKEN }}
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: tests
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | paths-ignore:
8 | - 'README.md'
9 | pull_request:
10 | types: ['opened', 'synchronize']
11 | paths-ignore:
12 | - 'README.md'
13 | jobs:
14 | unit:
15 | runs-on: ubuntu-20.04
16 | steps:
17 | - name: Checkout
18 | uses: actions/checkout@v3
19 | with:
20 | fetch-depth: 0
21 | - name: Set up Go
22 | uses: actions/setup-go@v3
23 | with:
24 | go-version: 1.19
25 | - name: Setup Dependencies
26 | run: |
27 | sudo apt-get update -q
28 | sudo apt-get install -qqy libpcsclite-dev
29 | - name: Run tests
30 | run: make test
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .awsu*
2 | build/
3 | exp/
4 | .token
5 | vendor/
6 |
7 | dist/
8 | .vscode
9 | # during GH action release
10 | default.profraw
--------------------------------------------------------------------------------
/.goreleaser.yml:
--------------------------------------------------------------------------------
1 | builds:
2 | - id: "awsu-linux-darwin"
3 | builder: prebuilt
4 | goos:
5 | - linux
6 | - darwin
7 | goarch:
8 | - amd64
9 | - arm64
10 | goamd64:
11 | - v1
12 | prebuilt:
13 | path: build/awsu_{{ .Os }}_{{ .Arch }}
14 | archives:
15 | - name_template: >-
16 | {{ .ProjectName }}_
17 | {{- title .Os }}_
18 | {{- if eq .Arch "amd64" }}x86_64
19 | {{- else if eq .Arch "arm64" }}arm
20 | {{- else }}{{ .Arch }}{{ end }}
21 | checksum:
22 | name_template: 'checksums.txt'
23 | snapshot:
24 | name_template: "{{ incpatch .Tag }}-next"
25 | changelog:
26 | sort: asc
27 | filters:
28 | exclude:
29 | - '^docs:'
30 | - '^test:'
31 | brews:
32 | - tap:
33 | owner: kreuzwerker
34 | name: homebrew-taps
35 | token: "{{ .Env.GORELEASER_TOKEN }}"
36 | homepage: "https://github.com/kreuzwerker/awsu"
37 | description: "It provides a convenient integration of AWS virtual MFA devices into commandline based workflows."
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable [changes](http://keepachangelog.com/en/1.0.0/) to this project will be documented in this file.
4 |
5 | ## [2.3.2]
6 |
7 | ### Added
8 |
9 | - Add small documentation regarding the usage of the magic account ID (#35)
10 |
11 | ### Changed
12 |
13 | - Updated dependencies and fixed Catalina compatibility (#39) - thanks @nauxliu
14 | - Fixed typo in `README` (#37)
15 |
16 | ## [2.3.1]
17 |
18 | ### Added
19 |
20 | - Added support for command to generate OTP token on Yubikey and return it to stdout (#32)
21 |
22 | ### Changed
23 |
24 | - Fixed wrong default for config file (#31)
25 |
26 | ## [2.3.0]
27 |
28 | ### Added
29 |
30 | - Added environment variables and config flags for all configuration mechanisms
31 | - Added support for long-term credential console link generation
32 |
33 | ### Changed
34 |
35 | - Fixed expires output bug and added expiry hints
36 | - Added better looking error handling
37 | - Massive update to the `README`
38 |
39 | #### Internal
40 |
41 | - Removed cache and session ttl mechanism and replaced it with duration and grace
42 | - Created new client structure with explicit generators, sources and target
43 | - Moved logic for console out of the command and into a dedicated helper
44 |
45 | ### Removed
46 |
47 | - Removed "list" command
48 |
49 | ## [2.2.1]
50 |
51 | ### Added
52 |
53 | - The MFA serial can now additionally be specified using `-m`, `--mfa-serial` or `AWSU_MFA_SERIAL`
54 | - A new generator (next to the default `yubikey`) called `manual` has been exposed using `-g`, `--generator` or `AWSU_TOKEN_GENERATOR` - this can be used to manually enter tokens for scenarios where roles are used in contexts where IAM policy [conditions](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_sample-policies.html#ExampleMFADenyNotRecent) don't prevent the usage of tokens that are older than e.g. 1 hour
55 |
56 | ### Changed
57 |
58 | - Fixed #26 and #27 (Limit role credential duration to AWS default of 1 hour)
59 |
60 | ## [2.2.0]
61 |
62 | ### Changed
63 |
64 | - Fixed #23 (Increase role and session token duration)
65 | - Fixed bug with missing grace period in session token
66 |
67 | ## [2.1.1]
68 |
69 | ### Changed
70 |
71 | - Fixed #21 (Don’t get session token w/o MFA)
72 |
73 | ## [2.1.0]
74 |
75 | ### Changed
76 |
77 | - Abandonded SDK internal logic for assuming roles with tokens and read shared configs directly instead
78 | - Dropped workspace support for the time being - directly select profiles with `-p` or `AWS_PROFILE` instead
79 | - Always get session token (including MFA) before doing anything else - this allows assuming the role in another tool e.g. Terraform while still having a MFA in the mix
80 | - Changed cache location of the sessions to just use the name of the profile
81 |
82 | ### Added
83 |
84 | - Added `list` command to show all configured profiles
85 | - Added `no-cache` option to prevent caching
86 |
87 | ## [2.0.2]
88 |
89 | ### Changed
90 |
91 | - Put instructions on how to delete the MFA into registration error message
92 |
93 | ## [2.0.1]
94 |
95 | ### Added
96 |
97 | - Added config-file-less mode using environment variables (e.g. in case Terraform is not used)
98 | - Trigger verbose mode via `AWSU_VERBOSE`
99 |
100 | ### Changed
101 |
102 | - Use username for virtual device name (instead of random id) - this should make self-service policies possible again
103 | - Added missing `export` prefix to export mode
104 | - Log code when fetching from Yubikey
105 | - Always assume roles for 1h
106 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | VERSION := "2.3.10"
2 |
3 | BUILD := $(shell git rev-parse --short HEAD)
4 | FLAGS := "-s -w -X=main.build=$(BUILD) -X=main.time=`TZ=UTC date '+%FT%TZ'` -X=main.version=$(VERSION)"
5 | REPO := awsu
6 | USER := kreuzwerker
7 |
8 | build/awsu-linux-amd64:
9 | @mkdir -p build
10 | nice docker container run --rm \
11 | -v $(PWD):/build/awsu \
12 | -w /build/awsu \
13 | golang:1.19rc1-stretch bash -c \
14 | "apt-get update -q && apt-get install -qqy libpcsclite-dev && go mod download && go build -o $@ -ldflags $(FLAGS) awsu.go"
15 |
16 | build/awsu-linux-amd64-ubuntu:
17 | @mkdir -p build
18 | nice docker container run --rm -e DEBIAN_FRONTEND=noninteractive \
19 | -v $(PWD):/build/awsu \
20 | -w /build/awsu \
21 | ubuntu:20.04 bash -c \
22 | "apt-get update -q && apt-get install -qqy build-essential software-properties-common pkg-config wget libpcsclite-dev && wget -c https://dl.google.com/go/go1.19.5.linux-amd64.tar.gz -O - | tar -xz -C /usr/local && export PATH=$$PATH:/usr/local/go/bin && go mod download && go build -o $@ -ldflags $(FLAGS) awsu.go"
23 |
24 | # Test within the container
25 | # curl -sL https://git.io/goreleaser | bash -s -- --clean --skip-publish --snapshot --skip-sign --debug
26 |
27 | build/awsu-darwin-amd64:
28 | @mkdir -p build
29 | nice go build -o $@ -ldflags $(FLAGS) awsu.go
30 |
31 | build: build/awsu-darwin-amd64 build/awsu-linux-amd64;
32 |
33 | clean:
34 | rm -rf build
35 |
36 | test:
37 | go list ./... | grep -v exp | xargs go test -cover
38 |
39 | .PHONY: build clean release retract test
40 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Amazon Web Services Switch User (`awsu`)
2 |
3 | [](https://github.com/kreuzwerker/awsu/releases)
4 | [](https://github.com/kreuzwerker/awsu/actions)
5 | [](http://godoc.org/github.com/kreuzwerker/awsu)
6 | [](https://goreportcard.com/report/github.com/kreuzwerker/awsu)
7 |
8 | `awsu` provides a convenient integration of [AWS](https://aws.amazon.com/) virtual [MFA devices](https://aws.amazon.com/iam/details/mfa/) into commandline based workflows. It does use [Yubikeys](https://www.yubico.com/) to provide the underlying [TOTP](https://tools.ietf.org/html/rfc6238) one-time passwords but does not rely on additional external infrastructure such as e.g. federation.
9 |
10 | There is also a high-level video overview from [This Is My Architecture](https://amzn.to/2Tpiv1m) Munich:
11 |
12 | [](https://www.youtube.com/watch?v=4FUqak5E_CA)
13 |
14 | [ [Installation](#installation) | [Usage](#usage) | [Configuration](#configuration) | [Caching](#caching) | [Commands](#commands) | [General multifactor considerations](#general-multifactor-considerations) ]
15 |
16 | # Installation
17 |
18 | Production-ready Mac releases can be installed e.g.through `brew` via [kreuzwerker/homebrew-taps](https://github.com/kreuzwerker/homebrew-taps):
19 |
20 | ```
21 | brew tap kreuzwerker/taps && brew install kreuzwerker/taps/awsu
22 | ```
23 |
24 | Linux is only available for download from the release tab. No Windows builds are provided at the moment.
25 |
26 | ## Prequisites
27 |
28 | `awsu` relies on [shared credentials files](https://aws.amazon.com/blogs/security/a-new-and-standardized-way-to-manage-credentials-in-the-aws-sdks/) (the same configuration files that other tools such as e.g. the [AWS commandline utilities](https://aws.amazon.com/cli/) are also using) being configured. The profiles are used to determine
29 |
30 | 1. which IAM long-term credentials ([access key pairs](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys)) are going to be used
31 | 2. if a / which virtual MFA device is going to be used
32 | 3. if a / which [IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) is going be used
33 |
34 | In contrast to the official AWS CLI `awsu` also supports putting an `mfa_serial` key into a profile which contains long-term credentials (instead of a role). In this case a virtual MFA device is _always_ used when using the long-term credential profile in question.
35 |
36 | # Usage
37 |
38 | An abstract overview of the usage workflow of `awsu` looks like this:
39 |
40 | 1. You ensure you fulfill the prerequisites above
41 | 2. You start using `awsu` by using the `register` command: this will create a virtual MFA device on AWS, store the secret of that device on your Yubikey and enable the virtual MFA device by getting two valid one-time passwords from the Yubikey
42 | 3. Now you just run `awsu` and - after a double-dash `—` - you specify the program you want to run in a given profile (e.g. `admin`); depending on the profile `awsu` will
43 | 1. determine the access-key pair to use
44 | 2. optionally use TOTP tokens from your Yubikey device (to get a session token from AWS in order to add the MFA context to the request) and
45 | 3. optionally assume an IAM role
46 | 4. use the credentials resulting from these operation(s), cache them and export them to the environment of the program specified after the double-dash
47 |
48 | Given the following shared credentials config:
49 |
50 | ```
51 | [default]
52 | aws_access_key_id = AKIAIOSFODNN7EXAMPLE
53 | aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
54 |
55 | [foo]
56 | aws_access_key_id = AKIAIFODNNOS7EXAMPLE
57 | aws_secret_access_key = bPxRfiCYEXAMPLEKEY/K7MDENG/wJalrXUtnFEMI
58 | mfa_serial = arn:aws:iam::123456789012:mfa/user@example.com
59 |
60 | [bar]
61 | mfa_serial = arn:aws:iam::123456789012:mfa/user@example.com
62 | role_arn = arn:aws:iam::123456789012:role/foo-cross-account
63 | source_profile = default
64 |
65 | [wee]
66 | external_id = 1a03197b-3cb5-491b-bc06-84795afc95ef
67 | mfa_serial = arn:aws:iam::123456789012:mfa/user@example.com
68 | role_arn = arn:aws:iam::121234567890:role/bar-cross-account
69 | source_profile = default
70 |
71 | [gee]
72 | role_arn = arn:aws:iam::121234567890:role/wee-cross-account
73 | source_profile = foo
74 | ```
75 |
76 | `awsu` will produce the following results:
77 |
78 | | Profile | Credentials | Cached? | MFA? |
79 | | --------- | ---------------------------------------------------- | ------- | ------------------------ |
80 | | `default` | Long-term* | No* | No* |
81 | | `foo` | Short-term session-token | Yes | Yes, from "foo" itself** |
82 | | `bar` | Short-term session-token, then role | Yes | Yes, from "bar" itself |
83 | | `wee` | Short-term session-token, then role with external ID | Yes | Yes, from "wee" itself |
84 | | `gee` | Short-term session-token, then role | Yes | Yes, from "foo" |
85 |
86 | *) unless a MFA is specified as parameter to `awsu` - then a short-term session-token (equivalent to `foo`) is produced
87 |
88 | **) the form of using `mfa_serial` directly long-term credential profiles is not supported by the official AWS CLI (it will just ignore it) - please note that this form will _always_ produce short-term credentials which may not be useful in some circumstances e.g. when re-registering a previously unregistered virtual MFA device
89 |
90 | ## Configuration
91 |
92 | In the following the global configuration parameters are described. Note that all parameters are implemented as flags with environment variable equivalents - when these start with `AWS_` (like the setting of profiles) they have equivalent semantics to e.g. other SDK using applications such as the AWS CLI.
93 |
94 | ### Profile and shared credential files
95 |
96 | These options describe the currently selected profile and the locations of the shared credential files.
97 |
98 | | | Long | Short | Environment | Default |
99 | | --------------------------- | ------------------------- | ----- | ----------------------------- | --------- |
100 | | Currently used profile | `profile` | `p` | `AWS_PROFILE` | `default` |
101 | | Shared config file location | `config-file` | `c` | `AWS_CONFIG_FILE` | Platform |
102 | | Shared credentials file | `shared-credentials-file` | `s` | `AWS_SHARED_CREDENTIALS_FILE` | Platform |
103 |
104 | ### Short-term credentials
105 |
106 | These options describe caching options, session token and role durations and other aspects of short-term credentials.
107 |
108 | | Description | Long | Short | Environment | Default |
109 | | ------------------------------------------------------------ | ----------- | ----- | ---------------- | ------------------------------------------------------------ |
110 | | Disable caching | `no-cache` | `n` | `AWSU_NO_CACHE` | `false` |
111 | | Duration of session tokens & roles | `duration` | `d` | `AWSU_DURATION` | 1 hour, maximum depends on config of the role in question (up to 12 hours) |
112 | | Grace period until caches expire - in other words: the time a session will be guaranteed to be valid | `grace` | `r` | `AWSU_GRACE` | 45 minutes |
113 | | Source of OTP tokens | `generator` | `g` | `AWSU_GENERATOR` | `yubikey` - can be set to `manual` if you want to manually enter OTP passwords |
114 | | MFA serial override | `mfa` | `m` | `AWSU_SERIAL` | None - can be used to set or override MFA serials |
115 |
116 | ### Other
117 |
118 | | Description | Long | Short | Environment | Default |
119 | | --------------- | --------- | ----- | -------------- | ------- |
120 | | Verbose logging | `verbose` | `v` | `AWSU_VERBOSE` | `false` |
121 |
122 | ## Caching
123 |
124 | Caching is only used for cacheable (short-term) credentials. It can be disabled completely (even on a case-by-case basis) and is controlled by two primary factors: duration and grace.
125 |
126 | The duration is always equivalent to the duration of the session token used which - in turn - is equivalent to the duration of the optionally assumed role (1 hour by default).
127 |
128 | The grace period is the minimum safe distance to the duration before it's considered invalid (45 minutes by default). This is useful for dealing with long-running deployments that might be interrupted when e.g. a role becomes invalid mid-deployment.
129 |
130 | Example: in the default setting with a duration of 1 hour and a grace period of 45 minutes `awsu` will consider cached credentials invalid after 15 minutes.
131 |
132 | ## Commands
133 |
134 | ### Default
135 |
136 | The default command (invoking just `awsu`) has two modes: _export_ and _exec_. It supports just the global parameters described above.
137 |
138 | #### Export mode
139 |
140 | When `awsu` is invoked without additional arguments, the resulting credentials are exposed as shell exports. In this mode, `awsu` can be used with `eval` to actually set these variables like this:
141 |
142 | ```
143 | eval $(awsu)
144 | ```
145 |
146 | After using export mode, credentials can used until they expire.
147 |
148 | #### Exec mode
149 |
150 | When `awsu` is invoked with a doubledash (`--`) as the last argument it will execute the application specified after the doubledash (including all arguments) with the resulting credentials being set into the environment of this application.
151 |
152 | In exec mode it makes sense to use shell aliases to drive `awsu` like e.g. in zsh:
153 |
154 | ```
155 | alias aws="awsu -v -- aws"
156 | alias terraform="awsu -v -- terraform"
157 | # etc ...
158 | ```
159 |
160 | Note that when using this alias style:
161 |
162 | 1. you can always reference the alias targets with absolute paths to temporarily escape, e.g. by referring to `aws` as e.g. `/usr/local/bin/aws`
163 | 2. you can still configure `awsu` by using the environment variable style of parameter passing
164 |
165 | ### Register
166 |
167 | `awsu register :iam-username` will perform the following actions:
168 |
169 | 1. create a new virtual MFA device that is named after the `:iam-username`
170 | 2. store the secret key of this device with a name derived from the virtual MFA's serial number (ARN) that is compatible with Yubikey
171 | 3. enable the virtual MFA device with the given `:iam-username`
172 |
173 | After successful registration `awsu` will log the serial of the MFA for usage as `mfa_serial` in your profiles.
174 |
175 | #### Parameters
176 |
177 | The following parameters are exclusive to `register`.
178 |
179 | | Description | Long | Short | Environment | Default |
180 | | ------------------------------------------------------------ | -------- | ----- | ------------- | -------- |
181 | | Generates a QR code of the MFA secret that can be used for backup purposes on smartphones | `qr` | `q` | `AWSU_QR` | `true` |
182 | | Sets the "issuer" part of the QR code URL - depending on the smartphone app used this may add stylistic information to the one-time passwords (e.g. an icon) | `issuer` | `i` | `AWSU_ISSUER` | `Amazon` |
183 |
184 | ### Unregister
185 |
186 | `awsu unregister :iam-username` will perform the following actions:
187 |
188 | 1. deactivate the virtual MFA device that is named after the `:iam-username`
189 | 2. remove the matching TOTP secret from the Yubikey
190 | 3. delete the virtual MFA device that is named after the `:iam-username`
191 |
192 | ### Console
193 |
194 | `awsu console` will open (in a browser) the link to the AWS console for a profile. It supports:
195 |
196 | 1. long-term credentials
197 | 2. short-term credentials for
198 | 1. cross-account ("internal") roles
199 | 2. external ("federated") roles (role with an `external_id` field in their profile)
200 |
201 | #### Parameters
202 |
203 | The following parameters are exclusive to `console`.
204 |
205 | | Description | Long | Short | Environment | Default |
206 | | ------------------------------------------------------------ | ------ | ----- | ----------- | ------- |
207 | | Opens the resulting link in a browser (as opposed to just returning it) | `open` | `o` | `-` | `true` |
208 |
209 | ### Token
210 |
211 | `awsu token` will generate a fresh one-time password from an inserted Yubikey. In order to determine the correct secret it will
212 |
213 | 1. use the MFA directly configured on the currently used `profile` or
214 | 2. use the the MFA configured through the `mfa-serial` parameter.
215 |
216 | # General multifactor considerations
217 |
218 | The goal of this section is to consider the multifactor options that are available on AWS without involving additional external infrastructure (e.g. by utilizing [federation](https://aws.amazon.com/identity/federation/)). Under these constraints there are two options available:
219 |
220 | 1. Restricing access by IPv4 addresses and/or networks, expressed in [CIDR](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation
221 | 1. Easy to implement in AWS and requires no additional effort except for the control of static IPv4 IPs or ranges
222 | 2. Hard to restrict to the right people in an organization e.g. your operators network vs. your backoffice network or guest wifi network
223 | 3. Some impact on remote workers - you'll need a VPN solution that routes all traffic for [AWS IP addresses](https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html) (or just all traffic)
224 | 4. Difficult to spoof unless you are a very privileged attacker
225 | 2. Restricing access by proving the possession of a [virtual or hardware MFA device](https://aws.amazon.com/iam/details/mfa/), specifically a device that can emit 6-digits [TOTP](https://tools.ietf.org/html/rfc6238) one-time passwords (OTP)
226 | 1. More difficult to implement in AWS since you'll want to introduce smartcards as sources for OTPs (unless users want to type in OTPs every _n_ minutes) - `awsu` supports [Yubikey](https://www.yubico.com/products/yubikey-hardware/) USB smartcards here
227 | 2. Easy to restrict in usage to the right people since MFA devices are first-class entities in IAM
228 | 3. No impact on remote workers
229 | 4. Difficult to spoof due to the aggressive rate-limits of MFA authentication attempts - since AWS uses a 6-digit configuration it's nevertheless possible and failures to authenticate with MFA should be monitoried through AWS CloudTrail
230 |
231 | When possible we recommend to require both seconds factors.
232 |
233 | ## Providing second factors
234 |
235 | IP based second factors are provided implicitly by virtue of being the address from which a request originates.
236 |
237 | MFA based second factors are provided through one of the following mechanisms:
238 |
239 | 1. Using long-term credentials (the access key pair associated with an IAM user) to get a [session token via STS](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html)
240 | 1. this yields new short-term credentials (a new access key pair plus the session token itself) that now contains
241 | 1. the information about the MFA context but
242 | 2. no new principal (the IAM user remains the principal)
243 | 2. a session token can be requested to be valid for a period between 15 minutes and 12 hours - there is no way of directly configuring an upper ceiling
244 | 2. Using long- or short-term credentials to [assume a role via STS](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html)
245 | 1. this yields new short-term credentials with a new principal (the role)
246 | 1. when using long-term credentials the MFA serial and OTP token must be passed to the STS API when assuming the role
247 | 2. when using short-credentials aquired from the session token mechanism described above the MFA serial and OTP token can be omitted
248 | 3. in both cases the role now includes a MFA context
249 | 2. a role can be requested to be valid for a period between 15 minutes and 12 hours - it's upper ceiling (between 1 hour and 12 hours, with 1 hour being the default) is configured directly on the IAM role
250 |
251 | ## Requiring second factors
252 |
253 | Second factor requirements are expressed in the form of [global conditions keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html) in the the optional `Condition` block that is found in most of the available types of IAM policies such as
254 |
255 | 1. [Trust policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html) of roles
256 | 2. Policies attached to e.g. roles or users
257 | 3. [Permission boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) attached to e.g. roles or users
258 | 4. Selected service policies e.g. [S3 bucket policies](https://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html#example-bucket-policies-use-case-3)
259 |
260 | [Service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_scp-syntax.html) that can be applied globally on [AWS Organization](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html) members are not supported at the moment.
261 |
262 | Regardless of its location the `Condition` for an IP-based second factor would look like this:
263 |
264 | ```json
265 | "IpAddress": {
266 | "aws:SourceIp": "203.0.113.0/24"
267 | }
268 | ```
269 |
270 | The `Condition` content for an MFA-based second factor can have two forms.
271 |
272 | The "age" form:
273 |
274 | ```json
275 | "NumericLessThan": {
276 | "aws:MultiFactorAuthAge": "3600"
277 | }
278 | ```
279 |
280 | Or the "boolean" form:
281 |
282 | ```json
283 | "Bool": {
284 | "aws:MultiFactorAuthPresent": "true"
285 | }
286 | ```
287 |
288 | The "age" form is preferred as the means of requiring a MFA. Since a session token (see the section before) cannot directly be configured for a maximum duration the "age" form is the only way to set an acceptable window for the proof of possession of a MFA device.
289 |
290 | ## Location implications
291 |
292 | The type of policy where a second factor requirement is enforced at has some implications.
293 |
294 | When applied to a non-trust policy, the requirement is enforced on _every_ interaction. That also means that if a permission is denied (e.g. due to `aws:MultiFactorAuthAge`) the user has not always a way of knowing exactly why it's denied (in some AWS APIs the `UnauthorizedOperation` response contains an `EncodedMessage` that can be decoded using the [appropriate STS API](https://docs.aws.amazon.com/STS/latest/APIReference/API_DecodeAuthorizationMessage.html) - this may or may not clarify a permission issue).
295 |
296 | When applied to a trust policy, the requirement is only enforced when _assuming the role_. Since a trust policy usually only regulates the acceptable principals (e.g. an AWS account) and second factor conditions the user should be able to deduce why the permission to assume the role has been denied (e.g. no access to the admin role in this account, not in the office / not dialed into the VPN, no MFA device active). Both approaches can also be mixed either through policies or through permission boundaries (under the usability constraints described above).
297 |
298 | Since an assumed role also has an explicit time-to-live that is clearly visible to users only using trust policies for MFA conditions makes MFA based second factors easier to handle in practice. This approach can be summarized as following:
299 |
300 | 1. A role requires the proof of posession once at the beginning of it's lifetime through an `aws:MultiFactorAuthAge` condition that should set to the duration attribute (the maximum lifetime) of a role (as discussed above: since an older session token could have been used to assume the role, the "boolean" form is not sufficient)
301 | 2. The longer a role can last, the greater the window of opportunity gets for an attacker to gain control of the principal (e.g. by gaining access to the computer where the short-term credentials reside)
302 | 3. Therefore long lasting session should have less permissions than shorter lasting roles
303 |
304 | This summary leads to the following basic setup recommendations:
305 |
306 | 1. Plan a permission schema that differentiates between the levels of access different functional roles should have - [typical examples](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_job-functions.html) include the AWS Managed Policies for Job Functions as well as e.g. roles for removing MFA devices from IAM users in self-service
307 | 2. Map those functional roles to IAM roles
308 | 1. Role durations and matching MFA conditions should reflect the level of access the associated policies will have
309 | 2. Consider that API operations carried with roles that expire mid-deployment will get aborted mid-deployment and that 1 hour might not be enough for certain operations to complete (such as e.g. RDS deployments) - `awsu` handles this problem by re-assuming roles that are due to expire in a configurable amount of time
310 | 3. Consider adopting an [AWS Organization setup with multiple member accounts](https://aws.amazon.com/answers/account-management/aws-multi-account-security-strategy/) and locate these roles in different accounts
311 | 3. Map the right to assume these IAM roles to IAM groups
312 | 1. Also give users in these groups (by using [policy variables](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html)) the right to [create](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateVirtualMFADevice.html) and [enable](https://docs.aws.amazon.com/IAM/latest/APIReference/API_EnableMFADevice.html) a virtual MFA device for themselves
313 | 2. Do not directly allow them to [deactive](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html) and [delete](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteVirtualMFADevice.html) their own MFA device (this would allow an attacker to simply replace an MFA device with one they control) - monitor deletions via CloudTrail and consider outsourcing this to dedicated privileged users or - at minimum - require second factors for the MFA deletion alone (directly or via a role dedicated to this purpose)
314 | 4. Do not give IAM users any other direct permissions
315 | 5. Add IAM users to IAM groups appropriate for their function roles
316 |
317 | ## Protecting second factor requirements
318 |
319 | With second factor conditions in various policies (likely in multiple accounts) in place one must consider protecting them from modification by regular and privileged users.
320 |
321 | Privileged users in this context are users that _can_ create and update IAM resources beyond the self-service permissions describe in the section above. Such privileged users are an unfortunate reality in AWS where service-linked permissions are not always fine-granular enough or are not supported at all. The unfortunate part is that it's currently [impossible to restrict](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html) role creation to service principals which implies that privileged users can create cross-account roles to arbitrary accounts.
322 |
323 | The following approaches are recommend in order to protect your second factor requirements:
324 |
325 | 1. Implement all IAM that regulate access under a dedicated [path](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html), e.g. `/master/`
326 | 2. Create an IAM policy ("master") that restricts create, update and delete operations on IAM resources under this path
327 | 1. attach this IAM policy as a permission boundary to your IAM roles
328 | 2. enforce the attachment of this permission boundary by expressing it as a `iam:PermissionsBoundary` condition to all [applicate IAM actions](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html)
329 | 3. Carefully monitor the creation of roles closely and consider implementing indirections (e.g. using the [AWS Service Catalog](https://aws.amazon.com/servicecatalog/)) as an alternative to directly creating IAM roles (e.g. for usage in [instance profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)) and IAM users (e.g. for creating [SMTP credentials](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html) for SES)
330 |
331 | Please don't hesitate to [contact us](https://kreuzwerker.de/) when you need consulting around the design of your organizational setup.
332 |
--------------------------------------------------------------------------------
/awsu.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/kreuzwerker/awsu/command"
5 | )
6 |
7 | var (
8 | build string
9 | time string
10 | version string
11 | )
12 |
13 | func main() {
14 | command.Execute(version, build, time)
15 | }
16 |
--------------------------------------------------------------------------------
/command/command.go:
--------------------------------------------------------------------------------
1 | package command
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "regexp"
7 | "time"
8 |
9 | "github.com/spf13/pflag"
10 | "github.com/spf13/viper"
11 | )
12 |
13 | const app = "awsu"
14 |
15 | var this = Version{}
16 |
17 | // Execute is the main entry point into the app
18 | func Execute(version, build, time string) {
19 |
20 | whitespace := regexp.MustCompile(`(\s{2,})`)
21 |
22 | this.Build = build
23 | this.Time = time
24 | this.Version = version
25 |
26 | if _, err := rootCmd.ExecuteC(); err != nil {
27 |
28 | fmt.Fprintf(os.Stderr, "error: %s\n",
29 | whitespace.ReplaceAllString(err.Error(), ""))
30 |
31 | os.Exit(-1)
32 |
33 | }
34 |
35 | }
36 |
37 | // flag adds configuration option with default value, long and short flags, a
38 | // matching environment (if not empty) and matching description
39 | func flag(fs *pflag.FlagSet, def interface{}, long, short, env, desc string) {
40 |
41 | switch t := def.(type) {
42 |
43 | case bool:
44 | fs.BoolP(long, short, t, desc)
45 | case time.Duration:
46 | fs.DurationP(long, short, t, desc)
47 | case string:
48 | fs.StringP(long, short, t, desc)
49 | default:
50 | panic(fmt.Sprintf("unexpected default value for type %T", def))
51 | }
52 |
53 | viper.BindPFlag(long, fs.Lookup(long))
54 |
55 | // don't bind to empty env
56 | if env != "" {
57 | viper.BindEnv(long, env)
58 | }
59 |
60 | viper.SetDefault(long, fs.Lookup(long).DefValue)
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/command/console.go:
--------------------------------------------------------------------------------
1 | package command
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/kreuzwerker/awsu/console"
7 | "github.com/skratchdot/open-golang/open"
8 | "github.com/spf13/cobra"
9 | "github.com/spf13/viper"
10 | )
11 |
12 | var consoleCmd = &cobra.Command{
13 |
14 | Use: "console",
15 | Short: "Generates link to or opens AWS console",
16 | PreRunE: func(cmd *cobra.Command, args []string) error {
17 | return viper.Unmarshal(&conf.Console)
18 | },
19 | RunE: func(cmd *cobra.Command, args []string) error {
20 |
21 | cons, err := console.New(&conf)
22 |
23 | if err != nil {
24 | return err
25 | }
26 |
27 | link, err := cons.Link()
28 |
29 | if err != nil {
30 | return err
31 | }
32 |
33 | if conf.Console.Open {
34 | return open.Run(link)
35 | }
36 |
37 | fmt.Println(link)
38 |
39 | return nil
40 |
41 | },
42 | }
43 |
44 | func init() {
45 |
46 | flag(consoleCmd.Flags(),
47 | true,
48 | "open",
49 | "o",
50 | "",
51 | "attempts to open the generated url in a browser",
52 | )
53 |
54 | rootCmd.AddCommand(consoleCmd)
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/command/register.go:
--------------------------------------------------------------------------------
1 | package command
2 |
3 | import (
4 | "encoding/base32"
5 | "fmt"
6 | "os"
7 |
8 | "github.com/kreuzwerker/awsu/log"
9 | "github.com/kreuzwerker/awsu/source/yubikey"
10 | "github.com/kreuzwerker/awsu/strategy"
11 | "github.com/kreuzwerker/awsu/target/mfa"
12 | qr "github.com/mdp/qrterminal"
13 | "github.com/spf13/cobra"
14 | "github.com/spf13/viper"
15 | )
16 |
17 | const (
18 | logSuccess = "MFA %q serial successfully registered"
19 | )
20 |
21 | var registerCmd = &cobra.Command{
22 |
23 | Use: "register :username",
24 | Short: "Initializes a device on AWS and Yubikey",
25 | Args: cobra.ExactArgs(1),
26 | PreRunE: func(cmd *cobra.Command, args []string) error {
27 | return viper.Unmarshal(&conf.Register)
28 | },
29 | RunE: func(cmd *cobra.Command, args []string) error {
30 |
31 | username := args[0]
32 |
33 | creds, err := strategy.Apply(&conf)
34 |
35 | if err != nil {
36 | return err
37 | }
38 |
39 | source, err := yubikey.New()
40 |
41 | if err != nil {
42 | return err
43 | }
44 |
45 | target, err := mfa.New(creds.NewSession(), source)
46 |
47 | if err != nil {
48 | return err
49 | }
50 |
51 | serial, secret, err := target.Add(username)
52 |
53 | if err != nil {
54 | return err
55 | }
56 |
57 | if conf.Register.QR {
58 |
59 | uri := fmt.Sprintf("otpauth://totp/%s@%s?secret=%s&issuer=%s",
60 | username,
61 | creds.Profile,
62 | base32.StdEncoding.EncodeToString(secret),
63 | conf.Register.Issuer,
64 | )
65 |
66 | qr.Generate(uri, qr.L, os.Stderr)
67 |
68 | }
69 |
70 | log.Info(logSuccess, *serial)
71 |
72 | return nil
73 |
74 | },
75 | }
76 |
77 | func init() {
78 |
79 | flag(registerCmd.Flags(),
80 | "Amazon",
81 | "issuer",
82 | "i",
83 | "AWSU_QR_ISSUER",
84 | "issuer parameter in the QR key uri",
85 | )
86 |
87 | flag(registerCmd.Flags(),
88 | true,
89 | "qr",
90 | "q",
91 | "AWSU_QR",
92 | "generate a QR barcode as backup for soft tokens",
93 | )
94 |
95 | rootCmd.AddCommand(registerCmd)
96 |
97 | }
98 |
--------------------------------------------------------------------------------
/command/root.go:
--------------------------------------------------------------------------------
1 | package command
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "time"
7 |
8 | "github.com/aws/aws-sdk-go/aws/defaults"
9 | "github.com/kreuzwerker/awsu/config"
10 | "github.com/kreuzwerker/awsu/strategy"
11 | "github.com/spf13/cobra"
12 | "github.com/spf13/viper"
13 | "github.com/yawn/doubledash"
14 | )
15 |
16 | var conf config.Config
17 |
18 | var rootCmd = &cobra.Command{
19 | Use: app,
20 | SilenceErrors: true,
21 | SilenceUsage: true,
22 | PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
23 |
24 | if err := viper.Unmarshal(&conf); err != nil {
25 | return err
26 | }
27 |
28 | return conf.Init()
29 |
30 | },
31 | RunE: func(cmd *cobra.Command, args []string) error {
32 |
33 | creds, err := strategy.Apply(&conf)
34 |
35 | if err != nil {
36 | return err
37 | }
38 |
39 | if len(doubledash.Xtra) > 0 {
40 | return creds.Exec(doubledash.Xtra[0], doubledash.Xtra)
41 | }
42 |
43 | fmt.Println(creds.String())
44 |
45 | return nil
46 |
47 | },
48 | }
49 |
50 | func init() {
51 |
52 | os.Args = doubledash.Args
53 |
54 | flag(rootCmd.PersistentFlags(),
55 | defaults.SharedConfigFilename(),
56 | "config-file",
57 | "c",
58 | "AWS_CONFIG_FILE",
59 | "sets the config file",
60 | )
61 |
62 | flag(rootCmd.PersistentFlags(),
63 | 1*time.Hour,
64 | "duration",
65 | "d",
66 | "AWSU_DURATION",
67 | "duration to use for session tokens and roles",
68 | )
69 |
70 | flag(rootCmd.PersistentFlags(),
71 | "",
72 | "mfa-serial",
73 | "m",
74 | "AWSU_MFA_SERIAL",
75 | "set or override MFA serial",
76 | )
77 |
78 | flag(rootCmd.PersistentFlags(),
79 | "yubikey",
80 | "generator",
81 | "g",
82 | "AWSU_TOKEN_GENERATOR",
83 | "configure the token generator to 'yubikey' or 'manual'",
84 | )
85 |
86 | flag(rootCmd.PersistentFlags(),
87 | 45*time.Minute,
88 | "grace",
89 | "r",
90 | "AWSU_GRACE",
91 | "distance to the duration before a cache credential is considered expired",
92 | )
93 |
94 | flag(rootCmd.PersistentFlags(),
95 | false,
96 | "no-cache",
97 | "n",
98 | "AWSU_NO_CACHE",
99 | "disable caching of short-term credentials",
100 | )
101 |
102 | flag(rootCmd.PersistentFlags(),
103 | "default",
104 | "profile",
105 | "p",
106 | "AWS_PROFILE",
107 | "shared config profile to use",
108 | )
109 |
110 | flag(rootCmd.PersistentFlags(),
111 | defaults.SharedCredentialsFilename(),
112 | "shared-credentials-file",
113 | "s",
114 | "AWS_SHARED_CREDENTIALS_FILE",
115 | "shared credentials file to use",
116 | )
117 |
118 | flag(rootCmd.PersistentFlags(),
119 | false,
120 | "verbose",
121 | "v",
122 | "AWSU_VERBOSE",
123 | "enable verbose logging",
124 | )
125 |
126 | }
127 |
--------------------------------------------------------------------------------
/command/token.go:
--------------------------------------------------------------------------------
1 | package command
2 |
3 | import (
4 | "fmt"
5 | "time"
6 |
7 | "github.com/kreuzwerker/awsu/source/yubikey"
8 | "github.com/kreuzwerker/awsu/target/mfa"
9 | "github.com/spf13/cobra"
10 | "github.com/spf13/viper"
11 | )
12 |
13 | const errTokenProfileNotFound = "no such profile or no direct MFA configured for profile %q"
14 |
15 | var tokenCmd = &cobra.Command{
16 |
17 | Use: "token",
18 | Short: "Generates one-time password from Yubikey",
19 | PreRunE: func(cmd *cobra.Command, args []string) error {
20 | return viper.Unmarshal(&conf.Register)
21 | },
22 | RunE: func(cmd *cobra.Command, args []string) error {
23 |
24 | var serial = conf.MFASerial
25 |
26 | if serial == "" {
27 |
28 | profile, ok := conf.Profiles[conf.Profile]
29 |
30 | if !ok || profile.MFASerial == "" {
31 | return fmt.Errorf(errTokenProfileNotFound, conf.Profile)
32 | }
33 |
34 | serial = profile.MFASerial
35 |
36 | }
37 |
38 | name, err := mfa.SerialToName(&serial)
39 |
40 | if err != nil {
41 | return err
42 | }
43 |
44 | token, err := yubikey.New()
45 |
46 | if err != nil {
47 | return err
48 | }
49 |
50 | otp, err := token.Generate(time.Now(), name)
51 |
52 | if err != nil {
53 | return err
54 | }
55 |
56 | fmt.Printf("%s", otp)
57 |
58 | return nil
59 |
60 | },
61 | }
62 |
63 | func init() {
64 | rootCmd.AddCommand(tokenCmd)
65 | }
66 |
--------------------------------------------------------------------------------
/command/unregister.go:
--------------------------------------------------------------------------------
1 | package command
2 |
3 | import (
4 | "github.com/kreuzwerker/awsu/source/yubikey"
5 | "github.com/kreuzwerker/awsu/strategy"
6 | "github.com/kreuzwerker/awsu/target/mfa"
7 | "github.com/spf13/cobra"
8 | )
9 |
10 | var unregisterCmd = &cobra.Command{
11 |
12 | Use: "unregister :username",
13 | Short: "Removes a device on AWS and Yubikey",
14 | Args: cobra.ExactArgs(1),
15 | RunE: func(cmd *cobra.Command, args []string) error {
16 |
17 | username := args[0]
18 |
19 | creds, err := strategy.Apply(&conf)
20 |
21 | if err != nil {
22 | return err
23 | }
24 |
25 | source, err := yubikey.New()
26 |
27 | if err != nil {
28 | return err
29 | }
30 |
31 | target, err := mfa.New(creds.NewSession(), source)
32 |
33 | if err != nil {
34 | return err
35 | }
36 |
37 | return target.Delete(username)
38 |
39 | },
40 | }
41 |
42 | func init() {
43 | rootCmd.AddCommand(unregisterCmd)
44 | }
45 |
--------------------------------------------------------------------------------
/command/version.go:
--------------------------------------------------------------------------------
1 | package command
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/spf13/cobra"
7 | )
8 |
9 | // Version describe the version of awsu
10 | type Version struct {
11 | Build, Time, Version string
12 | }
13 |
14 | // String returns a string representation of the version
15 | func (v Version) String() string {
16 | return fmt.Sprintf("%s version %s (%s, %s)", app, v.Version, v.Build, v.Time)
17 | }
18 |
19 | var versionCmd = &cobra.Command{
20 |
21 | Use: "version",
22 | Short: fmt.Sprintf("Print the version number of %s", app),
23 | RunE: func(cmd *cobra.Command, args []string) error {
24 | fmt.Println(this)
25 | return nil
26 | },
27 | }
28 |
29 | func init() {
30 | rootCmd.AddCommand(versionCmd)
31 | }
32 |
--------------------------------------------------------------------------------
/config/.awsu:
--------------------------------------------------------------------------------
1 | [profiles]
2 |
3 | default = kreuzwerker
4 | production = foo
5 | staging = bar
6 |
--------------------------------------------------------------------------------
/config/config.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "fmt"
5 | "time"
6 |
7 | "github.com/kreuzwerker/awsu/log"
8 | )
9 |
10 | const (
11 | errInvalidDuration = "invalid grace %q for duration %q"
12 | )
13 |
14 | // Config is the central configuration struct of awsu
15 | type Config struct {
16 | ConfigFile string `mapstructure:"config-file"`
17 | Console *Console `mapstructure:"-"`
18 | Duration time.Duration `mapstructure:"duration"`
19 | Generator string `mapstructure:"generator"`
20 | Grace time.Duration `mapstructure:"grace"`
21 | MFASerial string `mapstructure:"mfa-serial"`
22 | NoCache bool `mapstructure:"no-cache"`
23 | Profile string `mapstructure:"profile"`
24 | Profiles Profiles `mapstructure:"-"`
25 | Register *Register `mapstructure:"-"`
26 | SharedCredentialsFile string `mapstructure:"shared-credentials-file"`
27 | Verbose bool `mapstructure:"verbose"`
28 | }
29 |
30 | // Init will perform post config initializations and validations
31 | func (c *Config) Init() error {
32 |
33 | if c.Verbose {
34 | log.Verbose = true
35 | }
36 |
37 | profiles, err := Load(
38 | c.ConfigFile,
39 | c.SharedCredentialsFile,
40 | )
41 |
42 | if err != nil {
43 | return err
44 | }
45 |
46 | c.Profiles = profiles
47 |
48 | if c.Duration.Seconds() <= c.Grace.Seconds() {
49 | return fmt.Errorf(errInvalidDuration, c.Grace.String(), c.Duration.String())
50 | }
51 |
52 | return nil
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/config/config_test.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "testing"
5 | "time"
6 |
7 | "github.com/stretchr/testify/assert"
8 | "github.com/stretchr/testify/require"
9 | )
10 |
11 | func TestConfigInitLoad(t *testing.T) {
12 |
13 | var (
14 | assert = assert.New(t)
15 | require = require.New(t)
16 | )
17 |
18 | split := &Config{
19 | ConfigFile: "testdata/config",
20 | Duration: 5 * time.Minute,
21 | Grace: 1 * time.Minute,
22 | SharedCredentialsFile: "testdata/credentials",
23 | }
24 |
25 | merged := &Config{
26 | ConfigFile: "testdata/config-merged",
27 | Duration: 5 * time.Minute,
28 | Grace: 1 * time.Minute,
29 | SharedCredentialsFile: "testdata/merged",
30 | }
31 |
32 | for _, config := range []*Config{split, merged} {
33 |
34 | err := config.Init()
35 | require.NoError(err)
36 |
37 | source, ok := config.Profiles["default"]
38 | require.True(ok)
39 |
40 | assert.Equal("default", source.Name)
41 |
42 | assert.Equal("AKIAIOSFODNN7EXAMPLE", source.AccessKeyID)
43 | assert.Equal("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", source.SecretAccessKey)
44 | assert.Equal(source.AccessKeyID, source.Value().AccessKeyID)
45 | assert.Equal(source.SecretAccessKey, source.Value().SecretAccessKey)
46 |
47 | profile, ok := config.Profiles["foo"]
48 | require.True(ok)
49 |
50 | assert.Equal("foo", profile.Name)
51 |
52 | assert.Equal("default", profile.SourceProfile)
53 | assert.Equal("123456", profile.ExternalID)
54 | assert.Equal("arn:aws:iam::123456789012:mfa/jonsmith", profile.MFASerial)
55 | assert.Equal("arn:aws:iam::123456789012:role/marketingadmin", profile.RoleARN)
56 | assert.Equal(profile.AccessKeyID, profile.Value().AccessKeyID)
57 | assert.Equal(profile.SecretAccessKey, profile.Value().SecretAccessKey)
58 |
59 | }
60 |
61 | }
62 |
63 | func TestConfigInitValidate(t *testing.T) {
64 |
65 | var assert = assert.New(t)
66 |
67 | valid := &Config{
68 | Duration: 5 * time.Minute,
69 | Grace: 1 * time.Minute,
70 | }
71 |
72 | assert.NoError(valid.Init())
73 |
74 | invalid := &Config{
75 | Duration: 1 * time.Minute,
76 | Grace: 5 * time.Minute,
77 | }
78 |
79 | assert.Errorf(invalid.Init(), "invalid grace (f) for duration (d)")
80 |
81 | }
82 |
--------------------------------------------------------------------------------
/config/console.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | // Console is the console command configuration for awsu
4 | type Console struct {
5 | Open bool
6 | }
7 |
--------------------------------------------------------------------------------
/config/profile.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "github.com/aws/aws-sdk-go/aws/credentials"
5 | )
6 |
7 | // Profile is a long- or short-time credential profile managed in a shared config
8 | type Profile struct {
9 | AccessKeyID string `ini:"aws_access_key_id"`
10 | ExternalID string `ini:"external_id"`
11 | MFASerial string `ini:"mfa_serial"`
12 | Name string
13 | RoleARN string `ini:"role_arn"`
14 | SecretAccessKey string `ini:"aws_secret_access_key"`
15 | SourceProfile string `ini:"source_profile"`
16 | }
17 |
18 | // IsLongTerm identifies a profile that does not assume a role using a source profile
19 | func (p *Profile) IsLongTerm() bool {
20 | return p.RoleARN == ""
21 | }
22 |
23 | // Value returns the credentials associated with the profile (if any) - only long
24 | // term profiles have credentials
25 | func (p *Profile) Value() credentials.Value {
26 |
27 | return credentials.Value{
28 | AccessKeyID: p.AccessKeyID,
29 | SecretAccessKey: p.SecretAccessKey,
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/config/profiles.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "io/ioutil"
5 |
6 | "github.com/pkg/errors"
7 | ini "gopkg.in/ini.v1"
8 | )
9 |
10 | const (
11 | errFailedToOpen = "failed to open %q"
12 | )
13 |
14 | // Profiles is map of profile names to profiles
15 | type Profiles map[string]*Profile
16 |
17 | // Source resolves a short-term credential source profile
18 | func (p Profiles) Source(profile string) *Profile {
19 | return p[profile]
20 | }
21 |
22 | // Load will load profiles from multiple files, merging definitions on the way
23 | func Load(files ...string) (Profiles, error) {
24 |
25 | var (
26 | loaded []string
27 | profiles = make(map[string]*Profile)
28 | )
29 |
30 | for _, file := range files {
31 |
32 | if file == "" {
33 | continue
34 | }
35 |
36 | buf, err := ioutil.ReadFile(file)
37 |
38 | if err != nil {
39 | return nil, errors.Wrapf(err, errFailedToOpen, file)
40 | }
41 |
42 | loaded = append(loaded, file)
43 |
44 | f, err := ini.Load(buf)
45 |
46 | if err != nil {
47 | return nil, err
48 | }
49 |
50 | for _, section := range f.Sections() {
51 |
52 | name := section.Name()
53 |
54 | if name == "preview" {
55 | continue
56 | }
57 |
58 | init:
59 |
60 | profile, ok := profiles[name]
61 |
62 | if !ok {
63 | profiles[name] = new(Profile)
64 | goto init
65 | }
66 |
67 | if err := section.MapTo(profile); err != nil {
68 | return nil, err
69 | }
70 |
71 | profile.Name = name
72 |
73 | }
74 |
75 | }
76 |
77 | return profiles, nil
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/config/register.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | // Register is the register command configuration for awsu
4 | type Register struct {
5 | Issuer string
6 | QR bool
7 | }
8 |
--------------------------------------------------------------------------------
/config/testdata/config:
--------------------------------------------------------------------------------
1 | [default]
2 | region=us-west-2
3 | output=json
4 |
--------------------------------------------------------------------------------
/config/testdata/config-merged:
--------------------------------------------------------------------------------
1 | merged
--------------------------------------------------------------------------------
/config/testdata/credentials:
--------------------------------------------------------------------------------
1 | [default]
2 | aws_access_key_id=AKIAIOSFODNN7EXAMPLE
3 | aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
4 |
5 | [foo]
6 | role_arn=arn:aws:iam::123456789012:role/marketingadmin
7 | source_profile=default
8 | external_id=123456
9 | mfa_serial=arn:aws:iam::123456789012:mfa/jonsmith
10 |
--------------------------------------------------------------------------------
/config/testdata/merged:
--------------------------------------------------------------------------------
1 | [default]
2 | region=us-west-2
3 | output=json
4 |
5 | aws_access_key_id=AKIAIOSFODNN7EXAMPLE
6 | aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
7 |
8 | [foo]
9 | role_arn=arn:aws:iam::123456789012:role/marketingadmin
10 | source_profile=default
11 | external_id=123456
12 | mfa_serial=arn:aws:iam::123456789012:mfa/jonsmith
13 |
--------------------------------------------------------------------------------
/console/console.go:
--------------------------------------------------------------------------------
1 | package console
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "fmt"
7 | "io"
8 | "net/http"
9 | "net/url"
10 | "strings"
11 |
12 | "github.com/aws/aws-sdk-go/aws/arn"
13 | "github.com/aws/aws-sdk-go/service/sts"
14 | "github.com/kreuzwerker/awsu/config"
15 | "github.com/kreuzwerker/awsu/strategy"
16 | "github.com/pkg/errors"
17 | )
18 |
19 | // Console is a helper for opening links to the AWS console
20 | type Console struct {
21 | conf *config.Config
22 | profile *config.Profile
23 | }
24 |
25 | const (
26 | errCallerIdentity = "failed to determine caller identity"
27 | errFederationMarshal = "failed to marshal federation session"
28 | errFederationRequest = "failed to request federation"
29 | errFederationResponse = "failed to receive federation response body"
30 | errFederationUnmarshal = "failed to unmarshal sign-in token"
31 | errNoSuchProfile = "no such profile %q configured"
32 | )
33 |
34 | // New instantiates a new console helper
35 | func New(conf *config.Config) (*Console, error) {
36 |
37 | profile, ok := conf.Profiles[conf.Profile]
38 |
39 | if !ok {
40 | return nil, fmt.Errorf(errNoSuchProfile, conf.Profile)
41 | }
42 |
43 | return &Console{
44 | conf: conf,
45 | profile: profile,
46 | }, nil
47 |
48 | }
49 |
50 | // Link returns a link to the AWS console
51 | func (c *Console) Link() (string, error) {
52 |
53 | var f func() (string, error)
54 |
55 | if c.profile.IsLongTerm() {
56 | f = c.longterm
57 | } else if c.profile.ExternalID != "" {
58 | f = c.external
59 | } else {
60 | f = c.internal
61 | }
62 |
63 | return f()
64 |
65 | }
66 |
67 | // external returns a console link to an external / federated session
68 | func (c *Console) external() (string, error) {
69 |
70 | creds, err := strategy.Apply(c.conf)
71 |
72 | if err != nil {
73 | return "", err
74 | }
75 |
76 | fep := map[string]string{
77 | "sessionId": creds.AccessKeyID,
78 | "sessionKey": creds.SessionToken,
79 | "sessionToken": creds.SessionToken,
80 | }
81 |
82 | enc, err := json.Marshal(fep)
83 |
84 | if err != nil {
85 | return "", errors.Wrapf(err, errFederationMarshal)
86 | }
87 |
88 | url := fmt.Sprintf("https://signin.aws.amazon.com/federation?Action=getSigninToken&Session=%s", string(url.QueryEscape(string(enc))))
89 |
90 | var buf = bytes.NewBuffer(nil)
91 |
92 | res, err := http.Get(url)
93 |
94 | if err != nil {
95 | return "", errors.Wrapf(err, errFederationRequest)
96 | }
97 |
98 | defer res.Body.Close()
99 |
100 | if _, err := io.Copy(buf, res.Body); err != nil {
101 | return "", errors.Wrapf(err, errFederationResponse)
102 | }
103 |
104 | var body map[string]string
105 |
106 | if err := json.Unmarshal(buf.Bytes(), &body); err != nil {
107 | return "", errors.Wrapf(err, errFederationUnmarshal)
108 | }
109 |
110 | var (
111 | destination = "https://console.aws.amazon.com/"
112 | issuer = ""
113 | token = body["SigninToken"]
114 | )
115 |
116 | url = fmt.Sprintf("https://signin.aws.amazon.com/federation?Action=login&Issuer=%s&Destination=%s&SigninToken=%s\n",
117 | issuer,
118 | destination,
119 | token)
120 |
121 | return url, nil
122 |
123 | }
124 |
125 | // internal returns a console link to an internal / cross account session
126 | func (c *Console) internal() (string, error) {
127 |
128 | a, err := arn.Parse(c.profile.RoleARN)
129 |
130 | if err != nil {
131 | return "", err
132 | }
133 |
134 | url := fmt.Sprintf("https://signin.aws.amazon.com/switchrole?account=%s&roleName=%s&displayName=%s",
135 | a.AccountID,
136 | strings.TrimPrefix(a.Resource, "role/"),
137 | c.profile.Name)
138 |
139 | return url, nil
140 |
141 | }
142 |
143 | // longterm returns a console link for an IAM user
144 | func (c *Console) longterm() (string, error) {
145 |
146 | creds, err := strategy.Apply(c.conf)
147 |
148 | if err != nil {
149 | return "", err
150 | }
151 |
152 | client := sts.New(creds.NewSession())
153 |
154 | res, err := client.GetCallerIdentity(&sts.GetCallerIdentityInput{})
155 |
156 | if err != nil {
157 | return "", errors.Wrapf(err, errCallerIdentity)
158 | }
159 |
160 | // TODO: make this configurable
161 | region := "eu-west-1"
162 |
163 | // 015428540659 is the magic account ID for AWS sign-in
164 | url := fmt.Sprintf("https://signin.aws.amazon.com/oauth?redirect_uri=https://%s.console.aws.amazon.com/console/home?region=%s&client_id=arn:aws:iam::015428540659:user/homepage&response_type=code&iam_user=true&account=%s",
165 | region,
166 | region,
167 | *res.Account,
168 | )
169 |
170 | return url, nil
171 |
172 | }
173 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/kreuzwerker/awsu
2 |
3 | require (
4 | github.com/aws/aws-sdk-go v1.34.0
5 | github.com/dustin/go-humanize v0.0.0-20180713052910-9f541cc9db5d
6 | github.com/mdp/qrterminal v1.0.0
7 | github.com/mitchellh/go-homedir v1.0.0
8 | github.com/pkg/errors v0.9.1
9 | github.com/skratchdot/open-golang v0.0.0-20160302144031-75fb7ed4208c
10 | github.com/spf13/cobra v0.0.3
11 | github.com/spf13/pflag v1.0.2
12 | github.com/spf13/viper v1.2.0
13 | github.com/stretchr/testify v1.5.1
14 | github.com/yawn/doubledash v0.0.0-20151212175516-fd8a81db93af
15 | github.com/yawn/envmap v0.0.0-20160813152305-a78254303070
16 | github.com/yawn/ykoath v1.0.3
17 | gopkg.in/ini.v1 v1.38.2
18 | )
19 |
20 | require (
21 | github.com/BurntSushi/toml v0.4.1 // indirect
22 | github.com/davecgh/go-spew v1.1.1 // indirect
23 | github.com/ebfe/scard v0.0.0-20190212122703-c3d1b1916a95 // indirect
24 | github.com/fsnotify/fsnotify v1.4.7 // indirect
25 | github.com/hashicorp/hcl v1.0.0 // indirect
26 | github.com/inconshreveable/mousetrap v1.0.0 // indirect
27 | github.com/jmespath/go-jmespath v0.3.0 // indirect
28 | github.com/magiconair/properties v1.8.0 // indirect
29 | github.com/mitchellh/mapstructure v1.0.0 // indirect
30 | github.com/pelletier/go-toml v1.2.0 // indirect
31 | github.com/pmezard/go-difflib v1.0.0 // indirect
32 | github.com/rsc/qr v0.1.0 // indirect
33 | github.com/smartystreets/goconvey v1.6.4 // indirect
34 | github.com/spf13/afero v1.1.2 // indirect
35 | github.com/spf13/cast v1.2.0 // indirect
36 | github.com/spf13/jwalterweatherman v1.0.0 // indirect
37 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect
38 | golang.org/x/text v0.3.8 // indirect
39 | gopkg.in/yaml.v2 v2.2.2 // indirect
40 | rsc.io/qr v0.2.0 // indirect
41 | )
42 |
43 | go 1.19
44 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/BurntSushi/toml v0.4.1 h1:GaI7EiDXDRfa8VshkTj7Fym7ha+y8/XxIgD2okUIjLw=
2 | github.com/BurntSushi/toml v0.4.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
3 | github.com/aws/aws-sdk-go v1.34.0 h1:brux2dRrlwCF5JhTL7MUT3WUwo9zfDHZZp3+g3Mvlmo=
4 | github.com/aws/aws-sdk-go v1.34.0/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0=
5 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
6 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
7 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
8 | github.com/dustin/go-humanize v0.0.0-20180713052910-9f541cc9db5d h1:lDrio3iIdNb0Gw9CgH7cQF+iuB5mOOjdJ9ERNJCBgb4=
9 | github.com/dustin/go-humanize v0.0.0-20180713052910-9f541cc9db5d/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
10 | github.com/ebfe/scard v0.0.0-20190212122703-c3d1b1916a95 h1:OM0MnUcXBysj7ZtXvThVWHMoahuKQ8FuwIdeSLcNdP4=
11 | github.com/ebfe/scard v0.0.0-20190212122703-c3d1b1916a95/go.mod h1:8hHvF8DlEq5kE3KWOsZQezdWq1OTOVxZArZMscS954E=
12 | github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
13 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
14 | github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
15 | github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
16 | github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
17 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
18 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
19 | github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
20 | github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
21 | github.com/jmespath/go-jmespath v0.3.0 h1:OS12ieG61fsCg5+qLJ+SsW9NicxNkg3b25OyT2yCeUc=
22 | github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik=
23 | github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
24 | github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
25 | github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY=
26 | github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
27 | github.com/mdp/qrterminal v1.0.0 h1:Lir5hH+jRgOiyqdXIcQ2CHm7g8MQGd/SlpvxXpaoH00=
28 | github.com/mdp/qrterminal v1.0.0/go.mod h1:JHFxKzeFy8lXGu3bkkAZ4EwpmxWtm2laIs1MVvWoBt0=
29 | github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0=
30 | github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
31 | github.com/mitchellh/mapstructure v1.0.0 h1:vVpGvMXJPqSDh2VYHF7gsfQj8Ncx+Xw5Y1KHeTRY+7I=
32 | github.com/mitchellh/mapstructure v1.0.0/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
33 | github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
34 | github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
35 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
36 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
37 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
38 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
39 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
40 | github.com/rsc/qr v0.1.0 h1:WW8q4ZVCqHJvjgK1VrO0Guecromo+4lOKo4cYcGBB2A=
41 | github.com/rsc/qr v0.1.0/go.mod h1:pPTpZ297SDwxHkeVbI8UtK0t44AY2UwaRx/q7CiJXhw=
42 | github.com/skratchdot/open-golang v0.0.0-20160302144031-75fb7ed4208c h1:fyKiXKO1/I/B6Y2U8T7WdQGWzwehOuGIrljPtt7YTTI=
43 | github.com/skratchdot/open-golang v0.0.0-20160302144031-75fb7ed4208c/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog=
44 | github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
45 | github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
46 | github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
47 | github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
48 | github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
49 | github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
50 | github.com/spf13/cast v1.2.0 h1:HHl1DSRbEQN2i8tJmtS6ViPyHx35+p51amrdsiTCrkg=
51 | github.com/spf13/cast v1.2.0/go.mod h1:r2rcYCSwa1IExKTDiTfzaxqT2FNHs8hODu4LnUfgKEg=
52 | github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8=
53 | github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
54 | github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
55 | github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
56 | github.com/spf13/pflag v1.0.2 h1:Fy0orTDgHdbnzHcsOgfCN4LtHf0ec3wwtiwJqwvf3Gc=
57 | github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
58 | github.com/spf13/viper v1.2.0 h1:M4Rzxlu+RgU4pyBRKhKaVN1VeYOm8h2jgyXnAseDgCc=
59 | github.com/spf13/viper v1.2.0/go.mod h1:P4AexN0a+C9tGAnUFNwDMYYZv3pjFuvmeiMyKRaNVlI=
60 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
61 | github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A=
62 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
63 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
64 | github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
65 | github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
66 | github.com/yawn/doubledash v0.0.0-20151212175516-fd8a81db93af h1:eV7i4++vdsO+jWDa/0Us8EE4GZW5XFpYMuUAICYNBps=
67 | github.com/yawn/doubledash v0.0.0-20151212175516-fd8a81db93af/go.mod h1:dvhlbINDXiDEf/Cwinko7RWc1cTpvkn5eR9HhaAEyNQ=
68 | github.com/yawn/envmap v0.0.0-20160813152305-a78254303070 h1:kzDDpNOIQ/Ob/vdTWAmJ6k3NKDvJEy/CGdR6rSF2Emg=
69 | github.com/yawn/envmap v0.0.0-20160813152305-a78254303070/go.mod h1:n36oviu0t81CF3cW9sdxQzKQ10R9FaiQVmCT9Puslt8=
70 | github.com/yawn/ykoath v1.0.3 h1:6ItWA3pH9OmLmWAvu3iTWiWtgJ68mM7m6yIXTSr0/78=
71 | github.com/yawn/ykoath v1.0.3/go.mod h1:dcXMmLrvt6WFkySkG2k8ZEqxiTbu/TWSI4+/Cb54+Lg=
72 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
73 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
74 | golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
75 | golang.org/x/sys v0.0.0-20180906133057-8cf3aee42992/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
76 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
77 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s=
78 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
79 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
80 | golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
81 | golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
82 | golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
83 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
84 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
85 | gopkg.in/ini.v1 v1.38.2 h1:dGcbywv4RufeGeiMycPT/plKB5FtmLKLnWKwBiLhUA4=
86 | gopkg.in/ini.v1 v1.38.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
87 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
88 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
89 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
90 | rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY=
91 | rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs=
92 |
--------------------------------------------------------------------------------
/log/log.go:
--------------------------------------------------------------------------------
1 | package log
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "os"
7 | )
8 |
9 | // Verbose enabled debug logging
10 | var Verbose = false
11 |
12 | var logger = log.New(os.Stderr, "", log.LstdFlags)
13 |
14 | // Debug produces log messages if the Verbose flag is set to true
15 | func Debug(msg string, args ...interface{}) {
16 |
17 | if Verbose {
18 | logger.Printf("[DEBUG] %s", fmt.Sprintf(msg, args...))
19 | }
20 |
21 | }
22 |
23 | // Info produces log messages regardless of Verbose
24 | func Info(msg string, args ...interface{}) {
25 | logger.Printf(msg, args...)
26 | }
27 |
--------------------------------------------------------------------------------
/log/log_test.go:
--------------------------------------------------------------------------------
1 | package log
2 |
3 | import (
4 | "bytes"
5 | "os"
6 | "testing"
7 |
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestDebug(t *testing.T) {
12 |
13 | assert := assert.New(t)
14 |
15 | buf := bytes.NewBuffer(nil)
16 | logger.SetOutput(buf)
17 |
18 | defer func() {
19 | logger.SetOutput(os.Stderr)
20 | Verbose = false
21 | }()
22 |
23 | Debug("hello")
24 |
25 | assert.Empty(buf.String())
26 |
27 | Verbose = true
28 |
29 | Debug("goodbye")
30 |
31 | assert.Regexp(`\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2} \[DEBUG\] goodbye\n`, buf.String())
32 |
33 | }
34 |
35 | func TestInfo(t *testing.T) {
36 |
37 | assert := assert.New(t)
38 |
39 | buf := bytes.NewBuffer(nil)
40 | logger.SetOutput(buf)
41 |
42 | defer func() {
43 | logger.SetOutput(os.Stderr)
44 | Verbose = false
45 | }()
46 |
47 | Info("hello")
48 |
49 | assert.Regexp(`\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2} hello\n`, buf.String())
50 | buf.Reset()
51 |
52 | Verbose = true
53 |
54 | Info("goodbye")
55 |
56 | assert.Regexp(`\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2} goodbye\n`, buf.String())
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/source/manual/manual.go:
--------------------------------------------------------------------------------
1 | package manual
2 |
3 | import (
4 | "bufio"
5 | "fmt"
6 | "io"
7 | "os"
8 | "time"
9 | )
10 |
11 | // Manual is a generator that is based on manual input
12 | type Manual struct {
13 | reader io.Reader
14 | }
15 |
16 | // New initializes a new manual generator
17 | func New() *Manual {
18 |
19 | return &Manual{
20 | reader: os.Stdin,
21 | }
22 |
23 | }
24 |
25 | // Generate generates a new OTP by asking for it on the commandline
26 | func (m *Manual) Generate(clock time.Time, name string) (string, error) {
27 |
28 | fmt.Printf("enter TOTP token for %q: ", name)
29 |
30 | scanner := bufio.NewScanner(m.reader)
31 | scanner.Scan()
32 |
33 | return scanner.Text(), nil
34 |
35 | }
36 |
37 | // Name returns the name of this generator
38 | func (m *Manual) Name() string {
39 | return "manual"
40 | }
41 |
--------------------------------------------------------------------------------
/source/source.go:
--------------------------------------------------------------------------------
1 | package source
2 |
3 | import "time"
4 |
5 | // Generator is the interface defined by read-only sources of OTPs
6 | type Generator interface {
7 |
8 | // Generate generates a named one-time password using the given reference time
9 | Generate(clock time.Time, name string) (string, error)
10 |
11 | // Name returns the name of this generator
12 | Name() string
13 | }
14 |
15 | // Source is the interface defined by r/w sources of OTPS
16 | type Source interface {
17 | Generator
18 |
19 | // Add adds a new named TOTP secret
20 | Add(name string, secret []byte) error
21 |
22 | // Delete removes a named TOTP secret
23 | Delete(name string) error
24 | }
25 |
--------------------------------------------------------------------------------
/source/yubikey/yubikey.go:
--------------------------------------------------------------------------------
1 | package yubikey
2 |
3 | import (
4 | "sync"
5 | "time"
6 |
7 | "github.com/pkg/errors"
8 | "github.com/yawn/ykoath"
9 | )
10 |
11 | // Yubikey is a source based on a Yubikey
12 | type Yubikey struct {
13 | client *ykoath.OATH
14 | sync.Mutex
15 | }
16 |
17 | const (
18 | errInitializeSmartcard = "failed to initialize Yubikey"
19 | errSelectOathApplication = "failed to select OATH application in Yubikey"
20 | )
21 |
22 | // New initializes a new Yubikey source
23 | func New() (*Yubikey, error) {
24 |
25 | oath, err := ykoath.New()
26 |
27 | if err != nil {
28 | return nil, errors.Wrapf(err, errInitializeSmartcard)
29 | }
30 |
31 | _, err = oath.Select()
32 |
33 | if err != nil {
34 | return nil, errors.Wrapf(err, errSelectOathApplication)
35 | }
36 |
37 | return &Yubikey{
38 | client: oath,
39 | }, nil
40 |
41 | }
42 |
43 | // Add adds / overwrites a credential to a Yubikey
44 | func (y *Yubikey) Add(name string, secret []byte) error {
45 | return y.client.Put(name, ykoath.HmacSha1, ykoath.Totp, 6, secret, false)
46 | }
47 |
48 | // Delete deletes a credential from a Yubikey
49 | func (y *Yubikey) Delete(name string) error {
50 | return y.client.Delete(name)
51 | }
52 |
53 | // Generate generates a new OTP with a Yubikey
54 | func (y *Yubikey) Generate(clock time.Time, name string) (string, error) {
55 |
56 | y.Lock()
57 | defer y.Unlock()
58 |
59 | defer func(prev func() time.Time) {
60 | y.client.Clock = prev
61 | }(y.client.Clock)
62 |
63 | y.client.Clock = func() time.Time {
64 | return clock
65 | }
66 |
67 | return y.client.Calculate(name, nil)
68 |
69 | }
70 |
71 | // Name returns the name of this source
72 | func (y *Yubikey) Name() string {
73 | return "yubikey (ykoath)"
74 | }
75 |
--------------------------------------------------------------------------------
/strategy/assume_role.go:
--------------------------------------------------------------------------------
1 | package strategy
2 |
3 | import (
4 | "crypto/rand"
5 | "fmt"
6 | "io"
7 | "time"
8 |
9 | "github.com/aws/aws-sdk-go/aws"
10 | "github.com/aws/aws-sdk-go/aws/session"
11 | "github.com/aws/aws-sdk-go/service/sts"
12 | "github.com/kreuzwerker/awsu/config"
13 | "github.com/kreuzwerker/awsu/log"
14 | "github.com/kreuzwerker/awsu/strategy/credentials"
15 | "github.com/pkg/errors"
16 | )
17 |
18 | const (
19 | errAssumeRoleFailed = "failed to assume role %q"
20 | logAssumingRole = "assuming role %q using profile %s (sid %s)"
21 | )
22 |
23 | // AssumeRole is a strategy that assumes IAM roles
24 | type AssumeRole struct {
25 | Duration time.Duration
26 | Grace time.Duration
27 | Profiles []*config.Profile
28 | }
29 |
30 | // Credentials aquires actual credentials
31 | func (a *AssumeRole) Credentials(sess *session.Session) (*credentials.Credentials, error) {
32 |
33 | var (
34 | client = sts.New(sess)
35 | profile = a.Profile()
36 | sid = a.sessionName()
37 | )
38 |
39 | log.Debug(logAssumingRole, profile.RoleARN, profile.Name, sid)
40 |
41 | req := &sts.AssumeRoleInput{
42 | DurationSeconds: aws.Int64(int64(a.Duration.Seconds())),
43 | RoleArn: &profile.RoleARN,
44 | RoleSessionName: &sid,
45 | }
46 |
47 | if profile.ExternalID != "" {
48 | req.ExternalId = &profile.ExternalID
49 | }
50 |
51 | res, err := client.AssumeRole(req)
52 |
53 | if err != nil {
54 | return nil, errors.Wrapf(err, errAssumeRoleFailed, profile.RoleARN)
55 | }
56 |
57 | creds := credentials.NewShortTerm(
58 | profile.Name,
59 | *res.Credentials.AccessKeyId,
60 | *res.Credentials.SecretAccessKey,
61 | *res.Credentials.SessionToken,
62 | time.Now().Add(a.Duration).Add(a.Grace*-1),
63 | )
64 |
65 | return creds, nil
66 |
67 | }
68 |
69 | // IsCacheable indicates the output of this strategy can be cached (always true)
70 | func (a *AssumeRole) IsCacheable() bool {
71 | return true
72 | }
73 |
74 | // Name returns the name of this strategy
75 | func (a *AssumeRole) Name() string {
76 | return "assume_role"
77 | }
78 |
79 | // Profile returns the name of the profile used (if applicable, otherwise nil)
80 | func (a *AssumeRole) Profile() *config.Profile {
81 |
82 | for _, profile := range a.Profiles {
83 |
84 | if profile != nil && !profile.IsLongTerm() {
85 | return profile
86 | }
87 |
88 | }
89 |
90 | return nil
91 |
92 | }
93 |
94 | // sessionName returns the name give to the assumed role sessions
95 | func (a *AssumeRole) sessionName() string {
96 |
97 | var rid [16]byte
98 |
99 | io.ReadFull(rand.Reader, rid[:])
100 |
101 | // TODO: maybe add escaped profile name
102 | return fmt.Sprintf("awsu-%x", rid[:])
103 |
104 | }
105 |
--------------------------------------------------------------------------------
/strategy/credentials/credentials.go:
--------------------------------------------------------------------------------
1 | package credentials
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io/ioutil"
7 | "os"
8 | "os/exec"
9 | "path/filepath"
10 | "strings"
11 | "syscall"
12 | "time"
13 |
14 | "github.com/aws/aws-sdk-go/aws"
15 | "github.com/aws/aws-sdk-go/aws/credentials"
16 | "github.com/aws/aws-sdk-go/aws/session"
17 | "github.com/kreuzwerker/awsu/log"
18 | homedir "github.com/mitchellh/go-homedir"
19 | "github.com/yawn/envmap"
20 | )
21 |
22 | const (
23 | errInvalidCredentials = "cached credentials are invalid"
24 | logExec = "running %q with args %q"
25 | logLoadingCredentials = "loading cached credentials from %q"
26 | logSavingCredentials = "saving cached credentials to %q"
27 | )
28 |
29 | // Credentials encapsulates cacheable credentials that can convert to actual
30 | // session and can be used to aquire further credential
31 | type Credentials struct {
32 | credentials.Value
33 | Expires time.Time
34 | Profile string
35 | }
36 |
37 | // NewLongTerm is a constructor for long term credentials
38 | func NewLongTerm(profile, accessKeyID, secretAccessKey string) *Credentials {
39 |
40 | return &Credentials{
41 | Value: credentials.Value{
42 | AccessKeyID: accessKeyID,
43 | SecretAccessKey: secretAccessKey,
44 | },
45 | Profile: profile,
46 | }
47 |
48 | }
49 |
50 | // NewShortTerm is a constructor for short term credentials with expiry
51 | func NewShortTerm(profile, accessKeyID, secretAccessKey, sessionToken string, expires time.Time) *Credentials {
52 |
53 | return &Credentials{
54 | Value: credentials.Value{
55 | AccessKeyID: accessKeyID,
56 | SecretAccessKey: secretAccessKey,
57 | SessionToken: sessionToken,
58 | },
59 | Expires: expires,
60 | Profile: profile,
61 | }
62 |
63 | }
64 |
65 | // Load loads cached credentials
66 | func Load(profile string) (*Credentials, error) {
67 |
68 | path, err := cachePath(profile)
69 |
70 | if err != nil {
71 | return nil, err
72 | }
73 |
74 | log.Debug(logLoadingCredentials, path)
75 |
76 | raw, err := ioutil.ReadFile(path)
77 |
78 | if err != nil {
79 | return nil, err
80 | }
81 |
82 | var creds *Credentials
83 |
84 | if err := json.Unmarshal(raw, &creds); err != nil {
85 | return nil, err
86 | }
87 |
88 | if !creds.IsValid() {
89 | return nil, fmt.Errorf(errInvalidCredentials)
90 | }
91 |
92 | return creds, nil
93 |
94 | }
95 |
96 | // Exec sets an appropriate runtime environment and execs the passed in app
97 | func (c *Credentials) Exec(app string, args []string) error {
98 |
99 | env := envmap.Import()
100 |
101 | if c.Expires.Second() > 0 {
102 | env["AWSU_EXPIRES"] = c.Expires.Format(time.RFC3339)
103 | }
104 |
105 | env["AWSU_PROFILE"] = c.Profile
106 | env["AWS_ACCESS_KEY_ID"] = c.Value.AccessKeyID
107 | env["AWS_SECRET_ACCESS_KEY"] = c.Value.SecretAccessKey
108 | env["AWS_SESSION_TOKEN"] = c.Value.SessionToken
109 |
110 | cmd, err := exec.LookPath(app)
111 |
112 | if err != nil {
113 | return err
114 | }
115 |
116 | log.Debug(logExec, cmd, args)
117 |
118 | return syscall.Exec(cmd, args, env.ToEnv())
119 |
120 | }
121 |
122 | // IsValid indicates if a loaded credential is (still) valid
123 | func (c *Credentials) IsValid() bool {
124 | return time.Now().Before(c.Expires)
125 | }
126 |
127 | // NewSession creates a new session with these credentials
128 | func (c *Credentials) NewSession() *session.Session {
129 | return c.UpdateSession(session.New(&aws.Config{}))
130 | }
131 |
132 | // Save saves (caches) credentials
133 | func (c *Credentials) Save() error {
134 |
135 | path, err := cachePath(c.Profile)
136 |
137 | if err != nil {
138 | return err
139 | }
140 |
141 | log.Debug(logSavingCredentials, path)
142 |
143 | out, err := json.Marshal(c)
144 |
145 | if err != nil {
146 | return err
147 | }
148 |
149 | return ioutil.WriteFile(path, out, 0600)
150 |
151 | }
152 |
153 | // String returns a string representation of these credentials, suitable for eval()
154 | func (c *Credentials) String() string {
155 |
156 | parts := []string{
157 | fmt.Sprintf("export AWSU_EXPIRES=%s", c.Expires.Format(time.RFC3339)),
158 | fmt.Sprintf("export AWS_ACCESS_KEY_ID=%s", c.AccessKeyID),
159 | fmt.Sprintf("export AWS_SECRET_ACCESS_KEY=%s", c.SecretAccessKey),
160 | }
161 |
162 | if c.SessionToken != "" {
163 | parts = append(parts, fmt.Sprintf("export AWS_SESSION_TOKEN=%s", c.SessionToken))
164 | }
165 |
166 | return strings.Join(parts, "\n")
167 |
168 | }
169 |
170 | // UpdateSession updates a given session with this credentials
171 | func (c *Credentials) UpdateSession(sess *session.Session) *session.Session {
172 |
173 | sess.Config.Credentials = credentials.NewStaticCredentials(
174 | c.AccessKeyID,
175 | c.SecretAccessKey,
176 | c.SessionToken,
177 | )
178 |
179 | return sess
180 |
181 | }
182 |
183 | // cachePath determines the cache path for the given credentials
184 | func cachePath(profile string) (string, error) {
185 |
186 | home, err := homedir.Dir()
187 |
188 | if err != nil {
189 | return "", err
190 | }
191 |
192 | dir := filepath.Join(home, ".awsu", "sessions")
193 |
194 | if err := os.MkdirAll(dir, 0700); err != nil {
195 | return "", err
196 | }
197 |
198 | return filepath.Join(dir, fmt.Sprintf("%s.json", profile)), nil
199 |
200 | }
201 |
--------------------------------------------------------------------------------
/strategy/long_term.go:
--------------------------------------------------------------------------------
1 | package strategy
2 |
3 | import (
4 | "github.com/aws/aws-sdk-go/aws/session"
5 | "github.com/kreuzwerker/awsu/config"
6 | "github.com/kreuzwerker/awsu/strategy/credentials"
7 | )
8 |
9 | // LongTerm is a strategy that uses long-term credentials (IAM user keypairs)
10 | type LongTerm struct {
11 | Profiles []*config.Profile
12 | }
13 |
14 | // Credentials aquires actual credentials
15 | func (l *LongTerm) Credentials(sess *session.Session) (*credentials.Credentials, error) {
16 |
17 | p := l.Profile()
18 |
19 | return credentials.NewLongTerm(p.Name,
20 | p.AccessKeyID,
21 | p.SecretAccessKey),
22 | nil
23 |
24 | }
25 |
26 | // IsCacheable indicates the output of this strategy can be cached (always false)
27 | func (l *LongTerm) IsCacheable() bool {
28 | return false
29 | }
30 |
31 | // Name returns the name of this strategy
32 | func (l *LongTerm) Name() string {
33 | return "long_term"
34 | }
35 |
36 | // Profile returns the name of the profile used (if applicable, otherwise nil)
37 | func (l *LongTerm) Profile() *config.Profile {
38 |
39 | for _, profile := range l.Profiles {
40 |
41 | if profile != nil && profile.IsLongTerm() {
42 | return profile
43 | }
44 |
45 | }
46 |
47 | return nil
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/strategy/session_token.go:
--------------------------------------------------------------------------------
1 | package strategy
2 |
3 | import (
4 | "fmt"
5 | "time"
6 |
7 | "github.com/aws/aws-sdk-go/aws"
8 | "github.com/aws/aws-sdk-go/aws/session"
9 | "github.com/aws/aws-sdk-go/service/sts"
10 | "github.com/kreuzwerker/awsu/config"
11 | "github.com/kreuzwerker/awsu/log"
12 | "github.com/kreuzwerker/awsu/source"
13 | "github.com/kreuzwerker/awsu/source/manual"
14 | "github.com/kreuzwerker/awsu/source/yubikey"
15 | "github.com/kreuzwerker/awsu/strategy/credentials"
16 | "github.com/kreuzwerker/awsu/target/mfa"
17 | )
18 |
19 | const (
20 | // GenManual is the "manual" (type-OTP-in) generator
21 | GenManual = "manual"
22 |
23 | // GenYubikey is the native Yubikey generator
24 | GenYubikey = "yubikey"
25 | )
26 |
27 | const (
28 | errSessionTokenOnUnsuitableProfiles = "failed to get session token on unsuitable profiles: at least one long-term keypair must be configured"
29 | errSessionTokenWithoutMFA = "failed to get session token on unsuitable profiles: at least one MFA must be configured"
30 | errUnknownGenerator = "unknown generator %q"
31 | logGettingSessionToken = "getting session token for profile %q and serial %q"
32 | logSerialExplicit = "using explicitly supplied MFA serial %q"
33 | logSerialFromProfile = "using %q profile for MFA serial"
34 | )
35 |
36 | // SessionToken is a strategy that gets session tokens using long-term credentials
37 | type SessionToken struct {
38 | Duration time.Duration
39 | Generator string
40 | Grace time.Duration
41 | MFASerial string
42 | Profiles []*config.Profile
43 | _serial string
44 | }
45 |
46 | // Credentials aquires actual credentials
47 | func (s *SessionToken) Credentials(sess *session.Session) (*credentials.Credentials, error) {
48 |
49 | var (
50 | client = sts.New(sess)
51 | lt = s.Profile()
52 | serial = s.serial()
53 | )
54 |
55 | log.Debug(logGettingSessionToken, lt.Name, serial)
56 |
57 | token, err := s.generate(&serial)
58 |
59 | if err != nil {
60 | return nil, err
61 | }
62 |
63 | res, err := client.GetSessionToken(&sts.GetSessionTokenInput{
64 | DurationSeconds: aws.Int64(int64(s.Duration.Seconds())),
65 | SerialNumber: &serial,
66 | TokenCode: &token,
67 | })
68 |
69 | if err != nil {
70 | return nil, err
71 | }
72 |
73 | creds := credentials.NewShortTerm(
74 | lt.Name,
75 | *res.Credentials.AccessKeyId,
76 | *res.Credentials.SecretAccessKey,
77 | *res.Credentials.SessionToken,
78 | time.Now().Add(s.Duration).Add(s.Grace*-1),
79 | )
80 |
81 | return creds, nil
82 |
83 | }
84 |
85 | // IsCacheable indicates the output of this strategy can be cached (always true)
86 | func (s *SessionToken) IsCacheable() bool {
87 | return true
88 | }
89 |
90 | // Name returns the name of this strategy
91 | func (s *SessionToken) Name() string {
92 | return "session_token"
93 | }
94 |
95 | // Profile returns the name of the profile used (if applicable, otherwise nil)
96 | func (s *SessionToken) Profile() *config.Profile {
97 |
98 | for _, profile := range s.Profiles {
99 |
100 | if profile != nil && profile.IsLongTerm() && s.serial() != "" {
101 | return profile
102 | }
103 |
104 | }
105 |
106 | return nil
107 |
108 | }
109 |
110 | func (s *SessionToken) generate(serial *string) (string, error) {
111 |
112 | var g source.Generator
113 |
114 | switch s.Generator {
115 | case GenYubikey:
116 |
117 | gen, err := yubikey.New()
118 |
119 | if err != nil {
120 | return "", err
121 | }
122 |
123 | g = gen
124 |
125 | case GenManual:
126 | g = manual.New()
127 |
128 | default:
129 | return "", fmt.Errorf(errUnknownGenerator, s.Generator)
130 | }
131 |
132 | name, err := mfa.SerialToName(serial)
133 |
134 | if err != nil {
135 | return "", err
136 | }
137 |
138 | return g.Generate(time.Now(), name)
139 |
140 | }
141 |
142 | func (s *SessionToken) serial() string {
143 |
144 | if s._serial != "" {
145 | return s._serial
146 | }
147 |
148 | if s._serial = s.MFASerial; s._serial != "" {
149 | log.Debug(logSerialExplicit, s._serial)
150 | return s._serial
151 | }
152 |
153 | // find the MFA
154 | for _, profile := range s.Profiles {
155 |
156 | if profile != nil && profile.MFASerial != "" {
157 | s._serial = profile.MFASerial
158 | log.Debug(logSerialFromProfile, profile.Name)
159 | return s._serial
160 | }
161 |
162 | }
163 |
164 | // TODO: try autodetection as a last resort OR just don't get a session token?
165 |
166 | return s._serial
167 |
168 | }
169 |
--------------------------------------------------------------------------------
/strategy/strategy.go:
--------------------------------------------------------------------------------
1 | package strategy
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/aws/aws-sdk-go/aws/session"
7 | human "github.com/dustin/go-humanize"
8 | "github.com/kreuzwerker/awsu/config"
9 | "github.com/kreuzwerker/awsu/log"
10 | "github.com/kreuzwerker/awsu/strategy/credentials"
11 | )
12 |
13 | const (
14 | errProfileAquisitionFailed = "failed to acquire credentials for profile %q: %s"
15 | errProfileCacheLoadExpired = "ignoring expired cached profile %q"
16 | errProfileCacheLoadFailed = "failed to load cached profile %q: %s"
17 | errProfileCacheSaveFailed = "failed to save cached profile %q: %s"
18 | errProfileNotFound = "no such profile %q configured"
19 | logSessionExpires = "session will expire (after applying grace) %s"
20 | logStrategyWithProfile = "using strategy %q (cache: %t) for profile %q"
21 | )
22 |
23 | // Strategy identifies a way of aquiring short-term, cacheable credentials
24 | type Strategy interface {
25 |
26 | // Credentials acquires actual credentials
27 | Credentials(*session.Session) (*credentials.Credentials, error)
28 |
29 | // IsCacheable indicates the output of this strategy can be cached
30 | IsCacheable() bool
31 |
32 | // Name returns the name of this strategy
33 | Name() string
34 |
35 | // Profile returns the name of the profile used (if applicable, otherwise nil)
36 | Profile() *config.Profile
37 | }
38 |
39 | // Apply applies all configured strategy, depending on the given Config
40 | func Apply(cfg *config.Config) (*credentials.Credentials, error) {
41 |
42 | var (
43 | sess *session.Session
44 | source *config.Profile
45 | target = cfg.Profiles[cfg.Profile]
46 | )
47 |
48 | if target == nil {
49 | return nil, fmt.Errorf(errProfileNotFound, cfg.Profile)
50 | }
51 |
52 | source = cfg.Profiles[target.SourceProfile]
53 |
54 | strategies := []Strategy{
55 | &LongTerm{
56 | Profiles: []*config.Profile{source, target},
57 | },
58 | &SessionToken{
59 | Duration: cfg.Duration,
60 | Generator: cfg.Generator,
61 | Grace: cfg.Grace,
62 | MFASerial: cfg.MFASerial,
63 | Profiles: []*config.Profile{source, target},
64 | },
65 | &AssumeRole{
66 | Duration: cfg.Duration,
67 | Grace: cfg.Grace,
68 | Profiles: []*config.Profile{source, target},
69 | },
70 | }
71 |
72 | var last *credentials.Credentials
73 |
74 | for _, a := range strategies {
75 |
76 | var current *credentials.Credentials
77 |
78 | profile := a.Profile()
79 |
80 | if profile == nil {
81 | continue
82 | }
83 |
84 | cache := !cfg.NoCache && a.IsCacheable()
85 |
86 | log.Debug(logStrategyWithProfile, a.Name(), cache, profile.Name)
87 |
88 | // try to load
89 | if cache {
90 |
91 | creds, err := credentials.Load(profile.Name)
92 |
93 | if err != nil {
94 | log.Debug(errProfileCacheLoadFailed, profile.Name, err)
95 | } else if !creds.IsValid() {
96 | log.Debug(errProfileCacheLoadExpired, profile.Name)
97 | } else {
98 | current = creds
99 | }
100 |
101 | }
102 |
103 | // try to acquire
104 | if current == nil {
105 |
106 | creds, err := a.Credentials(sess)
107 |
108 | if err != nil {
109 | return nil, fmt.Errorf(errProfileAquisitionFailed, profile.Name, err)
110 | }
111 |
112 | current = creds
113 |
114 | // try to save
115 | if cache {
116 |
117 | if err := current.Save(); err != nil {
118 | return nil, fmt.Errorf(errProfileCacheSaveFailed, profile.Name, err)
119 | }
120 |
121 | }
122 |
123 | }
124 |
125 | last = current
126 |
127 | if sess == nil {
128 | sess = current.NewSession()
129 | } else {
130 | sess = current.UpdateSession(sess)
131 | }
132 |
133 | }
134 |
135 | if last.Expires.Second() > 0 {
136 | log.Debug(logSessionExpires, human.Time(last.Expires))
137 | }
138 |
139 | return last, nil
140 |
141 | }
142 |
--------------------------------------------------------------------------------
/target/mfa/mfa.go:
--------------------------------------------------------------------------------
1 | package mfa
2 |
3 | import (
4 | "encoding/base32"
5 | "time"
6 |
7 | "github.com/aws/aws-sdk-go/aws/session"
8 | "github.com/aws/aws-sdk-go/service/iam"
9 | "github.com/aws/aws-sdk-go/service/sts"
10 | "github.com/kreuzwerker/awsu/log"
11 | "github.com/kreuzwerker/awsu/source"
12 | "github.com/pkg/errors"
13 | )
14 |
15 | const (
16 | errAddToSource = "failed to add %q to source %q"
17 | errCalculateFirstOTP = "failed to calculate first one-time password"
18 | errCalculateSecondOTP = "failed to calculate second one-time password"
19 | errCreateVirtualDevice = "failed to create virtual AWS MFA device"
20 | errDeactivateVirtualDevice = "failed to deactivate virtual AWS MFA device with serial %q"
21 | errDecodeSecret = "failed to decode virtual AWS MFA device secret"
22 | errDeleteSerialDetermination = "failed to determine serial number for device deletion"
23 | errDeleteVirtualDevice = "failed to delete virtual AWS MFA device with serial %q"
24 | errEnableVirtualDevice = "failed to enable virtual AWS MFA device"
25 | errRemoveFromSource = "failed to remove %q from source %q"
26 | logAddSecretToSource = "adding secret to source %q"
27 | logCreateVirtualDevice = "create virtual AWS MFA device"
28 | logDeactivateVirtualDevice = "disable virtual AWS MFA device with serial %q"
29 | logDeleteVirtualDevice = "delete virtual AWS MFA device with serial %q"
30 | logEnableVirtualDevice = "enable virtual AWS MFA devices with codes %q and %q"
31 | )
32 |
33 | // MFA implements AWS virtual MFA devices as target
34 | type MFA struct {
35 | iam *iam.IAM
36 | source source.Source
37 | sts *sts.STS
38 | }
39 |
40 | // New initializes a AWS virtual MFA device as target
41 | func New(sess *session.Session, s source.Source) (*MFA, error) {
42 |
43 | return &MFA{
44 | iam: iam.New(sess),
45 | sts: sts.New(sess),
46 | source: s,
47 | }, nil
48 |
49 | }
50 |
51 | // Add adds virtual MFA to the source and associates it with the given IAM
52 | // username and returns MFA serial and TOTP secret
53 | func (m *MFA) Add(username string) (*string, []byte, error) {
54 |
55 | serial, secret, err := m.create(username)
56 |
57 | if err != nil {
58 | return nil, nil, err
59 | }
60 |
61 | if err := m.enable(username, serial, secret); err != nil {
62 | return nil, nil, err
63 | }
64 |
65 | return serial, secret, nil
66 |
67 | }
68 |
69 | // Delete removes a virtual MFA from the source including it's association with
70 | // the given IAM username
71 | func (m *MFA) Delete(username string) error {
72 |
73 | res, err := m.sts.GetCallerIdentity(&sts.GetCallerIdentityInput{})
74 |
75 | if err != nil {
76 | return errors.Wrapf(err, errDeleteSerialDetermination)
77 | }
78 |
79 | serial, err := CallerIdentityToSerial(res.Arn)
80 |
81 | if err != nil {
82 | return err
83 | }
84 |
85 | // ignore errors here
86 | m.deactivate(username, &serial)
87 |
88 | if err := m.delete(&serial); err != nil {
89 | return err
90 | }
91 |
92 | return nil
93 |
94 | }
95 |
96 | // create creates the virtual MFA device
97 | func (m *MFA) create(username string) (*string, []byte, error) {
98 |
99 | log.Debug(logCreateVirtualDevice)
100 |
101 | res, err := m.iam.CreateVirtualMFADevice(&iam.CreateVirtualMFADeviceInput{
102 | VirtualMFADeviceName: &username,
103 | })
104 |
105 | if err != nil {
106 | return nil, nil, errors.Wrapf(err, errCreateVirtualDevice)
107 | }
108 |
109 | secret, err := base32.StdEncoding.DecodeString(string(res.VirtualMFADevice.Base32StringSeed))
110 |
111 | if err != nil {
112 | return nil, nil, errors.Wrapf(err, errDecodeSecret)
113 | }
114 |
115 | return res.VirtualMFADevice.SerialNumber, secret, nil
116 |
117 | }
118 |
119 | // deactivate deactivates the virtual MFA device and removes it from the source
120 | func (m *MFA) deactivate(username string, serial *string) error {
121 |
122 | log.Debug(logDeactivateVirtualDevice, *serial)
123 |
124 | _, err := m.iam.DeactivateMFADevice(&iam.DeactivateMFADeviceInput{
125 | SerialNumber: serial,
126 | UserName: &username,
127 | })
128 |
129 | if err != nil {
130 | return errors.Wrapf(err, errDeactivateVirtualDevice, *serial)
131 | }
132 |
133 | name, err := SerialToName(serial)
134 |
135 | if err != nil {
136 | return err
137 | }
138 |
139 | if err := m.source.Delete(name); err != nil {
140 | return errors.Wrapf(err, errRemoveFromSource, name, m.source.Name())
141 | }
142 |
143 | return nil
144 |
145 | }
146 |
147 | // delete deletes the virtual MFA device
148 | func (m *MFA) delete(serial *string) error {
149 |
150 | log.Debug(logDeleteVirtualDevice, *serial)
151 |
152 | _, err := m.iam.DeleteVirtualMFADevice(&iam.DeleteVirtualMFADeviceInput{
153 | SerialNumber: serial,
154 | })
155 |
156 | if err != nil {
157 | return errors.Wrapf(err, errDeleteVirtualDevice, *serial)
158 | }
159 |
160 | return nil
161 |
162 | }
163 |
164 | // enable enables the virtual MFA device and adds it from the source
165 | func (m *MFA) enable(username string, serial *string, secret []byte) error {
166 |
167 | log.Debug(logAddSecretToSource, m.source.Name())
168 |
169 | name, err := SerialToName(serial)
170 |
171 | if err != nil {
172 | return err
173 | }
174 |
175 | if err = m.source.Add(name, secret); err != nil {
176 | return errors.Wrapf(err, errAddToSource, name, m.source.Name())
177 | }
178 |
179 | otp1, err := m.source.Generate(time.Now(), name)
180 |
181 | if err != nil {
182 | return errors.Wrapf(err, errCalculateFirstOTP)
183 | }
184 |
185 | otp2, err := m.source.Generate(time.Now().Add(30*time.Second), name)
186 |
187 | if err != nil {
188 | return errors.Wrapf(err, errCalculateSecondOTP)
189 | }
190 |
191 | log.Debug(logEnableVirtualDevice, otp1, otp2)
192 |
193 | if _, err := m.iam.EnableMFADevice(&iam.EnableMFADeviceInput{
194 | AuthenticationCode1: &otp1,
195 | AuthenticationCode2: &otp2,
196 | SerialNumber: serial,
197 | UserName: &username,
198 | }); err != nil {
199 | return errors.Wrapf(err, errEnableVirtualDevice)
200 | }
201 |
202 | return nil
203 |
204 | }
205 |
--------------------------------------------------------------------------------
/target/mfa/name.go:
--------------------------------------------------------------------------------
1 | package mfa
2 |
3 | import (
4 | "fmt"
5 | "strings"
6 |
7 | "github.com/aws/aws-sdk-go/aws/arn"
8 | "github.com/pkg/errors"
9 | )
10 |
11 | const (
12 | errParseARN = "failed to parse %q as ARN"
13 | )
14 |
15 | // CallerIdentityToSerial converts a caller identity ARN to a MFA serial
16 | func CallerIdentityToSerial(i *string) (string, error) {
17 |
18 | a, err := arn.Parse(*i)
19 |
20 | if err != nil {
21 | return "", errors.Wrapf(err, errParseARN, *i)
22 | }
23 |
24 | return strings.Replace(a.String(), ":user/", ":mfa/", 1), nil
25 |
26 | }
27 |
28 | // SerialToName converts a MFA serial to a source name
29 | func SerialToName(i *string) (string, error) {
30 |
31 | a, err := arn.Parse(*i)
32 |
33 | if err != nil {
34 | return "", errors.Wrapf(err, errParseARN, *i)
35 | }
36 |
37 | var (
38 | issuer = fmt.Sprintf("aws/iam/%s", a.AccountID)
39 | name = strings.TrimPrefix(a.Resource, "mfa/")
40 | )
41 |
42 | return strings.Join([]string{
43 | issuer,
44 | name,
45 | }, ":"), nil
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/target/mfa/name_test.go:
--------------------------------------------------------------------------------
1 | package mfa
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/aws/aws-sdk-go/aws"
7 | "github.com/stretchr/testify/assert"
8 | "github.com/stretchr/testify/require"
9 | )
10 |
11 | func TestCallerIdentityToSerial(t *testing.T) {
12 |
13 | var (
14 | assert = assert.New(t)
15 | require = require.New(t)
16 | )
17 |
18 | name, err := CallerIdentityToSerial(aws.String("arn:aws:iam::1234567890:user/foo"))
19 |
20 | require.NoError(err)
21 | assert.Equal("arn:aws:iam::1234567890:mfa/foo", name)
22 |
23 | name, err = CallerIdentityToSerial(aws.String("foo"))
24 |
25 | assert.EqualError(err, `failed to parse "foo" as ARN: arn: invalid prefix`)
26 | assert.Empty(name)
27 |
28 | }
29 |
30 | func TestSerialToName(t *testing.T) {
31 |
32 | var (
33 | assert = assert.New(t)
34 | require = require.New(t)
35 | )
36 |
37 | name, err := SerialToName(aws.String("arn:aws:iam::1234567890:mfa/foo"))
38 |
39 | require.NoError(err)
40 | assert.Equal("aws/iam/1234567890:foo", name)
41 |
42 | name, err = SerialToName(aws.String("foo"))
43 |
44 | assert.EqualError(err, `failed to parse "foo" as ARN: arn: invalid prefix`)
45 | assert.Empty(name)
46 |
47 | }
48 |
--------------------------------------------------------------------------------