Example #1
0
func ExampleSTS_GetSessionToken() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sts.New(sess)

	params := &sts.GetSessionTokenInput{
		DurationSeconds: aws.Int64(1),
		SerialNumber:    aws.String("serialNumberType"),
		TokenCode:       aws.String("tokenCodeType"),
	}
	resp, err := svc.GetSessionToken(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
// Retrieve generates a new set of temporary credentials using STS.
func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) {

	// Apply defaults where parameters are not set.
	if p.Client == nil {
		p.Client = sts.New(nil)
	}
	if p.RoleSessionName == "" {
		// Try to work out a role name that will hopefully end up unique.
		p.RoleSessionName = fmt.Sprintf("%d", time.Now().UTC().UnixNano())
	}
	if p.Duration == 0 {
		// Expire as often as AWS permits.
		p.Duration = 15 * time.Minute
	}

	roleOutput, err := p.Client.AssumeRole(&sts.AssumeRoleInput{
		DurationSeconds: aws.Long(int64(p.Duration / time.Second)),
		RoleARN:         aws.String(p.RoleARN),
		RoleSessionName: aws.String(p.RoleSessionName),
	})

	if err != nil {
		return credentials.Value{}, err
	}

	// We will proactively generate new credentials before they expire.
	p.SetExpiration(*roleOutput.Credentials.Expiration, p.ExpiryWindow)

	return credentials.Value{
		AccessKeyID:     *roleOutput.Credentials.AccessKeyID,
		SecretAccessKey: *roleOutput.Credentials.SecretAccessKey,
		SessionToken:    *roleOutput.Credentials.SessionToken,
	}, nil
}
Example #3
0
func ExampleSTS_GetFederationToken() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sts.New(sess)

	params := &sts.GetFederationTokenInput{
		Name:            aws.String("userNameType"), // Required
		DurationSeconds: aws.Int64(1),
		Policy:          aws.String("sessionPolicyDocumentType"),
	}
	resp, err := svc.GetFederationToken(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Example #4
0
func ExampleSTS_AssumeRole() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sts.New(sess)

	params := &sts.AssumeRoleInput{
		RoleArn:         aws.String("arnType"),             // Required
		RoleSessionName: aws.String("roleSessionNameType"), // Required
		DurationSeconds: aws.Int64(1),
		ExternalId:      aws.String("externalIdType"),
		Policy:          aws.String("sessionPolicyDocumentType"),
		SerialNumber:    aws.String("serialNumberType"),
		TokenCode:       aws.String("tokenCodeType"),
	}
	resp, err := svc.AssumeRole(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Example #5
0
func ExampleSTS_DecodeAuthorizationMessage() {
	svc := sts.New(nil)

	params := &sts.DecodeAuthorizationMessageInput{
		EncodedMessage: aws.String("encodedMessageType"), // Required
	}
	resp, err := svc.DecodeAuthorizationMessage(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.Prettify(resp))
}
Example #6
0
func ExampleSTS_AssumeRoleWithSAML() {
	svc := sts.New(nil)

	params := &sts.AssumeRoleWithSAMLInput{
		PrincipalARN:    aws.String("arnType"),           // Required
		RoleARN:         aws.String("arnType"),           // Required
		SAMLAssertion:   aws.String("SAMLAssertionType"), // Required
		DurationSeconds: aws.Long(1),
		Policy:          aws.String("sessionPolicyDocumentType"),
	}
	resp, err := svc.AssumeRoleWithSAML(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS Error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
Example #7
0
func (app *App) roleHandler(w http.ResponseWriter, r *http.Request) {
	svc := sts.New(session.New(), &aws.Config{LogLevel: aws.LogLevel(2)})
	resp, err := svc.AssumeRole(&sts.AssumeRoleInput{
		RoleArn:         aws.String(app.RoleArn),
		RoleSessionName: aws.String("aws-mock-metadata"),
	})
	if err != nil {
		log.Errorf("Error assuming role %+v", err)
		http.Error(w, err.Error(), 500)
		return
	}
	log.Debugf("STS response %+v", resp)
	credentials := Credentials{
		AccessKeyID:     *resp.Credentials.AccessKeyId,
		Code:            "Success",
		Expiration:      resp.Credentials.Expiration.Format("2006-01-02T15:04:05Z"),
		LastUpdated:     time.Now().Format("2006-01-02T15:04:05Z"),
		SecretAccessKey: *resp.Credentials.SecretAccessKey,
		Token:           *resp.Credentials.SessionToken,
		Type:            "AWS-HMAC",
	}
	if err := json.NewEncoder(w).Encode(credentials); err != nil {
		log.Errorf("Error sending json %+v", err)
		http.Error(w, err.Error(), 500)
	}
}
Example #8
0
func ExampleSTS_GetSessionToken() {
	svc := sts.New(nil)

	params := &sts.GetSessionTokenInput{
		DurationSeconds: aws.Int64(1),
		SerialNumber:    aws.String("serialNumberType"),
		TokenCode:       aws.String("tokenCodeType"),
	}
	resp, err := svc.GetSessionToken(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.Prettify(resp))
}
Example #9
0
// assumeRole uses IAM credentials to assume a role
func (p *VaultProvider) assumeRole(creds credentials.Value, roleArn string) (sts.Credentials, error) {
	client := sts.New(session.New(&aws.Config{
		Credentials: credentials.NewCredentials(&credentials.StaticProvider{Value: creds}),
	}))

	input := &sts.AssumeRoleInput{
		RoleArn:         aws.String(roleArn),
		RoleSessionName: aws.String(p.roleSessionName()),
		DurationSeconds: aws.Int64(int64(p.AssumeRoleDuration.Seconds())),
	}

	// if we don't have a session, we need to include MFA token in the AssumeRole call
	if mfa, ok := p.profiles[p.profile]["mfa_serial"]; ok {
		input.SerialNumber = aws.String(mfa)
		if p.MfaToken == "" {
			token, err := p.MfaPrompt(fmt.Sprintf("Enter token for %s: ", mfa))
			if err != nil {
				return sts.Credentials{}, err
			}
			input.TokenCode = aws.String(token)
		} else {
			input.TokenCode = aws.String(p.MfaToken)
		}
	}

	log.Printf("Assuming role %s with iam credentials", roleArn)
	resp, err := client.AssumeRole(input)
	if err != nil {
		return sts.Credentials{}, err
	}

	return *resp.Credentials, nil
}
Example #10
0
func (p *VaultProvider) getSessionToken(creds *credentials.Value) (sts.Credentials, error) {
	params := &sts.GetSessionTokenInput{
		DurationSeconds: aws.Int64(int64(p.SessionDuration.Seconds())),
	}

	if mfa, ok := p.profiles[p.profile]["mfa_serial"]; ok {
		params.SerialNumber = aws.String(mfa)
		if p.MfaToken == "" {
			token, err := p.MfaPrompt(fmt.Sprintf("Enter token for %s: ", mfa))
			if err != nil {
				return sts.Credentials{}, err
			}
			params.TokenCode = aws.String(token)
		} else {
			params.TokenCode = aws.String(p.MfaToken)
		}
	}

	client := sts.New(session.New(&aws.Config{
		Credentials: credentials.NewCredentials(&credentials.StaticProvider{
			Value: *creds,
		}),
	}))

	log.Printf("Getting new session token for profile %s", sourceProfile(p.profile, p.profiles))
	resp, err := client.GetSessionToken(params)
	if err != nil {
		return sts.Credentials{}, err
	}

	return *resp.Credentials, nil
}
Example #11
0
func ExampleSTS_AssumeRoleWithWebIdentity() {
	svc := sts.New(nil)

	params := &sts.AssumeRoleWithWebIdentityInput{
		RoleArn:          aws.String("arnType"),         // Required
		RoleSessionName:  aws.String("userNameType"),    // Required
		WebIdentityToken: aws.String("clientTokenType"), // Required
		DurationSeconds:  aws.Int64(1),
		Policy:           aws.String("sessionPolicyDocumentType"),
		ProviderId:       aws.String("urlType"),
	}
	resp, err := svc.AssumeRoleWithWebIdentity(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.Prettify(resp))
}
Example #12
0
func (p *VaultProvider) assumeRole(session sts.Credentials, roleArn string) (sts.Credentials, error) {
	client := p.client
	if client == nil {
		client = sts.New(&aws.Config{Credentials: credentials.NewStaticCredentials(
			*session.AccessKeyId,
			*session.SecretAccessKey,
			*session.SessionToken,
		)})
	}

	// Try to work out a role name that will hopefully end up unique.
	roleSessionName := fmt.Sprintf("%d", time.Now().UTC().UnixNano())

	input := &sts.AssumeRoleInput{
		RoleArn:         aws.String(roleArn),
		RoleSessionName: aws.String(roleSessionName),
		DurationSeconds: aws.Int64(int64(p.AssumeRoleDuration.Seconds())),
	}

	log.Printf("Assuming role %s", roleArn)
	resp, err := client.AssumeRole(input)
	if err != nil {
		return sts.Credentials{}, err
	}

	return *resp.Credentials, nil
}
Example #13
0
func ExampleSTS_AssumeRoleWithWebIdentity() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sts.New(sess)

	params := &sts.AssumeRoleWithWebIdentityInput{
		RoleArn:          aws.String("arnType"),             // Required
		RoleSessionName:  aws.String("roleSessionNameType"), // Required
		WebIdentityToken: aws.String("clientTokenType"),     // Required
		DurationSeconds:  aws.Int64(1),
		Policy:           aws.String("sessionPolicyDocumentType"),
		ProviderId:       aws.String("urlType"),
	}
	resp, err := svc.AssumeRoleWithWebIdentity(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Example #14
0
func ExampleSTS_AssumeRoleWithSAML() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sts.New(sess)

	params := &sts.AssumeRoleWithSAMLInput{
		PrincipalArn:    aws.String("arnType"),           // Required
		RoleArn:         aws.String("arnType"),           // Required
		SAMLAssertion:   aws.String("SAMLAssertionType"), // Required
		DurationSeconds: aws.Int64(1),
		Policy:          aws.String("sessionPolicyDocumentType"),
	}
	resp, err := svc.AssumeRoleWithSAML(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Example #15
0
func (k *AWSKey) stsClient() *sts.STS {
	sess := session.New(&aws.Config{
		Credentials: credentials.NewStaticCredentials(
			k.ID,
			k.Secret,
			"", // Temporary session token
		),
	})
	return sts.New(sess)
}
Example #16
0
// GetConsoleLoginURL works with the AWS API to create a federation login URL to
// the web console for the given environment which will expire after timeout
func (a *AWSCredentialStore) GetConsoleLoginURL(env string, timeout int, subconsole string) (string, error) {
	e, ok := a.Credentials[env]
	if !ok {
		return "", fmt.Errorf("Environment '%s' was not found.", env)
	}

	c := credentials.NewStaticCredentials(e.AWSAccessKeyID, e.AWSSecretAccessKey, "")

	// Get the username of the current user
	iam := iam.New(&aws.Config{Credentials: c})
	usr, err := iam.GetUser(nil)
	if err != nil {
		return "", err
	}

	username := "******"
	if usr.User.UserName != nil {
		username = *usr.User.UserName
	}

	// Create STS url for current user
	svc := sts.New(&aws.Config{Credentials: c})

	resp, err := svc.GetFederationToken(&sts.GetFederationTokenInput{
		Name:            aws.String(fmt.Sprintf("awsenv-%s", username)),
		DurationSeconds: aws.Int64(int64(timeout)),
		Policy:          aws.String(iamPolicy),
	})

	if err != nil {
		return "", err
	}

	signinToken, err := a.getFederatedSigninToken(resp)
	if err != nil {
		return "", err
	}

	p := url.Values{
		"Action":      []string{"login"},
		"Issuer":      []string{"https://github.com/Luzifer/awsenv"},
		"Destination": []string{fmt.Sprintf("https://console.aws.amazon.com/%s/home?region=%s", subconsole, e.AWSRegion)},
		"SigninToken": []string{signinToken},
	}
	out := url.URL{
		Scheme:   "https",
		Host:     "signin.aws.amazon.com",
		Path:     "federation",
		RawQuery: p.Encode(),
	}

	return out.String(), nil

}
Example #17
0
func setupIntegrationTest() (rc *RoleSet) {
	client := sts.New(
		session.New(),
		&aws.Config{Credentials: credentials.NewEnvCredentials()},
	)

	rc = NewRoleSet(client)
	rc.SetRole("valid", os.Getenv("FINTO_VALID_ARN"))
	rc.SetRole("invalid", os.Getenv("FINTO_INVALID_ARN"))

	return
}
// NewCredentials returns a pointer to a new Credentials object wrapping the
// AssumeRoleProvider. The credentials will expire every 15 minutes and the
// role will be named after a nanosecond timestamp of this operation.
//
// Takes a Config provider to create the STS client. The ConfigProvider is
// satisfied by the session.Session type.
func NewCredentials(c client.ConfigProvider, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials {
	p := &AssumeRoleProvider{
		Client:   sts.New(c),
		RoleARN:  roleARN,
		Duration: DefaultDuration,
	}

	for _, option := range options {
		option(p)
	}

	return credentials.NewCredentials(p)
}
func ExampleSTS_GetCallerIdentity() {
	svc := sts.New(session.New())

	var params *sts.GetCallerIdentityInput
	resp, err := svc.GetCallerIdentity(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Example #20
0
func ExampleSTS_DecodeAuthorizationMessage() {
	svc := sts.New(session.New())

	params := &sts.DecodeAuthorizationMessageInput{
		EncodedMessage: aws.String("encodedMessageType"), // Required
	}
	resp, err := svc.DecodeAuthorizationMessage(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Example #21
0
// Return AWS Credentials using current profile. Must supply source config.
func (c *CLIConfig) CredentialsFromProfile(conf *aws.Config) (*credentials.Credentials, error) {
	// If the profile name is equal to the source profile, there is no role to assume so return
	// the source credentials as they were captured.
	if c.ProfileName == c.SourceProfile {
		return c.SourceCredentials, nil
	}
	srcCfg := aws.NewConfig().Copy(conf).WithCredentials(c.SourceCredentials)
	svc := sts.New(session.New(), srcCfg)
	res, err := svc.AssumeRole(c.AssumeRoleInput)
	if err != nil {
		return nil, err
	}
	return credentials.NewStaticCredentials(
		*res.Credentials.AccessKeyId,
		*res.Credentials.SecretAccessKey,
		*res.Credentials.SessionToken,
	), nil
}
Example #22
0
func main() {
	r := os.Getenv("AWS_REGION")
	if r == "" {
		r = "us-east-1"
	}

	var role = flag.String("role", "", "The role ARN we will be assuming")
	var sess = flag.String("session", "assumerole", "Session name to include in role assumption [optional]")
	var externalid = flag.String("externalid", "", "External ID specified to assume role [optional]")

	flag.Parse()

	var awsexternalid = aws.String(*externalid)

	if *externalid == "" {
		awsexternalid = nil
	}

	svc := sts.New(session.New(), &aws.Config{Region: aws.String(r)})

	params := &sts.AssumeRoleInput{
		RoleArn:         aws.String(*role), // Required
		RoleSessionName: aws.String(*sess), // Required
		ExternalId:      awsexternalid,
	}

	// Call the DescribeInstances Operation
	resp, err := svc.AssumeRole(params)
	if err != nil {
		panic(err)
	}

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Printf("export AWS_ACCESS_KEY=\"%s\"\n", *resp.Credentials.AccessKeyId)
	fmt.Printf("export AWS_SECRET_KEY=\"%s\"\n", *resp.Credentials.SecretAccessKey)
	fmt.Printf("export AWS_SESSION_TOKEN=\"%s\"\n", *resp.Credentials.SessionToken)
}
Example #23
0
func main() {
	flag.Parse()

	if *printver {
		fmt.Println("finto", finto.Version)
		os.Exit(0)
	}

	logdest, err := prepareLog(*logfile)
	if err != nil {
		panic(err)
	}
	defer logdest.Close()

	config, err := LoadConfig(*fintorc)
	if err != nil {
		panic(err)
	}

	// SharedCredentialsProvider defaults to file=~/.aws/credentials and
	// profile=default when provided zero-value strings
	rs := finto.NewRoleSet(sts.New(session.New(), &aws.Config{
		Credentials: credentials.NewSharedCredentials(
			config.Credentials.File,
			config.Credentials.Profile,
		),
	}))

	for alias, arn := range config.Roles {
		rs.SetRole(alias, arn)
	}

	context, err := finto.InitFintoContext(rs, config.DefaultRole)
	if err != nil {
		fmt.Println("warning: default role not set:", err)
	}

	router := finto.FintoRouter(&context)
	handler := handlers.LoggingHandler(logdest, router)
	err = http.ListenAndServe(fmt.Sprint(*addr, ":", *port), handler)
	if err != nil {
		panic(err)
	}
}
Example #24
0
func assumeRole(sessionName, arn string, f func()) {

	const (
		awsAccessKeyID     = "AWS_ACCESS_KEY_ID"
		awsSecretAccessKey = "AWS_SECRET_ACCESS_KEY"
		awsSessionToken    = "AWS_SESSION_TOKEN"
	)

	var (
		oldAwsAccessKeyID     = os.Getenv(awsAccessKeyID)
		oldAwsSecretAccessKey = os.Getenv(awsSecretAccessKey)
	)

	client = sts.New(session.New())

	req := &sts.AssumeRoleInput{
		DurationSeconds: aws.Int64(900),
		RoleArn:         aws.String(arn),
		RoleSessionName: aws.String(sessionName),
	}

	res, err := client.AssumeRole(req)

	if err != nil {
		panic(err)
	}

	fmt.Printf("Assuming role %q\n", arn)

	creds := res.Credentials

	// utilizing the default credentials detection chain here - in a deployment
	// situation this would be an instance profile
	os.Setenv(awsAccessKeyID, *creds.AccessKeyId)
	os.Setenv(awsSecretAccessKey, *creds.SecretAccessKey)
	os.Setenv(awsSessionToken, *creds.SessionToken)

	f()

	os.Setenv(awsAccessKeyID, oldAwsAccessKeyID)
	os.Setenv(awsSecretAccessKey, oldAwsSecretAccessKey)
	os.Unsetenv(awsSessionToken)

}
Example #25
0
// getMockedAwsIamStsApi establishes a httptest server to simulate behaviour
// of a real AWS' IAM & STS server
func getMockedAwsIamStsApi(endpoints []*iamEndpoint) (func(), *iam.IAM, *sts.STS) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		buf := new(bytes.Buffer)
		buf.ReadFrom(r.Body)
		requestBody := buf.String()

		log.Printf("[DEBUG] Received API %q request to %q: %s",
			r.Method, r.RequestURI, requestBody)

		for _, e := range endpoints {
			if r.Method == e.Request.Method && r.RequestURI == e.Request.Uri && requestBody == e.Request.Body {
				log.Printf("[DEBUG] Mock API responding with %d: %s", e.Response.StatusCode, e.Response.Body)

				w.WriteHeader(e.Response.StatusCode)
				w.Header().Set("Content-Type", e.Response.ContentType)
				w.Header().Set("X-Amzn-Requestid", "1b206dd1-f9a8-11e5-becf-051c60f11c4a")
				w.Header().Set("Date", time.Now().Format(time.RFC1123))

				fmt.Fprintln(w, e.Response.Body)
				return
			}
		}

		w.WriteHeader(400)
		return
	}))

	sc := awsCredentials.NewStaticCredentials("accessKey", "secretKey", "")

	sess, err := session.NewSession(&aws.Config{
		Credentials:                   sc,
		Region:                        aws.String("us-east-1"),
		Endpoint:                      aws.String(ts.URL),
		CredentialsChainVerboseErrors: aws.Bool(true),
	})
	if err != nil {
		panic(fmt.Sprintf("Error creating AWS Session: %s", err))
	}
	iamConn := iam.New(sess)
	stsConn := sts.New(sess)
	return ts.Close, iamConn, stsConn
}
Example #26
0
func assumeRole(roleArn string) {
	client := sts.New(session.New())
	duration := time.Hour * 1
	stsProvider := &stscreds.AssumeRoleProvider{
		Client:          client,
		Duration:        duration,
		RoleARN:         roleArn,
		RoleSessionName: "drone",
	}

	value, err := credentials.NewCredentials(stsProvider).Get()
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"error": err,
		}).Fatal("Error assuming role!")
	}
	os.Setenv("AWS_ACCESS_KEY_ID", value.AccessKeyID)
	os.Setenv("AWS_SECRET_ACCESS_KEY", value.SecretAccessKey)
	os.Setenv("AWS_SESSION_TOKEN", value.SessionToken)
}
Example #27
0
func (key MasterKey) createStsSession(config aws.Config, sess *session.Session) (*session.Session, error) {
	hostname, err := os.Hostname()
	if err != nil {
		return nil, err
	}
	stsService := sts.New(sess)
	name := "sops@" + hostname
	out, err := stsService.AssumeRole(&sts.AssumeRoleInput{
		RoleArn: &key.Role, RoleSessionName: &name})
	if err != nil {
		return nil, fmt.Errorf("Failed to assume role %q: %v", key.Role, err)
	}
	config.Credentials = credentials.NewStaticCredentials(*out.Credentials.AccessKeyId,
		*out.Credentials.SecretAccessKey, *out.Credentials.SessionToken)
	sess, err = session.NewSession(&config)
	if err != nil {
		return nil, fmt.Errorf("Failed to create new aws session: %v", err)
	}
	return sess, nil
}
Example #28
0
// assumeRoleFromSession takes a session created with GetSessionToken and uses that to assume a role
func (p *VaultProvider) assumeRoleFromSession(creds sts.Credentials, roleArn string) (sts.Credentials, error) {
	client := sts.New(session.New(&aws.Config{Credentials: credentials.NewStaticCredentials(
		*creds.AccessKeyId,
		*creds.SecretAccessKey,
		*creds.SessionToken,
	)}))

	input := &sts.AssumeRoleInput{
		RoleArn:         aws.String(roleArn),
		RoleSessionName: aws.String(p.roleSessionName()),
		DurationSeconds: aws.Int64(int64(p.AssumeRoleDuration.Seconds())),
	}

	log.Printf("Assuming role %s from session token", roleArn)
	resp, err := client.AssumeRole(input)
	if err != nil {
		return sts.Credentials{}, err
	}

	return *resp.Credentials, nil
}
Example #29
0
// New creates config with credentials for using with AWS SDK for Go
func New() *aws.Config {
	config := aws.NewConfig()
	if *role != "" {
		session := session.New(config)
		client := sts.New(session)
		resp, err := client.GetSessionToken(&sts.GetSessionTokenInput{})
		if err != nil {
			log.Fatal("Can't retrieve temprorarily credentials because of:", err)
		}
		config.WithCredentials(credentials.NewStaticCredentials(
			*resp.Credentials.AccessKeyId,
			*resp.Credentials.SecretAccessKey,
			*resp.Credentials.SessionToken))
	} else {
		config.WithCredentials(credentials.NewEnvCredentials())
	}
	config.WithRegion(*region)
	if *logging {
		config.WithLogLevel(aws.LogDebugWithHTTPBody)
	}
	return config
}
Example #30
0
// NewServer gives new server value created from the given configuration.
func NewServer(cfg *Config) *Server {
	awsCfg := &aws.Config{
		Credentials: credentials.NewStaticCredentials(cfg.AccessKey, cfg.SecretKey, ""),
		Region:      aws.String(cfg.region()),
	}

	if cfg.Log != nil {
		awsCfg.Logger = amazon.NewLogger(cfg.Log.Debug)
	}

	sess := session.New(awsCfg)

	s := &Server{
		cfg: cfg,
		sts: sts.New(sess),
		s3:  s3.New(sess),
	}

	if s.cfg.Kite != nil {
		s.cfg.Kite.HandleFunc("keygen.auth", s.Auth)
	}

	return s
}