Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a -reset flag to unset AWS tokens before using the SDK calls. Add -debug mode to help debug errors. #44

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
17 changes: 17 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Golang CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-go/ for more details
version: 2
jobs:
build:
docker:
# specify the version
- image: circleci/golang:1.12.1

# working_directory: /go/src/github.com/{{ORG_NAME}}/{{REPO_NAME}}
steps:
- checkout

# specify any bash command here prefixed with `run: `
- run: make test
- run: make bins
12 changes: 12 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
FROM golang:1.12-stretch as build

WORKDIR /src
COPY . .

RUN make test bin
RUN make bins

FROM debian:stretch

COPY --from=build /src/bin/* /usr/local/bin/
RUN chmod 555 /usr/local/bin/assume-role*
30 changes: 21 additions & 9 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
.PHONY: test clean bin
DOCKER_TAG = assume-role

bin/assume-role: *.go
go build -o $@ .
.PHONY: all test clean bins deps docker

bin: bin/assume-role

bin: bin/assume-role-Linux bin/assume-role-Darwin bin/assume-role-Windows.exe
bins: bin/assume-role-Linux bin/assume-role-Darwin bin/assume-role-Windows.exe

bin/assume-role-Linux: *.go
bin/assume-role: deps *.go
go build -o $@ .
bin/assume-role-Linux: deps *.go
env GOOS=linux go build -o $@ .
bin/assume-role-Darwin: *.go
bin/assume-role-Darwin: deps *.go
env GOOS=darwin go build -o $@ .
bin/assume-role-Windows.exe: *.go
bin/assume-role-Windows.exe: deps *.go
env GOOS=windows go build -o $@ .

deps:
go get -v -d ./...

update-deps:
go get -v -u -d ./...

clean:
rm -rf bin/*

test:
go test -race $(shell go list ./... | grep -v /vendor/)
test: deps
go test -race ./...

docker:
docker build --tag $(DOCKER_TAG) .
104 changes: 104 additions & 0 deletions assume.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package main

import (
"flag"
"fmt"
"os"
"regexp"
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"

log "github.com/sirupsen/logrus"
)

var (
duration *time.Duration
roleArnRe = regexp.MustCompile(`^arn:aws:iam::(.+):role/([^/]+)(/.+)?$`)
)

func init() {
duration = flag.Duration("duration", time.Hour, "The duration that the credentials will be valid for.")
}

func loadCredentials(role string) (*credentials.Value, error) {
// Load credentials from configFilePath if it exists, else use regular AWS config
if roleArnRe.MatchString(role) {
return assumeRole(role, "", *duration)
}

if _, err := os.Stat(configFilePath); err == nil {
log.WithField("configFilePath", configFilePath).Warn(
"Using deprecated role file, switch to config file" +
" (https://docs.aws.amazon.com/cli/latest/userguide/cli-roles.html)")

config, err := loadConfig()
if err != nil {
return nil, err
}

if roleConfig, ok := config[role]; ok {
return assumeRole(roleConfig.Role, roleConfig.MFA, *duration)
}

return nil, fmt.Errorf("%s not in %s", role, configFilePath)
}

return assumeProfile(role)
}

// assumeProfile assumes the named profile which must exist in ~/.aws/config
// (https://docs.aws.amazon.com/cli/latest/userguide/cli-roles.html) and returns the temporary STS
// credentials.
func assumeProfile(profile string) (*credentials.Value, error) {
log.Debug("Assuming role via named profile")
sess := session.Must(session.NewSessionWithOptions(session.Options{
Profile: profile,
SharedConfigState: session.SharedConfigEnable,
AssumeRoleTokenProvider: readTokenCode,
}))

creds, err := sess.Config.Credentials.Get()
if err != nil {
return nil, err
}
return &creds, nil
}

// assumeRole assumes the given role and returns the temporary STS credentials.
func assumeRole(role, mfa string, duration time.Duration) (*credentials.Value, error) {
log.Debug("Assume role via temporary STS credentials")
sess := session.Must(session.NewSession())

svc := sts.New(sess)

params := &sts.AssumeRoleInput{
RoleArn: aws.String(role),
RoleSessionName: aws.String("cli"),
DurationSeconds: aws.Int64(int64(duration / time.Second)),
}
if mfa != "" {
params.SerialNumber = aws.String(mfa)
token, err := readTokenCode()
if err != nil {
return nil, err
}
params.TokenCode = aws.String(token)
}

resp, err := svc.AssumeRole(params)

if err != nil {
return nil, err
}

var creds credentials.Value
creds.AccessKeyID = *resp.Credentials.AccessKeyId
creds.SecretAccessKey = *resp.Credentials.SecretAccessKey
creds.SessionToken = *resp.Credentials.SessionToken

return &creds, nil
}
3 changes: 2 additions & 1 deletion circle.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Version 1
machine:
environment:
GODIST: "go1.7.linux-amd64.tar.gz"
GODIST: "go1.12.linux-amd64.tar.gz"
post:
- mkdir -p download
- test -e download/$GODIST || curl -o download/$GODIST https://storage.googleapis.com/golang/$GODIST
Expand Down
44 changes: 44 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package main

import (
"bufio"
"fmt"
"io/ioutil"
"os"
"strings"

log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
)

type roleConfig struct {
Role string `yaml:"role"`
MFA string `yaml:"mfa"`
}

type config map[string]roleConfig

var configFilePath = fmt.Sprintf("%s/.aws/roles", os.Getenv("HOME"))

// readTokenCode reads the MFA token from Stdin.
func readTokenCode() (string, error) {
r := bufio.NewReader(os.Stdin)
fmt.Fprintf(os.Stderr, "MFA code: ")
text, err := r.ReadString('\n')
if err != nil {
return "", err
}
return strings.TrimSpace(text), nil
}

// loadConfig loads the ~/.aws/roles file.
func loadConfig() (config, error) {
log.WithField("configFilePath", configFilePath).Debug("Reading config...")
raw, err := ioutil.ReadFile(configFilePath)
if err != nil {
return nil, err
}

roleConfig := make(config)
return roleConfig, yaml.Unmarshal(raw, &roleConfig)
}
30 changes: 30 additions & 0 deletions env-var.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package main

import (
"flag"
"os"

log "github.com/sirupsen/logrus"
)

var reset *bool

func init() {
reset = flag.Bool("reset", false, "Reset AWS Env-var tokens (internally) before retrieving new credentials.")
}

func resetEnvVars() {
log.WithFields(log.Fields{
"AWS_ACCESS_KEY_ID": os.Getenv("AWS_ACCESS_KEY_ID"),
"AWS_SECRET_ACCESS_KEY": os.Getenv("AWS_SECRET_ACCESS_KEY"),
"AWS_SESSION_TOKEN": os.Getenv("AWS_SESSION_TOKEN"),
"AWS_SECURITY_TOKEN": os.Getenv("AWS_SECURITY_TOKEN"),
"ASSUMED_ROLE": os.Getenv("ASSUMED_ROLE"),
}).Debug("Resetting Token Env-vars. Showing prev vals")

os.Unsetenv("AWS_ACCESS_KEY_ID")
os.Unsetenv("AWS_SECRET_ACCESS_KEY")
os.Unsetenv("AWS_SESSION_TOKEN")
os.Unsetenv("AWS_SECURITY_TOKEN")
os.Unsetenv("ASSUMED_ROLE")
}
20 changes: 20 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package main

import (
"os"
"os/exec"

log "github.com/sirupsen/logrus"
)

func must(err error) {
if err != nil {
if _, ok := err.(*exec.ExitError); ok {
// Errors are already on Stderr.
os.Exit(1)
}

log.Errorf("%v", err)
os.Exit(1)
}
}
35 changes: 35 additions & 0 deletions exec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import (
"os"
"os/exec"
"syscall"

"github.com/aws/aws-sdk-go/aws/credentials"
log "github.com/sirupsen/logrus"
)

func execWithCredentials(role string, argv []string, creds *credentials.Value) error {
argv0, err := exec.LookPath(argv[0])
if err != nil {
return err
}

os.Setenv("AWS_ACCESS_KEY_ID", creds.AccessKeyID)
os.Setenv("AWS_SECRET_ACCESS_KEY", creds.SecretAccessKey)
os.Setenv("AWS_SESSION_TOKEN", creds.SessionToken)
os.Setenv("AWS_SECURITY_TOKEN", creds.SessionToken)
os.Setenv("ASSUMED_ROLE", role)

log.WithFields(log.Fields{
"command": argv0,
"AWS_ACCESS_KEY_ID": os.Getenv("AWS_ACCESS_KEY_ID"),
"AWS_SECRET_ACCESS_KEY": os.Getenv("AWS_SECRET_ACCESS_KEY"),
"AWS_SESSION_TOKEN": os.Getenv("AWS_SESSION_TOKEN"),
"AWS_SECURITY_TOKEN": os.Getenv("AWS_SECURITY_TOKEN"),
"ASSUMED_ROLE": os.Getenv("ASSUMED_ROLE"),
}).Debug("Executing command with credentials...")

env := os.Environ()
return syscall.Exec(argv0, argv, env)
}
17 changes: 17 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module github.com/remind101/assume-role

go 1.12

require (
github.com/aws/aws-sdk-go v1.19.1
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
github.com/kr/pretty v0.1.0 // indirect
github.com/kr/pty v1.1.4 // indirect
github.com/sirupsen/logrus v1.4.0
github.com/stretchr/testify v1.3.0 // indirect
golang.org/x/crypto v0.0.0-20190320223903-b7391e95e576 // indirect
golang.org/x/net v0.0.0-20190322120337-addf6b3196f6 // indirect
golang.org/x/sys v0.0.0-20190322080309-f49334f85ddc // indirect
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
gopkg.in/yaml.v2 v2.2.2
)
33 changes: 33 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
github.com/aws/aws-sdk-go v1.19.1 h1:8kOP0/XGJwXIFlYoD1DAtA39cAjc15Iv/QiDMKitD9U=
github.com/aws/aws-sdk-go v1.19.1/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/pty v1.1.4/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.4.0 h1:yKenngtzGh+cUSSh6GWbxW2abRqhYUSR/t/6+2QqNvE=
github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190320223903-b7391e95e576 h1:aUX/1G2gFSs4AsJJg2cL3HuoRhCSCz733FE5GUSuaT4=
golang.org/x/crypto v0.0.0-20190320223903-b7391e95e576/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20190322120337-addf6b3196f6/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190322080309-f49334f85ddc h1:4gbWbmmPFp4ySWICouJl6emP0MyS31yy9SrTlAGFT+g=
golang.org/x/sys v0.0.0-20190322080309-f49334f85ddc/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
Loading