Example #1
1
func (u *User) CreateUser(svc *iam.IAM) error {
	params := &iam.CreateUserInput{
		UserName: aws.String(u.UserName), // Required
		Path:     aws.String("/"),
	}
	_, err := svc.CreateUser(params)

	if err != nil {
		return err
	}

	return nil
}
Example #2
0
// ValidateAccountId returns a context-specific error if the configured account
// id is explicitly forbidden or not authorised; and nil if it is authorised.
func (c *Config) ValidateAccountId(iamconn *iam.IAM) error {
	if c.AllowedAccountIds == nil && c.ForbiddenAccountIds == nil {
		return nil
	}

	log.Printf("[INFO] Validating account ID")

	out, err := iamconn.GetUser(nil)
	if err != nil {
		return fmt.Errorf("Failed getting account ID from IAM: %s", err)
	}

	account_id := strings.Split(*out.User.ARN, ":")[4]

	if c.ForbiddenAccountIds != nil {
		for _, id := range c.ForbiddenAccountIds {
			if id == account_id {
				return fmt.Errorf("Forbidden account ID (%s)", id)
			}
		}
	}

	if c.AllowedAccountIds != nil {
		for _, id := range c.AllowedAccountIds {
			if id == account_id {
				return nil
			}
		}
		return fmt.Errorf("Account ID not allowed (%s)", account_id)
	}

	return nil
}
Example #3
0
func (g *Group) GetGroupPolicy(cli *iam.IAM, groupName, policyName string) {
	//get-group-policy
	req := &iam.GetGroupPolicyInput{
		GroupName:  aws.String(groupName),
		PolicyName: aws.String(policyName),
	}
	resp, err := cli.GetGroupPolicy(req)
	raiseError(err)

	policyDocument := parsePolicyDocument(decodeUri(*resp.PolicyDocument))

	if len(policyDocument.Statement) < 1 {
		fmt.Printf("\"%s\", \"%s\", \"\"\n",
			*resp.GroupName,
			*resp.PolicyName,
		)
	}

	for i := 0; i < len(policyDocument.Statement); i++ {
		if len(policyDocument.Statement[i].Action) < 1 {
			fmt.Printf("\"%s\", \"%s\", \"\"\n",
				*resp.GroupName,
				*resp.PolicyName,
			)
		}
		for j := 0; j < len(policyDocument.Statement[i].Action); j++ {
			fmt.Printf("\"%s\", \"%s\", \"%s\"\n",
				*resp.GroupName,
				*resp.PolicyName,
				policyDocument.Statement[i].Action[j],
			)
		}
	}
}
func instanceProfileAddRole(iamconn *iam.IAM, profileName, roleName string) error {
	request := &iam.AddRoleToInstanceProfileInput{
		InstanceProfileName: aws.String(profileName),
		RoleName:            aws.String(roleName),
	}

	_, err := iamconn.AddRoleToInstanceProfile(request)
	return err
}
Example #5
0
func GetAccountId(iamconn *iam.IAM, stsconn *sts.STS, authProviderName string) (string, error) {
	// If we have creds from instance profile, we can use metadata API
	if authProviderName == ec2rolecreds.ProviderName {
		log.Println("[DEBUG] Trying to get account ID via AWS Metadata API")

		cfg := &aws.Config{}
		setOptionalEndpoint(cfg)
		metadataClient := ec2metadata.New(session.New(cfg))
		info, err := metadataClient.IAMInfo()
		if err != nil {
			// This can be triggered when no IAM Role is assigned
			// or AWS just happens to return invalid response
			return "", fmt.Errorf("Failed getting EC2 IAM info: %s", err)
		}

		return parseAccountIdFromArn(info.InstanceProfileArn)
	}

	// Then try IAM GetUser
	log.Println("[DEBUG] Trying to get account ID via iam:GetUser")
	outUser, err := iamconn.GetUser(nil)
	if err == nil {
		return parseAccountIdFromArn(*outUser.User.Arn)
	}

	awsErr, ok := err.(awserr.Error)
	// AccessDenied and ValidationError can be raised
	// if credentials belong to federated profile, so we ignore these
	if !ok || (awsErr.Code() != "AccessDenied" && awsErr.Code() != "ValidationError") {
		return "", fmt.Errorf("Failed getting account ID via 'iam:GetUser': %s", err)
	}
	log.Printf("[DEBUG] Getting account ID via iam:GetUser failed: %s", err)

	// Then try STS GetCallerIdentity
	log.Println("[DEBUG] Trying to get account ID via sts:GetCallerIdentity")
	outCallerIdentity, err := stsconn.GetCallerIdentity(&sts.GetCallerIdentityInput{})
	if err == nil {
		return *outCallerIdentity.Account, nil
	}
	log.Printf("[DEBUG] Getting account ID via sts:GetCallerIdentity failed: %s", err)

	// Then try IAM ListRoles
	log.Println("[DEBUG] Trying to get account ID via iam:ListRoles")
	outRoles, err := iamconn.ListRoles(&iam.ListRolesInput{
		MaxItems: aws.Int64(int64(1)),
	})
	if err != nil {
		return "", fmt.Errorf("Failed getting account ID via 'iam:ListRoles': %s", err)
	}

	if len(outRoles.Roles) < 1 {
		return "", fmt.Errorf("Failed getting account ID via 'iam:ListRoles': No roles available")
	}

	return parseAccountIdFromArn(*outRoles.Roles[0].Arn)
}
func detachPolicyFromUser(conn *iam.IAM, user string, arn string) error {
	_, err := conn.DetachUserPolicy(&iam.DetachUserPolicyInput{
		UserName:  aws.String(user),
		PolicyArn: aws.String(arn),
	})
	if err != nil {
		return err
	}
	return nil
}
func detachPolicyFromRole(conn *iam.IAM, role string, arn string) error {
	_, err := conn.DetachRolePolicy(&iam.DetachRolePolicyInput{
		RoleName:  aws.String(role),
		PolicyArn: aws.String(arn),
	})
	if err != nil {
		return err
	}
	return nil
}
func detachPolicyFromGroup(conn *iam.IAM, group string, arn string) error {
	_, err := conn.DetachGroupPolicy(&iam.DetachGroupPolicyInput{
		GroupName: aws.String(group),
		PolicyArn: aws.String(arn),
	})
	if err != nil {
		return err
	}
	return nil
}
Example #9
0
// Validate credentials early and fail before we do any graph walking
func (c *Config) ValidateCredentials(iamconn *iam.IAM) error {
	_, err := iamconn.GetUser(nil)

	if awsErr, ok := err.(awserr.Error); ok {
		if awsErr.Code() == "SignatureDoesNotMatch" {
			return fmt.Errorf("Failed authenticating with AWS: please verify credentials")
		}
	}

	return err
}
Example #10
0
func UserAccount(iamsvc *iam.IAM) (string, error) {
	getUserInput := &iam.GetUserInput{}
	getUserOutput, err := iamsvc.GetUser(getUserInput)
	if err != nil {
		return "", err
	}

	userAccount := strings.Split(*getUserOutput.User.Arn, ":")

	return userAccount[4], nil
}
func iamPolicyListVersions(arn string, iamconn *iam.IAM) ([]*iam.PolicyVersion, error) {
	request := &iam.ListPolicyVersionsInput{
		PolicyARN: aws.String(arn),
	}

	response, err := iamconn.ListPolicyVersions(request)
	if err != nil {
		return nil, fmt.Errorf("Error listing versions for IAM policy %s: %s", arn, err)
	}
	return response.Versions, nil
}
func detachPolicyFromUsers(conn *iam.IAM, users []*string, arn string) error {
	for _, u := range users {
		_, err := conn.DetachUserPolicy(&iam.DetachUserPolicyInput{
			UserName:  u,
			PolicyArn: aws.String(arn),
		})
		if err != nil {
			return err
		}
	}
	return nil
}
func iamPolicyDeleteVersion(arn, versionID string, iamconn *iam.IAM) error {
	request := &iam.DeletePolicyVersionInput{
		PolicyARN: aws.String(arn),
		VersionID: aws.String(versionID),
	}

	_, err := iamconn.DeletePolicyVersion(request)
	if err != nil {
		return fmt.Errorf("Error deleting version %s from IAM policy %s: %s", versionID, arn, err)
	}
	return nil
}
func detachPolicyFromRoles(conn *iam.IAM, roles []*string, arn string) error {
	for _, r := range roles {
		_, err := conn.DetachRolePolicy(&iam.DetachRolePolicyInput{
			RoleName:  r,
			PolicyArn: aws.String(arn),
		})
		if err != nil {
			return err
		}
	}
	return nil
}
func detachPolicyFromGroups(conn *iam.IAM, groups []*string, arn string) error {
	for _, g := range groups {
		_, err := conn.DetachGroupPolicy(&iam.DetachGroupPolicyInput{
			GroupName: g,
			PolicyArn: aws.String(arn),
		})
		if err != nil {
			return err
		}
	}
	return nil
}
func instanceProfileRemoveRole(iamconn *iam.IAM, profileName, roleName string) error {
	request := &iam.RemoveRoleFromInstanceProfileInput{
		InstanceProfileName: aws.String(profileName),
		RoleName:            aws.String(roleName),
	}

	_, err := iamconn.RemoveRoleFromInstanceProfile(request)
	if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" {
		return nil
	}
	return err
}
Example #17
0
func (u *User) DeleteLoginProfile(svc *iam.IAM) error {
	params := &iam.DeleteLoginProfileInput{
		UserName: aws.String(u.UserName), // Required
	}
	_, err := svc.DeleteLoginProfile(params)

	if err != nil {
		return err
	}

	return nil
}
func addUsersToGroup(conn *iam.IAM, users []*string, group string) error {
	for _, u := range users {
		_, err := conn.AddUserToGroup(&iam.AddUserToGroupInput{
			UserName:  u,
			GroupName: aws.String(group),
		})

		if err != nil {
			return err
		}
	}
	return nil
}
func removeUsersFromGroup(conn *iam.IAM, users []*string, group string) error {
	for _, u := range users {
		_, err := conn.RemoveUserFromGroup(&iam.RemoveUserFromGroupInput{
			UserName:  u,
			GroupName: aws.String(group),
		})

		if err != nil {
			return err
		}
	}
	return nil
}
Example #20
0
func (u *User) RemoveUserFromGroup(svc *iam.IAM) error {
	params := &iam.RemoveUserFromGroupInput{
		GroupName: aws.String(u.GroupName), // Required
		UserName:  aws.String(u.UserName),  // Required
	}
	_, err := svc.RemoveUserFromGroup(params)

	if err != nil {
		return err
	}

	return nil
}
Example #21
0
// Set the IAM users
func (u userMap) setIamUsers(svc *iam.IAM, g []string) error {
	for _, grp := range g {
		resp, err := svc.GetGroup(&iam.GetGroupInput{GroupName: aws.String(grp)})
		if err != nil {
			log.Error(fmt.Sprintf("Error getting Group: %v, %v", grp, err))
			return err
		}
		for _, user := range sync_iam.GetIamUsers(resp) {
			u[user] = &userData{group: grp}
		}
	}
	return nil
}
Example #22
0
func (u *User) CreateLoginProfile(svc *iam.IAM) error {
	params := &iam.CreateLoginProfileInput{
		UserName:              aws.String(u.UserName),
		Password:              aws.String(u.Password),
		PasswordResetRequired: aws.Bool(true),
	}

	_, err := svc.CreateLoginProfile(params)

	if err != nil {
		return err
	}

	return nil
}
Example #23
0
func (g *Group) ListGroupPolicies(cli *iam.IAM, groupName string) {
	// list-group-policies
	req := &iam.ListGroupPoliciesInput{GroupName: aws.String(groupName)}
	resp, err := cli.ListGroupPolicies(req)
	raiseError(err)

	if len(resp.PolicyNames) < 1 {
		fmt.Println("no policies")
		return
	}

	for i := 0; i < len(resp.PolicyNames); i++ {
		g.GetGroupPolicy(cli, groupName, *resp.PolicyNames[i])
	}
}
Example #24
0
func (g *Group) ListGroup(cli *iam.IAM) {
	req := &iam.ListGroupsInput{}
	resp, err := cli.ListGroups(req)
	raiseError(err)

	if len(resp.Groups) < 1 {
		fmt.Println("groups not found")
		return
	}

	fmt.Println("GroupName, PolicyName, Statement")
	for i := 0; i < len(resp.Groups); i++ {
		g.ListGroupPolicies(cli, *resp.Groups[i].GroupName)
	}
}
Example #25
0
func (i *IAM) ListGroup(cli *iam.IAM) {
	req := &iam.ListGroupsInput{}
	resp, err := cli.ListGroups(req)
	raiseError(err)

	if len(resp.Groups) < 1 {
		fmt.Println("not found")
		return
	}

	for i := 0; i < len(resp.Groups); i++ {
		fmt.Printf("Group[%s]\n",
			*resp.Groups[i].GroupName,
		)
	}
}
func removeUsersFromGroup(conn *iam.IAM, users []*string, group string) error {
	for _, u := range users {
		_, err := conn.RemoveUserFromGroup(&iam.RemoveUserFromGroupInput{
			UserName:  u,
			GroupName: aws.String(group),
		})

		if err != nil {
			if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" {
				return nil
			}
			return err
		}
	}
	return nil
}
Example #27
0
func (i *IAM) ListUsers(cli *iam.IAM) {
	req := &iam.ListUsersInput{}
	resp, err := cli.ListUsers(req)
	raiseError(err)

	if len(resp.Users) < 1 {
		fmt.Println("not found")
		return
	}

	for i := 0; i < len(resp.Users); i++ {
		fmt.Printf("User[%s] %s\n",
			*resp.Users[i].UserId,
			*resp.Users[i].UserName,
		)
	}
}
Example #28
0
func (r *Role) ListRolePolicies(cli *iam.IAM, rolename string) {
	req := &iam.ListRolePoliciesInput{
		RoleName: aws.String(rolename),
	}
	resp, err := cli.ListRolePolicies(req)

	if err != nil {
		panic(err)
	}
	if len(resp.PolicyNames) < 1 {
		fmt.Println("\tnot found")
		return
	}
	for i := 0; i < len(resp.PolicyNames); i++ {
		fmt.Printf("\t%s\n", *resp.PolicyNames[i])
	}
}
func attachPolicyToRoles(conn *iam.IAM, roles []*string, arn string) error {
	for _, r := range roles {
		_, err := conn.AttachRolePolicy(&iam.AttachRolePolicyInput{
			RoleName:  r,
			PolicyArn: aws.String(arn),
		})
		if err != nil {
			return err
		}

		var attachmentErr error
		attachmentErr = resource.Retry(2*time.Minute, func() *resource.RetryError {

			input := iam.ListRolePoliciesInput{
				RoleName: r,
			}

			attachedPolicies, err := conn.ListRolePolicies(&input)
			if err != nil {
				return resource.NonRetryableError(err)
			}

			if len(attachedPolicies.PolicyNames) > 0 {
				var foundPolicy bool
				for _, policyName := range attachedPolicies.PolicyNames {
					if strings.HasSuffix(arn, *policyName) {
						foundPolicy = true
						break
					}
				}

				if !foundPolicy {
					return resource.NonRetryableError(err)
				}
			}

			return nil
		})

		if attachmentErr != nil {
			return attachmentErr
		}
	}
	return nil
}
Example #30
0
// Validate credentials early and fail before we do any graph walking.
// In the case of an IAM role/profile with insuffecient privileges, fail
// silently
func (c *Config) ValidateCredentials(iamconn *iam.IAM) error {
	_, err := iamconn.GetUser(nil)

	if awsErr, ok := err.(awserr.Error); ok {
		if awsErr.Code() == "AccessDenied" || awsErr.Code() == "ValidationError" {
			log.Printf("[WARN] AccessDenied Error with iam.GetUser, assuming IAM role")
			// User may be an IAM instance profile, or otherwise IAM role without the
			// GetUser permissions, so fail silently
			return nil
		}

		if awsErr.Code() == "SignatureDoesNotMatch" {
			return fmt.Errorf("Failed authenticating with AWS: please verify credentials")
		}
	}

	return err
}