AWS Infra

[ AWS ] S3 특정 확장자 파일만 업로드 하는 버킷정책

Pydole 2023. 1. 13. 14:11

 

 


  CloudFront 서비스를 구축하기 위해 S3 저장소를 원본을 이용하기로 하였다. 압축파일, 이미지과 같은 컨텐츠용만 서비스
 하기 때문에, 버킷정책을 이용하여 필요한 확장자만 업로드할 수 있도록 세팅한다.
   
  보안적으로는 화이트리스트 기반의 업로드 제약조건 세팅이며, 어플리케이션 (Java, Python, .Net ) 에서 사용자에게 오픈
 되어있는 확장자를 제약할 수 있다.

 

 

 


 

S3 버킷 정책 세팅

 

 

특정 확장자만 접근할 수 있도록 허용한다. ( 물론 CloudFront 등 다른 정책도 포함되어 있지만 같이 기술하지 않는다 )

 

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PutObjectDenyPolicy",
            "Effect": "Deny",
            "Principal": "*",
            "Action": "s3:PutObject",
            "NotResource": [
                "arn:aws:s3:::<버킷이름>/*.zip",
                "arn:aws:s3:::<버킷이름>/*.jpg",
                "arn:aws:s3:::<버킷이름>/*.gif",
                "arn:aws:s3:::<버킷이름>/*.png"
            ]
        }
    ]
}

 

 

 


업로드 테스트

 

 

간단한 파이썬 코드로 테스트를 해본다.

 

html은 허용한 확장자가 아니기 때문에, 에러가 발생한다.

 

fileName = 'test.html'

try:
    res = s3.upload_file(fileName, bucket, fileName)
    print('정상 업로드')
    
except Exception as e:
    print(e)

 

 
 Result : 
 
 Failed to upload test.html to 버킷명/test.html: An error occurred (AccessDenied) when calling the PutObject operation: 
 Access Denied

 

 

jpg는 허용한 확장자가 이기 때문에, 정상 업로드 된다.

 

fileName = 'test.jpg'

try:
    res = s3.upload_file(fileName, bucket, fileName)
    print('정상 업로드')
    
except Exception as e:
    print(e)

 

 
 Result : 
 
 정상 업로드