func New(config Config) (*Client, error) { credentials := credentials.NewStaticCredentials(config.AccessKey, config.SecretKey, "") sdkConfig := &aws.Config{ Credentials: credentials, Region: aws.String(config.Region), } session := session.New(sdkConfig) if config.CloudFormationWaitTimeout == 0 { return nil, fmt.Errorf("AWS config CloudFormationWaitTimeout must be a positive timeout") } ec2EndpointConfig, err := config.getEndpoint("ec2") if err != nil { return nil, err } cloudformationEndpointConfig, err := config.getEndpoint("cloudformation") if err != nil { return nil, err } iamEndpointConfig, err := config.getEndpoint("iam") if err != nil { return nil, err } return &Client{ EC2: ec2.New(session, ec2EndpointConfig), CloudFormation: cloudformation.New(session, cloudformationEndpointConfig), IAM: iam.New(session, iamEndpointConfig), Clock: clockImpl{}, CloudFormationWaitTimeout: config.CloudFormationWaitTimeout, }, nil }
/// validateUserAccess checks for the "AdministratorAccess" policy needed to create a rack. func validateUserAccess(region string, creds *AwsCredentials) error { // this validation need to check for actual permissions somehow and not // just a policy name return nil Iam := iam.New(session.New(), awsConfig(region, creds)) userOutput, err := Iam.GetUser(&iam.GetUserInput{}) if err != nil { if ae, ok := err.(awserr.Error); ok { return fmt.Errorf("%s. See %s", ae.Code(), iamUserURL) } return fmt.Errorf("%s. See %s", err, iamUserURL) } policies, err := Iam.ListAttachedUserPolicies(&iam.ListAttachedUserPoliciesInput{ UserName: userOutput.User.UserName, }) if err != nil { if ae, ok := err.(awserr.Error); ok { return fmt.Errorf("%s. See %s", ae.Code(), iamUserURL) } } for _, policy := range policies.AttachedPolicies { if "AdministratorAccess" == *policy.PolicyName { return nil } } msg := fmt.Errorf("Administrator access needed. See %s", iamUserURL) stdcli.QOSEventSend("cli-install", distinctID, stdcli.QOSEventProperties{Error: msg}) return stdcli.Error(msg) }
func (infra *Infrastructure) createIAMLambdaRolePolicy(roleName string) error { svc := iam.New(session.New(), infra.config) _, err := svc.PutRolePolicy(&iam.PutRolePolicyInput{ PolicyDocument: aws.String(`{ "Version": "2012-10-17", "Statement": [ { "Action": [ "sqs:SendMessage" ], "Effect": "Allow", "Resource": "arn:aws:sqs:*:*:goad-*" }, { "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Effect": "Allow", "Resource": "arn:aws:logs:*:*:*" } ] }`), PolicyName: aws.String("goad-lambda-role-policy"), RoleName: aws.String(roleName), }) return err }
func (infra *Infrastructure) createIAMLambdaRole(roleName string) (arn string, err error) { svc := iam.New(session.New(), infra.config) resp, err := svc.GetRole(&iam.GetRoleInput{ RoleName: aws.String(roleName), }) if err != nil { if awsErr, ok := err.(awserr.Error); ok { if awsErr.Code() == "NoSuchEntity" { res, err := svc.CreateRole(&iam.CreateRoleInput{ AssumeRolePolicyDocument: aws.String(`{ "Version": "2012-10-17", "Statement": { "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole" } }`), RoleName: aws.String(roleName), Path: aws.String("/"), }) if err != nil { return "", err } if err := infra.createIAMLambdaRolePolicy(*res.Role.RoleName); err != nil { return "", err } return *res.Role.Arn, nil } } return "", err } return *resp.Role.Arn, nil }
func main() { flag.Parse() config, err := LoadConfig(configFilePath) if err != nil { log.Fatalf("Error loading config file: %s", err) } logger := buildLogger(config.LogLevel) awsConfig := aws.NewConfig().WithRegion(config.SQSConfig.Region) awsSession := session.New(awsConfig) sqssvc := sqs.New(awsSession) queue := awssqs.NewSQSQueue(sqssvc, logger) iamsvc := iam.New(awsSession) user := awsiam.NewIAMUser(iamsvc, logger) serviceBroker := sqsbroker.New(config.SQSConfig, queue, user, logger) credentials := brokerapi.BrokerCredentials{ Username: config.Username, Password: config.Password, } brokerAPI := brokerapi.New(serviceBroker, logger, credentials) http.Handle("/", brokerAPI) fmt.Println("SQS Service Broker started on port " + port + "...") http.ListenAndServe(":"+port, nil) }
func (u *User) Run(args []string) int { cli := iam.New(session.New(aws.NewConfig().WithRegion(u.config.Region))) u.ListUsers(cli) return 0 }
func teardown() error { creds := credentials.NewStaticCredentials(os.Getenv("AWS_ACCESS_KEY_ID"), os.Getenv("AWS_SECRET_ACCESS_KEY"), "") awsConfig := &aws.Config{ Credentials: creds, Region: aws.String("us-east-1"), HTTPClient: cleanhttp.DefaultClient(), } svc := iam.New(session.New(awsConfig)) attachment := &iam.DetachRolePolicyInput{ PolicyArn: aws.String(testPolicyArn), RoleName: aws.String(testRoleName), // Required } _, err := svc.DetachRolePolicy(attachment) params := &iam.DeleteRoleInput{ RoleName: aws.String(testRoleName), } log.Printf("[INFO] AWS DeleteRole: %s", testRoleName) _, err = svc.DeleteRole(params) if err != nil { log.Printf("[WARN] AWS DeleteRole failed: %v", err) } return err }
func main() { flag.Parse() config, err := LoadConfig(configFilePath) if err != nil { log.Fatalf("Error loading config file: %s", err) } logger := buildLogger(config.LogLevel) awsConfig := aws.NewConfig().WithRegion(config.RDSConfig.Region) awsSession := session.New(awsConfig) iamsvc := iam.New(awsSession) rdssvc := rds.New(awsSession) dbInstance := awsrds.NewRDSDBInstance(config.RDSConfig.Region, iamsvc, rdssvc, logger) dbCluster := awsrds.NewRDSDBCluster(config.RDSConfig.Region, iamsvc, rdssvc, logger) sqlProvider := sqlengine.NewProviderService(logger) serviceBroker := rdsbroker.New(config.RDSConfig, dbInstance, dbCluster, sqlProvider, logger) credentials := brokerapi.BrokerCredentials{ Username: config.Username, Password: config.Password, } brokerAPI := brokerapi.New(serviceBroker, logger, credentials) http.Handle("/", brokerAPI) fmt.Println("RDS Service Broker started on port " + port + "...") http.ListenAndServe(":"+port, nil) }
// AccountID parses an AWS arn string to get the Account ID. func (c *Cred) AccountID() (string, error) { user, err := iam.New(c.session()).GetUser(nil) if err == nil { return parseAccountID(aws.StringValue(user.User.Arn)) } for msg := err.Error(); msg != ""; { i := strings.Index(msg, arnPrefix) if i == -1 { break } msg = msg[i:] accountID, e := parseAccountID(msg) if e != nil { continue } return accountID, nil } return "", err }
func (r *Role) Run(args []string) int { cli := iam.New(session.New(aws.NewConfig().WithRegion(r.config.Region))) r.ListRole(cli) return 0 }
// clientIAM creates a client to interact with AWS IAM API func (b *backend) clientIAM(s logical.Storage, region string) (*iam.IAM, error) { b.configMutex.RLock() if b.IAMClientsMap[region] != nil { defer b.configMutex.RUnlock() // If the client object was already created, return it return b.IAMClientsMap[region], nil } // Release the read lock and acquire the write lock b.configMutex.RUnlock() b.configMutex.Lock() defer b.configMutex.Unlock() // If the client gets created while switching the locks, return it if b.IAMClientsMap[region] != nil { return b.IAMClientsMap[region], nil } // Create an AWS config object using a chain of providers awsConfig, err := b.getClientConfig(s, region) if err != nil { return nil, err } // Create a new IAM client object, cache it and return the same b.IAMClientsMap[region] = iam.New(session.New(awsConfig)) return b.IAMClientsMap[region], nil }
func clientIAM(s logical.Storage) (*iam.IAM, error) { entry, err := s.Get("config/root") if err != nil { return nil, err } if entry == nil { return nil, fmt.Errorf( "root credentials haven't been configured. Please configure\n" + "them at the 'config/root' endpoint") } var config rootConfig if err := entry.DecodeJSON(&config); err != nil { return nil, fmt.Errorf("error reading root configuration: %s", err) } creds := credentials.NewStaticCredentials(config.AccessKey, config.SecretKey, "") awsConfig := &aws.Config{ Credentials: creds, Region: aws.String(config.Region), HTTPClient: cleanhttp.DefaultClient(), } return iam.New(session.New(awsConfig)), nil }
func (r *run) initIamClient() *iam.IAM { var awsconf aws.Config if r.c.AccessKey != "" && r.c.SecretKey != "" { awscreds := awscred.NewStaticCredentials(r.c.AccessKey, r.c.SecretKey, "") awsconf.Credentials = awscreds } return iam.New(session.New(), &awsconf) }
func (r *run) initIamClient() *iam.IAM { awsconf := aws.NewConfig() if r.c.AccessKey != "" && r.c.SecretKey != "" { creds := awscred.NewStaticCredentials(r.c.AccessKey, r.c.SecretKey, "") awsconf = awsconf.WithCredentials(creds) } return iam.New(session.New(), awsconf) }
// see http://stackoverflow.com/a/18124234 func determineAccountIdViaGetUser(sess *session.Session) (string, error) { getUserResp, err := iam.New(sess).GetUser(&iam.GetUserInput{}) if err != nil { return "", err } return getAccountIdFromArn(*getUserResp.User.Arn), nil }
func testDecryptPasswordAndTest(nProfile, nAccessKey, key string) resource.TestCheckFunc { return func(s *terraform.State) error { profileResource, ok := s.RootModule().Resources[nProfile] if !ok { return fmt.Errorf("Not found: %s", nProfile) } password, ok := profileResource.Primary.Attributes["encrypted_password"] if !ok { return errors.New("No password in state") } accessKeyResource, ok := s.RootModule().Resources[nAccessKey] if !ok { return fmt.Errorf("Not found: %s", nAccessKey) } accessKeyId := accessKeyResource.Primary.ID secretAccessKey, ok := accessKeyResource.Primary.Attributes["secret"] if !ok { return errors.New("No secret access key in state") } decryptedPassword, err := pgpkeys.DecryptBytes(password, key) if err != nil { return fmt.Errorf("Error decrypting password: %s", err) } iamAsCreatedUserSession := session.New(&aws.Config{ Region: aws.String("us-west-2"), Credentials: credentials.NewStaticCredentials(accessKeyId, secretAccessKey, ""), }) _, err = iamAsCreatedUserSession.Config.Credentials.Get() if err != nil { return fmt.Errorf("Error getting session credentials: %s", err) } return resource.Retry(2*time.Minute, func() *resource.RetryError { iamAsCreatedUser := iam.New(iamAsCreatedUserSession) _, err = iamAsCreatedUser.ChangePassword(&iam.ChangePasswordInput{ OldPassword: aws.String(decryptedPassword.String()), NewPassword: aws.String(generatePassword(20)), }) if err != nil { if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "InvalidClientTokenId" { return resource.RetryableError(err) } return resource.NonRetryableError(fmt.Errorf("Error changing decrypted password: %s", err)) } return nil }) } }
// 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 }
func determineAccountIdViaListUsers(sess *session.Session) (string, error) { listUsersResp, err := iam.New(sess).ListUsers(&iam.ListUsersInput{}) if err != nil { return "", err } if len(listUsersResp.Users) == 0 { return "", errors.New("No users found") } return getAccountIdFromArn(*listUsersResp.Users[0].Arn), nil }
// findAcccountID returns the AWS account ID func (c *config) findAcccountID() (string, error) { i := iam.New(session.New(), &aws.Config{Region: aws.String(c.src)}) u, err := i.GetUser(nil) if err != nil { return "", err } parts := strings.Split(*u.User.Arn, ":") if len(parts) != 6 { return "", fmt.Errorf("Error parsing user ARN") } return parts[4], nil }
// Verify & cache the IAM rolename to ARN mapping func verifyIAMRoles(ctx *workflowContext) (workflowStep, error) { // The map is either a literal Arn from a pre-existing role name // or a ArbitraryJSONObject{ // "Fn::GetAtt": []string{iamRoleDefinitionName, "Arn"}, // } // Don't verify them, just create them... ctx.logger.Info("Verifying IAM Lambda execution roles") ctx.lambdaIAMRoleNameMap = make(map[string]interface{}, 0) svc := iam.New(ctx.awsSession) for _, eachLambda := range ctx.lambdaAWSInfos { if "" != eachLambda.RoleName && nil != eachLambda.RoleDefinition { return nil, fmt.Errorf("Both RoleName and RoleDefinition defined for lambda: %s", eachLambda.lambdaFnName) } // Get the IAM role name if "" != eachLambda.RoleName { _, exists := ctx.lambdaIAMRoleNameMap[eachLambda.RoleName] if !exists { // Check the role params := &iam.GetRoleInput{ RoleName: aws.String(eachLambda.RoleName), } ctx.logger.Debug("Checking IAM RoleName: ", eachLambda.RoleName) resp, err := svc.GetRole(params) if err != nil { ctx.logger.Error(err.Error()) return nil, err } // Cache it - we'll need it later when we create the // CloudFormation template which needs the execution Arn (not role) ctx.lambdaIAMRoleNameMap[eachLambda.RoleName] = *resp.Role.Arn } } else { logicalName := eachLambda.RoleDefinition.logicalName() _, exists := ctx.lambdaIAMRoleNameMap[logicalName] if !exists { // Insert it into the resource creation map and add // the "Ref" entry to the hashmap ctx.cloudformationResources[logicalName] = eachLambda.RoleDefinition.rolePolicy(eachLambda.EventSourceMappings, ctx.logger) ctx.lambdaIAMRoleNameMap[logicalName] = ArbitraryJSONObject{ "Fn::GetAtt": []string{logicalName, "Arn"}, } } } } ctx.logger.WithFields(logrus.Fields{ "Count": len(ctx.lambdaIAMRoleNameMap), }).Info("IAM roles verified") return createPackageStep(), nil }
func NewAWSCloud(region string, tags map[string]string) (*AWSCloud, error) { c := &AWSCloud{Region: region} config := aws.NewConfig().WithRegion(region) c.EC2 = ec2.New(session.New(), config) c.IAM = iam.New(session.New(), config) c.ELB = elb.New(session.New(), config) c.Autoscaling = autoscaling.New(session.New(), config) c.Route53 = route53.New(session.New(), config) c.tags = tags return c, nil }
func createRole(t *testing.T) { const testRoleAssumePolicy = `{ "Version": "2012-10-17", "Statement": [ { "Effect":"Allow", "Principal": { "AWS": "arn:aws:iam::%s:root" }, "Action": "sts:AssumeRole" } ] } ` creds := credentials.NewStaticCredentials(os.Getenv("AWS_ACCESS_KEY_ID"), os.Getenv("AWS_SECRET_ACCESS_KEY"), "") awsConfig := &aws.Config{ Credentials: creds, Region: aws.String("us-east-1"), HTTPClient: cleanhttp.DefaultClient(), } svc := iam.New(session.New(awsConfig)) trustPolicy := fmt.Sprintf(testRoleAssumePolicy, os.Getenv("AWS_ACCOUNT_ID")) params := &iam.CreateRoleInput{ AssumeRolePolicyDocument: aws.String(trustPolicy), RoleName: aws.String(testRoleName), Path: aws.String("/"), } log.Printf("[INFO] AWS CreateRole: %s", testRoleName) _, err := svc.CreateRole(params) if err != nil { t.Fatal("AWS CreateRole failed: %v", err) } attachment := &iam.AttachRolePolicyInput{ PolicyArn: aws.String(testPolicyArn), RoleName: aws.String(testRoleName), // Required } _, err = svc.AttachRolePolicy(attachment) if err != nil { t.Fatal("AWS CreateRole failed: %v", err) } // Sleep sometime because AWS is eventually consistent log.Println("[WARN] Sleeping for 10 seconds waiting for AWS...") time.Sleep(10 * time.Second) }
func getCommandStruct(conf *config.Config) (*command.Command, int) { // aws Credentials creds, err := conf.GetAWSCreds() if err != nil { log.Errorf("%s", err.Error()) return nil, 1 } // aws config init awsConfig := aws.NewConfig() awsConfig = awsConfig.WithCredentials(creds) awsConfig = awsConfig.WithRegion(conf.Rds[nameFlag].Region) // new iam awsIam := iam.New(awsConfig) // IAM info iamUsers, err := awsIam.ListUsers(&iam.ListUsersInput{}) if err != nil { log.Errorf("%s", err.Error()) return nil, 1 } if len(iamUsers.Users) <= 0 { log.Errorf("iam user not found") return nil, 1 } // edit IAM ARN // arn:aws:iam::<account>:user/<username> to arn:aws:rds:<region>:<account>: // see also // Tagging Amazon RDS Resources - Amazon Relational Database Service // http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Tagging.html#USER_Tagging.ARN iamSplit := strings.SplitAfter(*iamUsers.Users[0].Arn, "::") iamAccount := iamSplit[len(iamSplit)-1] iamSplit = strings.Split(iamAccount, ":") iamAccount = iamSplit[0] // new rds awsRds := rds.New(awsConfig) commandStruct := &command.Command{ OutConfig: conf.Out, RDSConfig: conf.Rds[nameFlag], RDSClient: awsRds, ARNPrefix: "arn:aws:rds:" + conf.Rds[nameFlag].Region + ":" + iamAccount + ":", } log.Debugf("Command: %+v", commandStruct) return commandStruct, 0 }
// GetIAMUsers returns a list of IAM Users that match the provided search term func GetIAMUsers(search string) (*IAMUsers, error) { svc := iam.New(session.New()) result, err := svc.ListUsers(&iam.ListUsersInput{}) // TODO truncated? if err != nil { terminal.ShowErrorMessage("Error gathering IAM Users list", err.Error()) return &IAMUsers{}, err } iamList := make(IAMUsers, len(result.Users)) for i, user := range result.Users { iamList[i].Marshal(user) } return &iamList, nil }
// GetIAMUser returns a single IAM User that matches the provided username func GetIAMUser(username string) (IAMUser, error) { svc := iam.New(session.New()) params := &iam.GetUserInput{ UserName: aws.String(username), } resp, err := svc.GetUser(params) if err != nil { return IAMUser{}, err } user := new(IAMUser) user.Marshal(resp.User) return *user, nil }
// CreateIAMUser creates a new IAM User with the provided username and path func CreateIAMUser(username, path string) error { svc := iam.New(session.New()) params := &iam.CreateUserInput{ UserName: aws.String(username), } if path != "" { params.Path = aws.String(path) } _, err := svc.CreateUser(params) if err == nil { terminal.Information("Done!") } return err }
func New(config Config) (*Client, error) { credentials := credentials.NewStaticCredentials(config.AccessKey, config.SecretKey, "") sdkConfig := &aws.Config{ Credentials: credentials, Region: aws.String(config.RegionName), } session := session.New(sdkConfig) route53EndpointConfig, err := config.getEndpoint("route53") if err != nil { return nil, err } ec2EndpointConfig, err := config.getEndpoint("ec2") if err != nil { return nil, err } s3EndpointConfig, err := config.getEndpoint("s3") if err != nil { return nil, err } cloudformationEndpointConfig, err := config.getEndpoint("cloudformation") if err != nil { return nil, err } iamEndpointConfig, err := config.getEndpoint("iam") if err != nil { return nil, err } return &Client{ Region: config.RegionName, EC2: ec2.New(session, ec2EndpointConfig), S3: s3.New(session, s3EndpointConfig), Route53: route53.New(session, route53EndpointConfig), Cloudformation: cloudformation.New(session, cloudformationEndpointConfig), IAM: iam.New(session, iamEndpointConfig), }, nil }
// Run command. func run(c *cobra.Command, args []string) error { stats.Track("Init", nil) if err := root.Prepare(c, args); err != nil { return err } region := root.Config.Region if region == nil { return errors.New(credentialsError) } b := boot.Bootstrapper{ IAM: iam.New(root.Session), Region: *region, } return b.Boot() }
// 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 }
// GetInstanceIAMRole gets the iam roles attached to the instance profile func GetInstanceIAMRole() (*iam.Role, error) { // This returns the name of the role instanceRoleName, err := GetInstanceMetadata("iam/security-credentials") if err != nil { return nil, fmt.Errorf("Error getting instance role name, err: %v", err) } if utils.ZeroOrNil(instanceRoleName) { return nil, fmt.Errorf("Instance Role name nil") } iamClient := iam.New(session.New()) instanceRole, err := iamClient.GetRole(&iam.GetRoleInput{ RoleName: aws.String(instanceRoleName), }) if err != nil { return nil, err } return instanceRole.Role, nil }