codepipeline-template.yaml [474:687]:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
            Condition:
              StringEquals:
                's3:x-amz-acl': 'bucket-owner-full-control'
          - Sid: AllowSSLRequestsOnly # AWS Foundational Security Best Practices v1.0.0 S3.5
            Effect: Deny
            Principal: '*'
            Action: 's3:*'
            Resource: !Join 
              - ''
              - - !GetAtt 
                  - TrailBucket
                  - Arn
                - /*
            Condition:
              Bool:
                'aws:SecureTransport': false

    ### CloudTrail
    Trail: 
      DependsOn: 
        - TrailBucketPolicy
      Type: AWS::CloudTrail::Trail
      Properties: 
        S3BucketName: 
          Ref: TrailBucket
        IncludeGlobalServiceEvents: true
        IsLogging: true
        IsMultiRegionTrail: true
        EnableLogFileValidation: true
        CloudWatchLogsLogGroupArn: !GetAtt 'TrailLogGroup.Arn'
        CloudWatchLogsRoleArn: !GetAtt 'TrailLogGroupRole.Arn'

    ### CloudTrail LogGroup
    TrailLogGroup:
      Type: 'AWS::Logs::LogGroup'
      Properties:
        RetentionInDays: 90

    ### CloudTrail LogGroup Role
    TrailLogGroupRole:
      Type: 'AWS::IAM::Role'
      Properties:
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
          - Sid: AssumeRole1
            Effect: Allow
            Principal:
              Service: 'cloudtrail.amazonaws.com'
            Action: 'sts:AssumeRole'
        Policies:
        - PolicyName: 'cloudtrail-policy'
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
            - Effect: Allow
              Action:
              - 'logs:CreateLogStream'
              - 'logs:PutLogEvents'
              Resource: !GetAtt 'TrailLogGroup.Arn'
              
    ### Metrics and Alarms to send Cloudtrail notifications on pipeline updates, deletes, and codebuild project creation, deletion
    PipelineStateChangeMetricFiletr:
      Type: 'AWS::Logs::MetricFilter'
      Properties:
          FilterPattern: '{ ($.eventName = "StartPipelineExecution") || ($.eventName = "StopPipelineExecution") || ($.eventName = "UpdatePipeline") || ($.eventName = "DeletePipeline") }'
          LogGroupName: !Ref TrailLogGroup
          MetricTransformations:
              - MetricName: "pipelineEvent"
                MetricNamespace: "CloudTrailMetrics"
                MetricValue: "1"

    PipelineStateChangeAlarm:
      Type: AWS::CloudWatch::Alarm
      Properties:
        AlarmName: !Sub ${AWS::StackName}-CloudTrailPipelineEventChange
        AlarmDescription: "Alarm when cloudtrail receives an state change event from codepipeline"
        MetricName: "pipelineEvent"
        AlarmActions: 
          - !Ref CloudTrailTopic
        ComparisonOperator: "GreaterThanThreshold"
        EvaluationPeriods: 1
        Threshold: 0
        Namespace: "CloudTrailMetrics"
        Statistic: "Sum"
        Period: 1800

    CodeBuildChangeMetricFilter:
      Type: 'AWS::Logs::MetricFilter'
      Properties:
          FilterPattern: '{ (($.eventSource = "codebuild.amazonaws.com") && (($.eventName = "CreateProject") || ($.eventName = "DeleteProject"))) }'
          LogGroupName: !Ref TrailLogGroup
          MetricTransformations:
              - MetricName: "codebuildEvent"
                MetricNamespace: "CloudTrailMetrics"
                MetricValue: "1"

    CodeBuildStateChangeAlarm:
      Type: AWS::CloudWatch::Alarm
      Properties:
        AlarmName: !Sub ${AWS::StackName}-CloudTrailCodebuildEventChange
        AlarmDescription: "Alarm when cloudtrail receives an state change event from codebuild"
        MetricName: "codebuildEvent"
        AlarmActions: 
          - !Ref CloudTrailTopic
        ComparisonOperator: "GreaterThanThreshold"
        EvaluationPeriods: 1
        Threshold: 0
        Namespace: "CloudTrailMetrics"
        Statistic: "Sum"
        Period: 1800

    ### AWS Config rules to record out of complaince scenarios
    AWSConfigRule1:
      Type: 'AWS::Config::ConfigRule'
      Properties:
        ConfigRuleName: !Sub ${AWS::StackName}-codebuild-project-envvar-awscred-check
        Description: >-
          Checks whether the project contains environment variables
          AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. The rule is NON_COMPLIANT
          when the project environment variables contains plaintext credentials.
        InputParameters: {}
        Scope:
          ComplianceResourceTypes:
            - 'AWS::CodeBuild::Project'
        Source:
          Owner: AWS
          SourceIdentifier: CODEBUILD_PROJECT_ENVVAR_AWSCRED_CHECK

    AWSConfigRule2:
      Type: 'AWS::Config::ConfigRule'
      Properties:
        ConfigRuleName: !Sub ${AWS::StackName}-codebuild-project-source-repo-url-check
        Description: >-
          Checks whether the GitHub or Bitbucket source repository URL contains
          either personal access tokens or user name and password. The rule is
          complaint with the usage of OAuth to grant authorization for accessing
          GitHub or Bitbucket repositories.
        InputParameters: {}
        Scope:
          ComplianceResourceTypes:
            - 'AWS::CodeBuild::Project'
        Source:
          Owner: AWS
          SourceIdentifier: CODEBUILD_PROJECT_SOURCE_REPO_URL_CHECK

    AWSConfigRule3:
      Type: 'AWS::Config::ConfigRule'
      Properties:
        ConfigRuleName: !Sub ${AWS::StackName}-cloud-trail-log-file-validation-enabled
        Description: >-
          Checks whether AWS CloudTrail creates a signed digest file with logs.
          AWS recommends that the file validation must be enabled on all trails.
          The rule is noncompliant if the validation is not enabled.
        InputParameters: {}
        Scope: {}
        Source:
          Owner: AWS
          SourceIdentifier: CLOUD_TRAIL_LOG_FILE_VALIDATION_ENABLED

    #### Codepipeline creation 
    AppPipeline:
      Type: 'AWS::CodePipeline::Pipeline'
      Properties:
        Name: !Sub ${AWS::StackName}-pipeline
        RoleArn: !GetAtt 
          - PipelineServiceRole
          - Arn
        Stages:
          - Name: Source
            Actions:
              - Name: SourceAction
                ActionTypeId:
                  Category: Source # Valid categories "Source", "Build", "Test", "Deploy", "Invoke", and "Approval"
                  Owner: AWS  # 3 valid values - AWS, Thirdparty, and custom
                  Version: '1'
                  Provider: CodeCommit # Depends on the Ation Category, various Action Provider options are available. Refer to codepipeline CF template documentation.
                OutputArtifacts:
                  - Name: SourceOutput
                Configuration: # for each action provider, the configuration parameters differ. Refer to codepipeline structure reference documentation. https://docs.aws.amazon.com/codepipeline/latest/userguide/reference-pipeline-structure.html#structure-configuration-examples
                  BranchName: !Ref BranchName
                  RepositoryName: !Ref RepositoryName
                  PollForSourceChanges: false
                RunOrder: 1
          
          ### Build stage for SAST analysis with SonarQube or Phpstan          
          - Name: SCA-and-SAST-Analysis
            Actions:
              - Name: SCAnalysis
                InputArtifacts:
                  - Name: SourceOutput
                ActionTypeId:
                  Category: Test
                  Owner: AWS
                  Version: '1'
                  Provider: CodeBuild
                OutputArtifacts: 
                  - Name: SCAArtifacts
                Configuration:
                  ProjectName: !Ref SCABuildProject
                RunOrder: 2
              - Name: SASTAnalysis
                InputArtifacts:
                  - Name: SourceOutput
                ActionTypeId:
                  Category: Build
                  Owner: AWS
                  Version: '1'
                  Provider: CodeBuild
                OutputArtifacts: 
                  - Name: SASTArtifacts
                Configuration:
                  ProjectName: !Ref SASTBuildProject
                RunOrder: 2
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -



workshop/templates/devsecops-codepipeline.yaml [486:699]:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
            Condition:
              StringEquals:
                's3:x-amz-acl': 'bucket-owner-full-control'
          - Sid: AllowSSLRequestsOnly # AWS Foundational Security Best Practices v1.0.0 S3.5
            Effect: Deny
            Principal: '*'
            Action: 's3:*'
            Resource: !Join 
              - ''
              - - !GetAtt 
                  - TrailBucket
                  - Arn
                - /*
            Condition:
              Bool:
                'aws:SecureTransport': false

    ### CloudTrail
    Trail: 
      DependsOn: 
        - TrailBucketPolicy
      Type: AWS::CloudTrail::Trail
      Properties: 
        S3BucketName: 
          Ref: TrailBucket
        IncludeGlobalServiceEvents: true
        IsLogging: true
        IsMultiRegionTrail: true
        EnableLogFileValidation: true
        CloudWatchLogsLogGroupArn: !GetAtt 'TrailLogGroup.Arn'
        CloudWatchLogsRoleArn: !GetAtt 'TrailLogGroupRole.Arn'

    ### CloudTrail LogGroup
    TrailLogGroup:
      Type: 'AWS::Logs::LogGroup'
      Properties:
        RetentionInDays: 90

    ### CloudTrail LogGroup Role
    TrailLogGroupRole:
      Type: 'AWS::IAM::Role'
      Properties:
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
          - Sid: AssumeRole1
            Effect: Allow
            Principal:
              Service: 'cloudtrail.amazonaws.com'
            Action: 'sts:AssumeRole'
        Policies:
        - PolicyName: 'cloudtrail-policy'
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
            - Effect: Allow
              Action:
              - 'logs:CreateLogStream'
              - 'logs:PutLogEvents'
              Resource: !GetAtt 'TrailLogGroup.Arn'
              
    ### Metrics and Alarms to send Cloudtrail notifications on pipeline updates, deletes, and codebuild project creation, deletion
    PipelineStateChangeMetricFiletr:
      Type: 'AWS::Logs::MetricFilter'
      Properties:
          FilterPattern: '{ ($.eventName = "StartPipelineExecution") || ($.eventName = "StopPipelineExecution") || ($.eventName = "UpdatePipeline") || ($.eventName = "DeletePipeline") }'
          LogGroupName: !Ref TrailLogGroup
          MetricTransformations:
              - MetricName: "pipelineEvent"
                MetricNamespace: "CloudTrailMetrics"
                MetricValue: "1"

    PipelineStateChangeAlarm:
      Type: AWS::CloudWatch::Alarm
      Properties:
        AlarmName: !Sub ${AWS::StackName}-CloudTrailPipelineEventChange
        AlarmDescription: "Alarm when cloudtrail receives an state change event from codepipeline"
        MetricName: "pipelineEvent"
        AlarmActions: 
          - !Ref CloudTrailTopic
        ComparisonOperator: "GreaterThanThreshold"
        EvaluationPeriods: 1
        Threshold: 0
        Namespace: "CloudTrailMetrics"
        Statistic: "Sum"
        Period: 1800

    CodeBuildChangeMetricFilter:
      Type: 'AWS::Logs::MetricFilter'
      Properties:
          FilterPattern: '{ (($.eventSource = "codebuild.amazonaws.com") && (($.eventName = "CreateProject") || ($.eventName = "DeleteProject"))) }'
          LogGroupName: !Ref TrailLogGroup
          MetricTransformations:
              - MetricName: "codebuildEvent"
                MetricNamespace: "CloudTrailMetrics"
                MetricValue: "1"

    CodeBuildStateChangeAlarm:
      Type: AWS::CloudWatch::Alarm
      Properties:
        AlarmName: !Sub ${AWS::StackName}-CloudTrailCodebuildEventChange
        AlarmDescription: "Alarm when cloudtrail receives an state change event from codebuild"
        MetricName: "codebuildEvent"
        AlarmActions: 
          - !Ref CloudTrailTopic
        ComparisonOperator: "GreaterThanThreshold"
        EvaluationPeriods: 1
        Threshold: 0
        Namespace: "CloudTrailMetrics"
        Statistic: "Sum"
        Period: 1800

    ### AWS Config rules to record out of complaince scenarios
    AWSConfigRule1:
      Type: 'AWS::Config::ConfigRule'
      Properties:
        ConfigRuleName: !Sub ${AWS::StackName}-codebuild-project-envvar-awscred-check
        Description: >-
          Checks whether the project contains environment variables
          AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. The rule is NON_COMPLIANT
          when the project environment variables contains plaintext credentials.
        InputParameters: {}
        Scope:
          ComplianceResourceTypes:
            - 'AWS::CodeBuild::Project'
        Source:
          Owner: AWS
          SourceIdentifier: CODEBUILD_PROJECT_ENVVAR_AWSCRED_CHECK

    AWSConfigRule2:
      Type: 'AWS::Config::ConfigRule'
      Properties:
        ConfigRuleName: !Sub ${AWS::StackName}-codebuild-project-source-repo-url-check
        Description: >-
          Checks whether the GitHub or Bitbucket source repository URL contains
          either personal access tokens or user name and password. The rule is
          complaint with the usage of OAuth to grant authorization for accessing
          GitHub or Bitbucket repositories.
        InputParameters: {}
        Scope:
          ComplianceResourceTypes:
            - 'AWS::CodeBuild::Project'
        Source:
          Owner: AWS
          SourceIdentifier: CODEBUILD_PROJECT_SOURCE_REPO_URL_CHECK

    AWSConfigRule3:
      Type: 'AWS::Config::ConfigRule'
      Properties:
        ConfigRuleName: !Sub ${AWS::StackName}-cloud-trail-log-file-validation-enabled
        Description: >-
          Checks whether AWS CloudTrail creates a signed digest file with logs.
          AWS recommends that the file validation must be enabled on all trails.
          The rule is noncompliant if the validation is not enabled.
        InputParameters: {}
        Scope: {}
        Source:
          Owner: AWS
          SourceIdentifier: CLOUD_TRAIL_LOG_FILE_VALIDATION_ENABLED

    #### Codepipeline creation 
    AppPipeline:
      Type: 'AWS::CodePipeline::Pipeline'
      Properties:
        Name: !Sub ${AWS::StackName}-pipeline
        RoleArn: !GetAtt 
          - PipelineServiceRole
          - Arn
        Stages:
          - Name: Source
            Actions:
              - Name: SourceAction
                ActionTypeId:
                  Category: Source # Valid categories "Source", "Build", "Test", "Deploy", "Invoke", and "Approval"
                  Owner: AWS  # 3 valid values - AWS, Thirdparty, and custom
                  Version: '1'
                  Provider: CodeCommit # Depends on the Ation Category, various Action Provider options are available. Refer to codepipeline CF template documentation.
                OutputArtifacts:
                  - Name: SourceOutput
                Configuration: # for each action provider, the configuration parameters differ. Refer to codepipeline structure reference documentation. https://docs.aws.amazon.com/codepipeline/latest/userguide/reference-pipeline-structure.html#structure-configuration-examples
                  BranchName: !Ref BranchName
                  RepositoryName: !Ref RepositoryName
                  PollForSourceChanges: false
                RunOrder: 1
          
          ### Build stage for SAST analysis with SonarQube or Phpstan          
          - Name: SCA-and-SAST-Analysis
            Actions:
              - Name: SCAnalysis
                InputArtifacts:
                  - Name: SourceOutput
                ActionTypeId:
                  Category: Test
                  Owner: AWS
                  Version: '1'
                  Provider: CodeBuild
                OutputArtifacts: 
                  - Name: SCAArtifacts
                Configuration:
                  ProjectName: !Ref SCABuildProject
                RunOrder: 2
              - Name: SASTAnalysis
                InputArtifacts:
                  - Name: SourceOutput
                ActionTypeId:
                  Category: Build
                  Owner: AWS
                  Version: '1'
                  Provider: CodeBuild
                OutputArtifacts: 
                  - Name: SASTArtifacts
                Configuration:
                  ProjectName: !Ref SASTBuildProject
                RunOrder: 2
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -



