Skip to content

Commit

Permalink
Permissions (#123)
Browse files Browse the repository at this point in the history
* Fixed perma for GC07 and GC12

* management account id in csv

* csv

* missing reinvoke perma

---------

Co-authored-by: EC2 Default User <[email protected]>
  • Loading branch information
a-shokri-ssc and EC2 Default User authored Mar 3, 2025
1 parent 43cb426 commit 6fc4639
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 3 deletions.
35 changes: 35 additions & 0 deletions arch/lza_extensions/customizations/GCGuardrailsRoles.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,41 @@ Resources:
Roles:
- Ref: GCLambdaExecutionRole

# OpenSearch Access
GCLambdaExecutionRoleOpenSearchPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AllowOpenSearchAccess
Action:
- "es:Desc*"
Resource:
- "*"
Effect: Allow
PolicyName: !Sub "${OrganizationName}GCLambdaExecutionRoleOpenSearchPolicy"
Roles:
- !Ref GCLambdaExecutionRole2


# MarketPlace Access
GCLambdaExecutionRoleMarketPlacePolicy:
Type: AWS::IAM::Policy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AllowMarketPlaceAccess
Action:
- "aws-marketplace:Li*"
Resource:
- "*"
Effect: Allow
PolicyName: !Sub "${OrganizationName}GCLambdaExecutionRoleMarketPlacePolicy"
Roles:
- !Ref GCLambdaExecutionRole2

# IAM Access
GCLambdaExecutionRoleCloudFrontPolicy:
Type: AWS::IAM::Policy
Expand Down
4 changes: 3 additions & 1 deletion arch/templates/EvidenceCollectionComponents.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,8 @@ Resources:
- Effect: Allow
Action:
- organizations:ListTagsForResource
- organizations:Des*
- lambda:In*
Resource: "*"
- PolicyName: S3Policy
PolicyDocument:
Expand Down Expand Up @@ -268,7 +270,7 @@ Resources:
- !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${OrganizationName}gc*"
Effect: Allow

## Create schedule
## Create schedule.
CronjobsScheduledRule:
Condition: IsAuditAccount
Type: AWS::Events::Rule
Expand Down
33 changes: 33 additions & 0 deletions arch/templates/main.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,39 @@ Resources:
Runtime: !Ref PythonRuntime
Timeout: 90

# OpenSearch Access
GCLambdaExecutionRoleOpenSearchPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AllowOpenSearchAccess
Action:
- "es:Desc*"
Resource:
- "*"
Effect: Allow
PolicyName: !Sub "${OrganizationName}GCLambdaExecutionRoleOpenSearchPolicy"
Roles:
- !Ref GCLambdaExecutionRole2

# MarketPlace Access
GCLambdaExecutionRoleMarketPlacePolicy:
Type: AWS::IAM::Policy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AllowMarketPlaceAccess
Action:
- "aws-marketplace:Li*"
Resource:
- "*"
Effect: Allow
PolicyName: !Sub "${OrganizationName}GCLambdaExecutionRoleMarketPlacePolicy"
Roles:
- !Ref GCLambdaExecutionRole2
GenerateEvidenceBucketName:
Type: Custom::GenerateEvidenceBucketName
Condition: GenerateEvidenceBucketName
Expand Down
21 changes: 19 additions & 2 deletions src/lambda/aws_compile_audit_report/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import time
import uuid
import concurrent.futures
import botocore.exceptions

import boto3
from botocore.exceptions import BotoCoreError, ClientError
Expand Down Expand Up @@ -54,10 +55,26 @@ def create_boto3_clients():
"organizations": get_client("organizations", assume_role=False)
}


# MAIN LAMBDA HANDLER
def lambda_handler(event, context):
logger.info("Lambda invocation started (structured).")
clients = create_boto3_clients()
# Initialize AWS Organizations client
org_client = boto3.client("organizations")

# Fetch Management Account ID
def get_management_account_id():
try:
response = org_client.describe_organization()
return response["Organization"]["MasterAccountId"] # Older accounts use "MasterAccountId"
except Exception as e:
print(f"Error fetching management account ID: {e}")
return "unknown"

# Retrieve Management Account ID
global management_account_id
management_account_id = get_management_account_id()

# Handle concurrency limit
current_concurrency = event.get("current_concurrency", 1)
Expand Down Expand Up @@ -439,7 +456,7 @@ def finalize_and_cleanup_if_necessary(temp_dir, state, s3_client):
logger.info("State is finished. Merging partial CSV files.")
merged_csv = merge_chunk_files(state["chunks_written"], temp_dir)
if merged_csv:
final_key = f'{datetime.datetime.now(tz=datetime.timezone.utc).strftime(config["DATE_FORMAT"])}.csv'
final_key = f'{management_account_id}_{datetime.datetime.now(tz=datetime.timezone.utc).strftime(config["DATE_FORMAT"])}.csv'
try:
with open(merged_csv, "rb") as f:
safe_aws_call(
Expand Down Expand Up @@ -487,7 +504,7 @@ def merge_chunk_files(chunk_files, temp_dir):
return merged_path

def cleanup_temp_directory(temp_dir):
"""Remove the entire temporary directory."""
"""Remove the entire temporary directory.."""
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
logger.info("Cleaned up temp directory: %s", temp_dir)

0 comments on commit 6fc4639

Please sign in to comment.