Chapter 01: AWS IAM Fundamentals

Haiyue
16min

Chapter 01: AWS IAM Fundamentals

Learning Objectives
  • Understand what AWS IAM is and its core functions
  • Master the basic components and concepts of IAM
  • Learn IAM’s position in AWS security architecture
  • Understand the difference between authentication and authorization

Key Concepts

What is AWS IAM

AWS Identity and Access Management (IAM) is a web service that helps you securely control access to AWS resources. IAM allows you to control who can be authenticated (signed in) and authorized (have permissions) to use resources.

IAM Core Components

🔄 正在渲染 Mermaid 图表...

IAM Component Details

ComponentPurposeCharacteristicsUse Cases
UsersRepresent individuals or applicationsPermanent credentials, long-term accessDevelopers, system administrators
GroupsCollection of usersSimplify permission managementDepartment, team permission management
RolesAssumable identityTemporary credentials, high securityService-to-service calls, cross-account access
PoliciesDocuments defining permissionsJSON format, fine-grained controlPermission definition and management

Authentication vs Authorization

🔄 正在渲染 Mermaid 图表...

Example Code

Basic IAM Concepts Example

import boto3
import json
from datetime import datetime

# Initialize IAM client
iam_client = boto3.client('iam')

def demonstrate_iam_concepts():
    """
    Demonstrate basic IAM concepts and components
    """

    print("=== AWS IAM Fundamentals Demonstration ===")

    # 1. List current account users
    print("\n1. IAM Users in Current Account:")
    try:
        users_response = iam_client.list_users()
        for user in users_response['Users']:
            print(f"   - Username: {user['UserName']}")
            print(f"     Created: {user['CreateDate']}")
            print(f"     ARN: {user['Arn']}")
    except Exception as e:
        print(f"   Failed to get user list: {e}")

    # 2. List user groups
    print("\n2. IAM Groups in Current Account:")
    try:
        groups_response = iam_client.list_groups()
        for group in groups_response['Groups']:
            print(f"   - Group Name: {group['GroupName']}")
            print(f"     Created: {group['CreateDate']}")
            print(f"     ARN: {group['Arn']}")
    except Exception as e:
        print(f"   Failed to get group list: {e}")

    # 3. List roles
    print("\n3. IAM Roles in Current Account:")
    try:
        roles_response = iam_client.list_roles(MaxItems=5)  # Limit display count
        for role in roles_response['Roles']:
            print(f"   - Role Name: {role['RoleName']}")
            print(f"     Created: {role['CreateDate']}")
            print(f"     Description: {role.get('Description', 'No description')}")
    except Exception as e:
        print(f"   Failed to get role list: {e}")

    # 4. List policies (show customer-managed policies only)
    print("\n4. Customer Managed Policies in Current Account:")
    try:
        policies_response = iam_client.list_policies(
            Scope='Local',  # Show only customer-created policies
            MaxItems=5
        )
        for policy in policies_response['Policies']:
            print(f"   - Policy Name: {policy['PolicyName']}")
            print(f"     ARN: {policy['Arn']}")
            print(f"     Description: {policy.get('Description', 'No description')}")
    except Exception as e:
        print(f"   Failed to get policy list: {e}")

def analyze_iam_structure():
    """
    Analyze IAM structure and relationships
    """

    print("\n=== IAM Structure Analysis ===")

    try:
        # Get account summary
        summary = iam_client.get_account_summary()
        summary_map = summary['SummaryMap']

        print("\nAccount IAM Resource Statistics:")
        print(f"   - User Count: {summary_map.get('Users', 0)}")
        print(f"   - Group Count: {summary_map.get('Groups', 0)}")
        print(f"   - Role Count: {summary_map.get('Roles', 0)}")
        print(f"   - Policy Count: {summary_map.get('Policies', 0)}")
        print(f"   - Customer Managed Policies: {summary_map.get('PolicyVersionsInUse', 0)}")

        # Analyze password policy
        try:
            password_policy = iam_client.get_account_password_policy()
            policy = password_policy['PasswordPolicy']

            print("\nAccount Password Policy:")
            print(f"   - Minimum Length: {policy.get('MinimumPasswordLength', 'Not set')}")
            print(f"   - Require Uppercase: {policy.get('RequireUppercaseCharacters', False)}")
            print(f"   - Require Lowercase: {policy.get('RequireLowercaseCharacters', False)}")
            print(f"   - Require Numbers: {policy.get('RequireNumbers', False)}")
            print(f"   - Require Symbols: {policy.get('RequireSymbols', False)}")
            print(f"   - Password Expiration Days: {policy.get('MaxPasswordAge', 'No expiration')}")

        except iam_client.exceptions.NoSuchEntityException:
            print("\nAccount Password Policy: No custom password policy set")

    except Exception as e:
        print(f"Failed to get account summary: {e}")

def demonstrate_policy_evaluation():
    """
    Demonstrate IAM policy evaluation logic
    """

    print("\n=== IAM Policy Evaluation Logic ===")

    # Basic policy evaluation principles
    evaluation_rules = {
        "Default Deny": "By default, all requests are denied",
        "Explicit Allow": "An explicit Allow statement can override the default deny",
        "Explicit Deny": "An explicit Deny statement has the highest priority",
        "Policy Types": "Combined evaluation of identity policies, resource policies, permission boundaries, SCPs, etc."
    }

    print("\nPolicy Evaluation Principles:")
    for rule, description in evaluation_rules.items():
        print(f"   - {rule}: {description}")

    # Simulate policy evaluation process
    print("\nPolicy Evaluation Process:")
    print("   1. Collect all applicable policies")
    print("   2. Check for explicit deny -> If exists, deny immediately")
    print("   3. Check for explicit allow -> If exists, allow")
    print("   4. Default deny -> Deny if no explicit allow")

if __name__ == "__main__":
    # Run demonstration functions
    demonstrate_iam_concepts()
    analyze_iam_structure()
    demonstrate_policy_evaluation()

IAM Permission Checker Tool

import boto3
import json
from botocore.exceptions import ClientError

class IAMPermissionChecker:
    """
    IAM Permission Checker Tool Class
    """

    def __init__(self):
        self.iam_client = boto3.client('iam')
        self.sts_client = boto3.client('sts')

    def check_current_identity(self):
        """
        Check current identity information
        """
        try:
            identity = self.sts_client.get_caller_identity()
            print("Current Identity Information:")
            print(f"   - Account ID: {identity['Account']}")
            print(f"   - User/Role ARN: {identity['Arn']}")
            print(f"   - User ID: {identity['UserId']}")
            return identity
        except Exception as e:
            print(f"Failed to get identity information: {e}")
            return None

    def check_user_permissions(self, username):
        """
        Check specified user's permissions
        """
        print(f"\nChecking permissions for user '{username}':")

        try:
            # Get user information
            user = self.iam_client.get_user(UserName=username)
            print(f"   User ARN: {user['User']['Arn']}")

            # Get directly attached policies
            attached_policies = self.iam_client.list_attached_user_policies(
                UserName=username
            )
            print(f"   Directly Attached Managed Policies: {len(attached_policies['AttachedPolicies'])}")

            for policy in attached_policies['AttachedPolicies']:
                print(f"     - {policy['PolicyName']} ({policy['PolicyArn']})")

            # Get user's inline policies
            inline_policies = self.iam_client.list_user_policies(UserName=username)
            print(f"   Inline Policies: {len(inline_policies['PolicyNames'])}")

            for policy_name in inline_policies['PolicyNames']:
                print(f"     - {policy_name}")

            # Get user's groups
            groups = self.iam_client.get_groups_for_user(UserName=username)
            print(f"   Member of Groups: {len(groups['Groups'])}")

            for group in groups['Groups']:
                print(f"     - {group['GroupName']}")
                self._check_group_permissions(group['GroupName'])

        except ClientError as e:
            if e.response['Error']['Code'] == 'NoSuchEntity':
                print(f"   User '{username}' does not exist")
            else:
                print(f"   Failed to check user permissions: {e}")

    def _check_group_permissions(self, group_name):
        """
        Check group permissions (private method)
        """
        try:
            # Get group's attached policies
            attached_policies = self.iam_client.list_attached_group_policies(
                GroupName=group_name
            )

            if attached_policies['AttachedPolicies']:
                print(f"       Group '{group_name}' Managed Policies:")
                for policy in attached_policies['AttachedPolicies']:
                    print(f"         - {policy['PolicyName']}")

            # Get group's inline policies
            inline_policies = self.iam_client.list_group_policies(GroupName=group_name)
            if inline_policies['PolicyNames']:
                print(f"       Group '{group_name}' Inline Policies:")
                for policy_name in inline_policies['PolicyNames']:
                    print(f"         - {policy_name}")

        except Exception as e:
            print(f"       Failed to check group '{group_name}' permissions: {e}")

    def simulate_policy(self, principal_arn, action_names, resource_arns):
        """
        Simulate policy execution
        """
        print(f"\nSimulating Policy Execution:")
        print(f"   Principal: {principal_arn}")
        print(f"   Actions: {', '.join(action_names)}")
        print(f"   Resources: {', '.join(resource_arns)}")

        try:
            response = self.iam_client.simulate_principal_policy(
                PolicySourceArn=principal_arn,
                ActionNames=action_names,
                ResourceArns=resource_arns
            )

            print(f"\nSimulation Results:")
            for result in response['EvaluationResults']:
                action = result['EvalActionName']
                decision = result['EvalDecision']
                resource = result['EvalResourceName']

                print(f"   Action: {action}")
                print(f"   Resource: {resource}")
                print(f"   Decision: {decision}")

                if 'MatchedStatements' in result:
                    print(f"   Matched Statements: {len(result['MatchedStatements'])}")

                print()

        except Exception as e:
            print(f"   Policy simulation failed: {e}")

# Usage example
if __name__ == "__main__":
    checker = IAMPermissionChecker()

    # Check current identity
    identity = checker.check_current_identity()

    # To check a specific user, uncomment and replace the username
    # checker.check_user_permissions("your-username")

    # Policy simulation example (requires actual ARNs)
    # checker.simulate_policy(
    #     principal_arn="arn:aws:iam::123456789012:user/testuser",
    #     action_names=["s3:GetObject"],
    #     resource_arns=["arn:aws:s3:::my-bucket/*"]
    # )

IAM’s Position in AWS Security Architecture

🔄 正在渲染 Mermaid 图表...

IAM Core Concepts Summary

Main Functions of IAM
  • Centralized Access Control: Unified management of permissions for all AWS resources
  • Fine-Grained Permissions: Can control specific operations on specific resources
  • Temporary Credentials: Provide secure temporary access through roles
  • Federated Identity: Integrate with existing identity systems
  • Audit Trail: Complete access logging
Important Concept Distinctions
  • Users vs Roles: Users have permanent credentials, roles use temporary credentials
  • Managed Policies vs Inline Policies: Managed policies are reusable, inline policies are embedded in specific entities
  • Identity Policies vs Resource Policies: Identity policies attach to identities, resource policies attach to resources
  • Allow vs Deny: Deny always takes precedence over allow

Best Practice Principles

PrincipleDescriptionImplementation Method
Least PrivilegeGrant only the minimum permissions needed to complete tasksRegularly review and clean up permissions
Separation of DutiesAssign different permissions to different rolesCreate specialized roles and groups
Strong AuthenticationUse strong passwords and MFAEnable password policies and MFA
Regular RotationPeriodically change access keysSet up access key rotation policies
Monitoring and AuditingRecord and monitor all access activitiesEnable CloudTrail and CloudWatch
Key Takeaways

IAM is the core foundation of AWS security. Properly understanding and using IAM components is key to building a secure cloud architecture. Mastering the relationships between users, groups, roles, and policies, as well as the difference between authentication and authorization, is the foundation for in-depth IAM learning.