More Related Content Similar to AWS Builders - Industry Edition: DevSecOps, Application Security Enforcement (20) More from Amazon Web Services Korea (20) AWS Builders - Industry Edition: DevSecOps, Application Security Enforcement2. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
모든 것을 안전하게
3. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
2020 보안 사고 원인
Verizon 2020 데이터 침해 조사 리포트:
https://enterprise.verizon.com/resources/reports/2020-data-breach-investigations-report.pdf
4. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS 보안 공동 책임 모델
Shared responsibility Model
5. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Permissions management
6. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• AWS 사용자 및 그룹을 생성 및 관리하고 권한을 사용하여 AWS 리소스에 대한 접근을
허용 및 거부
• SAML 자격증명 연동 및 AWS Directory Service (AD Connector)를 사용하여
Microsoft Active Directory와 통합
• 엔티티 또는 AWS 서비스 (예: EC2 인스턴스)에서 수행할 수 있는 작업을 제어하기 위한
역할을 생성하고 연결
AWS Identity & Access Management
7. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• AWS 사용자 및 그룹을 생성 및 관리하고 권한을 사용하여 AWS 리소스에 대한 접근을
허용 및 거부
• SAML 자격증명 연동 및 AWS Directory Service (AD Connector)를 사용하여
Microsoft Active Directory와 통합
• 엔티티 또는 AWS 서비스 (예: EC2 인스턴스)에서 수행할 수 있는 작업을 제어하기 위한
역할을 생성하고 연결
AWS Identity & Access Management
8. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• AWS와 상호 작용
IAM과 API 호출
AWS
서비스 API
엔드포인트
AWS SDK
AWS CLI
또 다른
AWS 서비스
AWS
Management
Console
API 인터페이스
9. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• API 요청 흐름
IAM과 API 호출
HTTP/HTTPS
클라이언트
API 인터페이스
IAM
AWS
CloudTrail
AWS 서비스
API 엔드포인트
API 요청
10. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• API 요청 흐름
IAM과 API 호출
HTTP/HTTPS
클라이언트
API 인터페이스
IAM
AWS
CloudTrail
AWS 서비스
API 엔드포인트
API 요청
자격증명 필요!
(Credentials)
11. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS에서 인증이 작동하는 방식
Caller IAM role
AWS service, e.g.,
Amazon Simple Storage
Service (Amazon S3)
AWS Management
Console
AWS Command Line
Interface
AWS Tools and SDKs
via
12. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS 엔터프라이즈 환경의 IAM
AWS Cloud
Account Account Account
Account
13. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Account A(111122223333) Account B(444455556666)
Caller IAM role
Caller IAM policy
Target Amazon S3 bucket
“other-account-bucket”
AWS 다른 계정으로 작업
14. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Account A(111122223333) Account B(444455556666)
Caller IAM role
Caller IAM policy
Target Amazon S3 bucket
“other-account-bucket”
Amazon S3
bucket policy
AWS 다른 계정으로 작업(리소스 기반 정책)
15. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Account A(111122223333) Account B(444455556666)
Caller IAM role
Target Amazon DynamoDB table
“MyTable”
AWS 다른 계정으로 작업
16. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Account A(111122223333) Account B(444455556666)
Caller IAM role Target Amazon
DynamoDB table
“MyTable”
Cross-account
access IAM role
AWS 다른 계정으로 작업
17. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Account A(111122223333) Account B(444455556666)
Caller IAM role Target Amazon
DynamoDB table
“MyTable”
Cross-account
access IAM role
AWS 다른 계정으로 작업
18. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Account A(111122223333) Account B(444455556666)
Caller IAM role Target Amazon
DynamoDB table
“MyTable”
Cross-account
access IAM role
AWS 다른 계정으로 작업(AssumeRole)
19. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• aws configure 파일 설정
• AWS CLI 명령이 호출되는지 확인 후 IAM 사용자 액세스를 확인합니다.
• aws sts get-caller-identity
CLI 를 이용하여 다른 계정으로 작업
{
"UserId": "AIDXXXXXXXXXXXXXX",
"Account": ”0123456789012",
"Arn": "arn:aws:iam::01234567890:user/Bob"
}
[default]
aws_access_key_id={YOUR_ACCESS_KEY_ID}
aws_secret_access_key={YOUR_SECRET_ACCESS_KEY}
[dev]
aws_access_key_id={YOUR_ACCESS_KEY_ID}
aws_secret_access_key={YOUR_SECRET_ACCESS_KEY}
20. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
21. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• IAM 정책 생성
• IAM 역할의 신뢰 관계를 정의
CLI 를 이용하여 다른 계정으로 작업
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::123456789012:root" },
"Action": "sts:AssumeRole" }
}
{
"Version": "2012-10-17",
"Statement": [ {
"Effect": "Allow",
"Action": [ "ec2:Describe*", "iam:ListRoles", "sts:AssumeRole" ],
"Resource": "*" } ]
}
22. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 다음 명령을 실행하여 IAM 역할을 위임합니다.
• aws sts assume-role --role-arn "arn:aws:iam::020251214532:role/sts-s3-read" --rol
e-session-name AWSCLI-Session
CLI 를 이용하여 다른 계정으로 작업
{
"Credentials": {
"AccessKeyId": "ASIAQXXXXXXXXXXX",
"SecretAccessKey": "BtplfN0KXXxxxXXxxxXXXXxXXXxxXXxXX",
"SessionToken": "IQoJb3J…//////////………MqxKUsPN55KtalpyVfnjSsTii7D8sqap5cipN4V25
bOsojU",
"Expiration": "2021-06-08T13:03:06+00:00"
},
"AssumedRoleUser": {
"AssumedRoleId": "AROAXXXXXXXXXXXXXXXX:AWSCLI-Session",
"Arn": "arn:aws:sts::123456789012:assumed-role/rolename/AWSCLI-Session"
}
}
23. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• IAM 역할을 위임하도록 세 가지 환경 변수를 생성합니다.
• 다음 명령을 실행하여 IAM 역할을 위임하는지 확인합니다.
• aws sts get-caller-identity
CLI 를 이용하여 다른 계정으로 작업
export AWS_ACCESS_KEY_ID=RoleAccessKeyID
export AWS_SECRET_ACCESS_KEY=RoleSecretKey
export AWS_SESSION_TOKEN=RoleSessionToken
{
"UserId": "AROXXXXXXXXXX:AWSCLI-Session",
"Account": ”123456789012",
"Arn": "arn:aws:sts::123456789012:assumed-role/userxxx/AWSCLI-Session"
}
24. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 다른 계정에 작업을 확인합니다.
• IAM 사용자로 돌아가려면 환경 변수를 제거합니다.
CLI 를 이용하여 다른 계정으로 작업
aws ec2 describe-instances --query "Reservations[*].Instances[*].[VpcId, InstanceId, ImageId, Inst
anceType]"
aws rds describe-db-instances --query "DBInstances[*].[DBInstanceIdentifier, DBName, DBInstan
ceStatus, AvailabilityZone, DBInstanceClass]"
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
aws sts get-caller-identity
25. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• IDE에서 실행중인 경우 AWS Toolkit 설정에 자격증명을 추가합니다.
• AWS 콘솔을 사용하는 경우 이미 IAM 사용자로 로그인했을 것입니다
• Amazon Cognito는 모바일 및 웹 앱과 같은 신뢰할 수 없는 환경에 제한된 임시 자격증명을
제공합니다
• 개발 컴퓨터 또는 AWS에서 코드가 실행중이고 SDK를 사용한다면 여러 단계에 걸쳐서
조회 프로세스가 이어집니다
어떻게 사용자/애플리케이션이 인증되나요?
26. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• aws configure 파일 설정
다중 계정 작업을 위한 설정
[default]
aws_access_key_id={YOUR_ACCESS_KEY_ID}
aws_secret_access_key={YOUR_SECRET_ACCESS_KEY}
[dev]
aws_access_key_id={YOUR_ACCESS_KEY_ID}
aws_secret_access_key={YOUR_SECRET_ACCESS_KEY}
27. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
JAVA
28. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Amazon Web Services에 요청하려면 AWS 자격 증명을 AWS SDK for Java에 제공해야 합
니다.
• 기본 자격 증명 공급자 체인(권장)을 사용합니다.
• 특정 자격 증명 공급자 또는 공급자 체인을 사용합니다(또는 직접 생성).
• 자체적으로 자격 증명을 제공합니다. 이러한 자격 증명은 루트 계정 자격 증명, IAM 자
격 증명 또는 AWS STS에서 가져온 임시 자격 증명일 수 있습니다.
AWS SDK for Java
29. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
기본 자격증명 공급자 체인(JAVA)
01
Java system properties – aws.accessKeyId and aws.secretKey. The AWS SDK for Java uses
the SystemPropertiesCredentialsProvider to load these credentials.
02
The default credential profiles file – typically located at ~/.aws/credentials (location can
vary per platform), and shared by many of the AWS SDKs and by the AWS CLI.
The AWS SDK for Java uses the ProfileCredentialsProvider to load these credentials.
03
Environment variables – AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
The AWS SDK for Java uses the EnvironmentVariableCredentialsProvider class to load these
credentials.
Amazon ECS container credentials – loaded from the Amazon ECS if the environment
variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set.
The AWS SDK for Java uses the ContainerCredentialsProvider to load these credentials.
04
Instance profile credentials – used on EC2 instances, and delivered through the Amazon EC2
metadata service. The AWS SDK for Java uses the InstanceProfileCredentialsProvider to load
these credentials.
05
30. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 자격 증명을 설정한 후에 사용
기본 자격 증명 공급자 체인을 사용(Java)
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(Regions.AP_NORTHEAST_2)
.build();
31. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• EnvironmentVariableCredentialsProvider 사용
자격 증명 공급자 또는 공급자 체인 지정(Java)
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new EnvironmentVariableCredentialsProvider())
.build();
32. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• BasicAWSCredentials 사용
명시적으로 자격 증명 지정(Java)
BasicAWSCredentials awsCreds = new BasicAWSCredentials("access_key_id", "secret_key_id");
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
33. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• AWS Security Token 서비스(STS) 사용
임시 자격 증명을 사용하는 경우(Java)
AWSSecurityTokenService securityTokenService = AWSSecurityTokenServiceClientBuilder.standard()
.withRegion(stsRegion)
.build();
AWSCredentials awsCredentials = new STSAssumeRoleSessionCredentialsProvider.Builder(assumeRole,
roleSessionName)
.withStsClient(securityTokenService)
.build();
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(AWSSTSCredentialsProvider.getSTSAssumeRoleSessionCredentialsPro
vider(clientRegion, roleARN, roleSessionName))
.withRegion(clientRegion)
.build();
34. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Python
35. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Boto3
• Python 용 AWS SDK (Boto3)를 사용하여 Amazon과 같은 AWS 서비스를 생성, 구성 및 관
리합니다.
• SDK는 AWS 서비스에 대한 낮은 수준의 액세스와 객체 지향 API를 제공합니다.
Python
36. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Passing credentials as parameters in the boto.client() method
• Passing credentials as parameters when creating a Session object
• Environment variables
• Shared credential file (~/.aws/credentials)
• AWS config file (~/.aws/config)
• Assume Role provider
• Instance metadata service on an Amazon EC2 instance that has an IAM role configured.
• https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#
configuring-credentials
기본 자격증명 공급자 체인(Python)
37. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 기본 Role
• Profile 지정
Amazon EC2 인스턴스의 IAM 역할
import boto3
session = boto3.Session(region_name=‘ap-northeast-2’)
dev_s3_client = session.client('s3')
import boto3
session = boto3.Session(profile_name=’dev’, region_name=‘ap-northeast-2’)
dev_s3_client = session.client('s3')
38. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Client
• Session
자격 증명을 매개 변수로 전달
import boto3
client = boto3.client(
's3’,
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
aws_session_token=SESSION_TOKEN
)
import boto3
session = boto3.Session(
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
aws_session_token=SESSION_TOKEN
)
39. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• RoleArn, RoleSession 및 임시 자격증명을 이용하여 새로운 세션 연결
임시 자격증명
session = boto3.Session(profile_name=’dev’)
assumed_role = sts_client.assume.role(
RoleArn=“arn:aws:iam::…….:role/……”,
RoleSessionName=“……”
}
credentials=assumed_role[‘Credentials’]
sts_new_session=boto3.Session(
aws_access_key_id=credentials[‘AccessKeyId’],
aws_secret_access_key=credentials[‘SercretAccessKey’],
aws_session_token=credentials[‘SessionToken’]
)
sts_s3_client = sts_new_session.client('s3')
40. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
모바일
41. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
모바일 애플리케이션에서의 자격 증명 사용
Standard Tokens
Web and Mobile
Apps
Amazon
Cognito
Managed User Directory
Hosted UI
Federation
AWS Credentials
42. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
모바일 애플리케이션에서 Cognito 사용 방법
UI 및
OAuth 구현
AWS Amplify 직접 API 통합
43. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
44. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
추가 작업
45. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 자격 증명 정규식
• Access Key ID 검색 : (? <! [A-Z0-9]) [A-Z0-9] {20} (?! [A-Z0-9])
• Secret Access Key 검색 : (? <! [A-Za-z0-9 / + =]) [A-Za-z0-9 / + =] {40} (?! [A-Za-z0-9
/ + =])
• grep을 이용하여 코드에서 하드 코딩된 자격증명 검색
• grep -RP '(? <! [A-Z0-9]) [A-Z0-9] {20} (?! [A-Z0-9])’*
• grep -RP '(? <! [A-Za-z0-9 / + =]) [A-Za-z0-9 / + =] {40} (?! [A-Za-z0-9 / + = ]) ‘*
기존 코드에서 하드 코딩된 자격증명을 찾아보세요
46. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• AWSFraud 팀 + Github
자격증명이 Github 에 Commit 되었다면?
47. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• AWS Labs의 오픈 소스 git-secrets 도구를 사용
• Git-secrets는 Git 소스 리포지토리를 스캔하고 사용자 암호와 같은 민감한 정보를 포함 할
수 있거나 다른 보안 문제가 있는 코드를 찾습니다.
• Git-secret : https://github.com/awslabs/git-secrets
Git-Secrets
48. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Data encryption
49. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 데이터 암호화에 사용하는 암호화 키를 쉽게 생성/보관/관리해주는 관리형 서비스
• 서버측 / 클라이언트 측 암호화를 지원
• 중앙 집중 암호화 키 관리 :
KMS(Key Management Service)이란?
EBS S3 Redshift
AWS
SDK
AWS CloudTrail
Customer
master key
S3
bucket
EBS
volume
RDS
instance
CMK
Data key Data key Data key
Key Management Service
50. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Customer Master Keys (CMKs)
• 데이터 키를 생성 및 암호화
• 고유한 ARN
• AWS KMS 인프라를 벗어나지 않음
• HSM 에서 생성되거나 고객에 의해 import
• Region specific, globally unique
Data Keys
• 데이터 암호화
• AWS KMS 인프라 내에서 생성
• CMK에 의해 보호됨
• 암호화 되지 않은 상태로 영구 스토리지에 보관하지 말 것 !
Customer Master Keys 와 Data Keys
51. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 2계층 키 구조와 봉투 암호화
• 데이터를 암호화하는데 사용되는 데이터 키
• 고객 마스터 키(CMK)를 통해 데이터 키를
암호화
• CMK 정책으로 데이터에 대한 접근 제어
• 장점
• 데이터 키의 변조 위험 감소
• 대용량 데이터 암호화에 대한 성능 향상
• 수백만 데이터 키들보다 훨씬 적은 수의 마
스터 키를 집중 관리하는게 효율적
• 키 관련 행위에 대한 중앙 집중식 접근관리
와 감사 (CloudTrail
KMS의 봉투 암호화
Encrypted
Data Key
Encrypted
Data
Plaintext Data
Encrypted
Message
Key Encryption
Key (CMK)
Plaintext Data Key Encryption
Algorithm
Encryption
Algorithm
52. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
서버 측 암호화(Server-Side Encryption)
• AWS가 전송된 데이터에 대해 고객 대신 서버 측에서 암호화 작업 수행
• 총 34 개 서비스 연동 : Amazon S3, Amazon EBS, Amazon RDS,
Amazon Redshift, Amazon WorkSpaces, Amazon Kinesis Streams,
AWS CloudTrail…
• 고객 관리 통제 하에 AWS KMS에 암호화 키 보관
클라이언트 측 암호화(Client-Side Encryption)
• 데이터를 전송하기 전에 암호화 수행
• 고객이 직접 암호화 키를 마련하고 직접 관리하거나, AWS
KMS/CloudHSM내에 보관 관리
• 도구들: AWS Encryption SDK, S3 Encryption Client, EMRFS Client,
DynamoDB Encryption Client
AWS 상에서 암호화를 적용하는 2가지 타입
53. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
서버 측 암호화
Client-side
Server-side
Request
KMS
②
③
+
④
CMK
Data key Data key
Data key Data key
Plaintext
data key
Encrypted
data key
①
Encryption
Algorithm
Data key Data key
Plaintext
data key
Encrypted
data key
⑤
Data key
Plaintext
data key
Removed from m
emory
+ +
X
Encryption
Algorithm
Encrypted
data
+
Stored in S3
54. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
클라이언트 측 암호화
Client-side
Server-side
Application
Master Key Provider
(Keyring)
②
③
+
CMK
Data key
Data key
Plaintext
data key
Encrypted
data key
①
AWS Encryption
SDK
Encryption
Algorithm
Data key
Plaintext
data key
+ +
Encryption
Algorithm
Encrypted
data
Data key
Encrypted
data key
+
S3
Encrypted
data
Metadata
Data key Data key
On-prem
HSM
AWS CloudHSM
AWS KMS
55. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 암호화를 위한 데이터 형식과 APIs
• AWS KMS 봉투 암호화에 대한 간단한 인터페이스
• 오픈소스, Apache 2.0 라이선스에 따라 무료 제공
• 지원하는 언어:
• AWS Encryption SDK for Java
• AWS Encryption SDK for Python
• AWS Encryption SDK for C
• AWS Encryption SDK for JavaScript
• 브라우저에서 JavaScript 용 AWS 암호화 SDK 및 Node.js 용 AWS 암호화 SDK
• 암호화 모범 사례에 따른 기본 구현
• 마스터 키를 사용하여 데이터 키를 보호하기 위한 프레임워크
• 암호화된 데이터와 함께 암호화된 데이터 키를 저장하는 형식 메시지
AWS 암호화 SDK
56. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
public static void main(String[] args) {
byte[] myData = "Hello World!".getBytes(StandardCharsets.UTF_8);
KmsMasterKeyProvider masterKeyProvider = KmsMasterKeyProvider.builder()
.withKeysForEncryption(keyArn).build();
Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleCont
extValue");
byte[] ciphertext = new AwsCrypto()
.encryptData(mkp, myData, encryptionContext).getResult();
byte[] plaintext = new AwsCrypto()
.decryptData(mkp, ciphertext).getResult();
System.out.println(new String(myData, StandardCharsets.UTF_8));
}
The AWS Encryption SDK (Java)
57. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
import aws_encryption_sdk
def cycle_string(key_arn, source_plaintext, botocore_session=None):
plaintext = "Hello World!”
kms_kwargs = dict(key_ids=[key_arn])
mkp = aws_encryption_sdk.KMSMasterKeyProvider(**kms_kwargs)
encryption_context = {"data_type": "example", "classification": "public"}
ciphertext, encryptor_header = aws_encryption_sdk.encrypt(
source=plaintext, key_provider=mkp, encryption_context=encryption_context
)
decrypted_plaintext, decryptor_header = aws_encryption_sdk.decrypt(
source=ciphertext, key_provider=mkp
)
print(decrypted_plaintext.decode("utf-8"))
The AWS Encryption SDK (Python)
58. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
async function encryptThis() {
const text = 'Hello World!’
const keyring = new KmsKeyringNode({ generatorKeyId: 'alias/myExampleKey' })
const context = {
dataType: 'example',
classification: 'public',
}
const { ciphertext } = await encrypt(keyring, text, { context })
const { plaintext, messageHeader } = await decrypt(keyring, ciphertext)
console.log(plaintext.toString('utf8))
}
The AWS Encryption SDK (JavaScript)
59. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 성능 향상 및 비용 절감할 수 있습니다.
• 데이터 키를 재사용할 수 있습니다.
• 애플리케이션이 확장 될 때 서비스 한도 내에서 유지하도록 도와줍니다.
데이터 키 캐싱
60. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
키 캐싱 – 안하는 경우
61. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
키 캐싱 – 하는 경우
62. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 데이터 키 캐싱
데이터 키 캐싱 설정 (Python)
# Max entry age is required.
# Max messages (and max bytes) per entry are optional
caching_cmm = CachingCryptoMaterialsManager(
cache=LocalCryptoMaterialsCache(capacity=100),
max_age=60.0 * 5.0, # Five minutes
max_bytes_encrypted=1024 * 1024 * 1024, # 1GiB
max_messages_encrypted=100,
master_key_provider=mkp
)
data = b'Hello World!'
ciphertext, _header = aws_encryption_sdk.encrypt(
source=data,
materials_manager=caching_cmm
)
63. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
코드에서 데이터를 분리
64. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS Systems Manager - Parameter Store
65. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 관리할 서버가 없는 안전하고 확장 가능한 호스팅 보안 암호 관리 서비스를 사용
• 코드에서 데이터를 분리하여 보안 상태를 개선
• 구성 데이터 및 보안 문자열을 계층으로 저장하고 버전을 추적
• 세분화된 수준에서 액세스 제어 및 감사
AWS 시스템 관리자 Parameter Store
AWS Systems Manager
Systems Manager는
대규모 리소스를 안전하게
관리하고 운영하는데
도움이 됩니다.
66. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 파라미터
• DB connection string
• Password
• License key
• 유형
• 문자열
• 문자열 목록
• 보안 문자열
Parameter Store 파라미터 설정
67. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 파라미터 티어 : 표준 파라미터 / 고급 파라미터
• 표준 매개 변수
• 매개 변수 정책에 대한 지원 없음
• 리전별로 계정 당 최대 10,000 개의 매개 변수 허용
• 매개 변수 값의 최대 크기 : 4KB
• 추가 비용 없음
• 고급 매개 변수
• 매개 변수 정책 지원
• 지역별 계정 당 최대 100,000 개의 매개 변수 허용
• 매개 변수 값의 최대 크기 : 8KB
• 추가 비용
Parameter Store 파라미터 설정
68. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Java v1
Parameter Store 사용
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement;
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagementClientBuilder;
import com.amazonaws.services.simplesystemsmanagement.model.DescribeParametersRequest;
import com.amazonaws.services.simplesystemsmanagement.model.DescribeParametersResult;
import com.amazonaws.services.simplesystemsmanagement.model.ParameterMetadata;
public class GetSimpleSystemsManagementParas {
public static void main(String[] args) {
AWSSimpleSystemsManagement ssm = AWSSimpleSystemsManagementClientBuilder.standard().withRegion(Regions.AP_NORTHEAST_2).b
uild();
try {
DescribeParametersRequest desRequest = new DescribeParametersRequest();
desRequest.setMaxResults(10);
DescribeParametersResult results = ssm.describeParameters(desRequest);
List<ParameterMetadata> params = results.getParameters();
//Iterate through the list
Iterator<ParameterMetadata> tagIterator = params.iterator();
while(tagIterator.hasNext()) {
ParameterMetadata paraMeta = (ParameterMetadata)tagIterator.next();
System.out.println(paraMeta.getName());
System.out.println(paraMeta.getDescription());
}
} catch (AmazonServiceException e) {
e.getStackTrace();
}
}
}
69. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Java v2
Parameter Store 사용
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.GetParameterRequest;
import software.amazon.awssdk.services.ssm.model.GetParameterResponse;
import software.amazon.awssdk.services.ssm.model.SsmException;
public class GetParameter {
public static void main(String[] args) {
String paraName = "/prod/test";
Region region = Region.AP_NORTHEAST_2;
SsmClient ssmClient = SsmClient.builder().region(region).build();
try {
GetParameterRequest parameterRequest = GetParameterRequest.builder().name(paraName).build();
GetParameterResponse parameterResponse = ssmClient.getParameter(parameterRequest);
System.out.println("The parameter value is " + parameterResponse.parameter().value());
} catch (SsmException e) {
System.err.println(e.getMessage());
}
ssmClient.close();
}
}
70. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Lambda(Python)
Parameter Store 사용
import os, traceback, json, configparser, boto3
client = boto3.client('ssm’)
...
def load_config(ssm_parameter_path):
configuration = configparser.ConfigParser()
try:
# Get all parameters for this app
param_details = client.get_parameters_by_path(
Path=ssm_parameter_path,
Recursive=False,
WithDecryption=True )
# Loop through the returned parameters and populate the ConfigParser
if 'Parameters' in param_details and len(param_details.get('Parameters')) > 0:
for param in param_details.get('Parameters’):
param_path_array = param.get('Name').split("/")
section_position = len(param_path_array) - 1
section_name = param_path_array[section_position]
config_values = json.loads(param.get('Value’))
config_dict = {section_name: config_values}
configuration.read_dict(config_dict)
except:
traceback.print_exc()
finally:
return configuration
71. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS Secret Manager
72. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 데이터베이스 자격 증명 및 API 키와 같은 암호에 대한 수명주기 관리
AWS Secret Manager
보안 정보를
안전하게 교체
사용한 만큼 지불
세분화된 정책을
통해 액세스 관리
중앙 집중식
보안 정보 보호
및 감사
73. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 평문 보안 정보 삭제 이점
• 오용 위험 감소
• "비밀 확산"감소
• 개발자의 오버 헤드 감소
• 시작하기
• 계정 전략 선택 – 중앙 계정 또는 여러 계정에서 보안 정보 관리
• 보안 정보가 사용되는 위치 찾기
• AWS CloudFormation 또는 사용자 지정 도구를 사용하여 마이그레이션 자동화
AWS Secret Manager
Pro tip:
• 각 AWS 계정에서 Secrets Manager 운영
• 보안 암호 이름 지정, 검색, 암호화 및 순환에 대한 관행을 정의합니다.
• 보안 암호의 수를 확인하십시오.
74. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Good practice
• Poor practice
이름 지정 방법 정의
75. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Good practice
• Poor practice
• 이렇게 해보세요
• 의미있는 이름 사용
• 계층적 이름 (예: prod/MyMobileApp/MySQL)
• 설명을 사용하여 이 보안 암호에 대한 세부 정
보를 기록합니다.
• 태그를 사용하여 보안 암호를 그룹화하고 대규
모로 쉽게 관리합니다.
이름 지정 방법 정의
76. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Good practice
• Poor practice
이름 지정 방법 정의
77. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Good practice
• Poor practice
이름 지정 방법 정의
78. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Good practice
• Poor practice
이름 지정 방법 정의
79. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
“Statement": [
{
"Sid": “RequireTagWhenYouCreateSecret",
"Effect": "Allow",
"Action": [
“secretsmanager:CreateSecret“
],
"Resource": "*",
"Condition": {
"StringLike": {
“SecretsManager:RequestTag/Team": "*"
}
}
}
]
• Good practice
• Poor practice
이름 지정 방법 정의
80. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 프로그래밍 방식으로 검색시 이점
• 개발자는 보안 암호를 보거나 관리 할 필요가 없습니다.
• 시작하기
• 애플리케이션에 대한 IAM 역할 생성
• IAM 역할에 보안 암호를 검색 할 수 있는 권한 부여
• GetSecretValue API를 호출하도록 코드 업데이트
프로그래밍 방식으로 검색
Pro tip:
• 매시간 검색
• 클라이언트 측 캐싱 라이브러리를 사용하거나 자체 SDK를 개발하십시오
(예 : Spring Cloud SDK와 유사).
• Lambda 핸들러 외부에 검색할 코드 배치
• 삭제 스케줄
81. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
<bean id="employeeDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass"
value="com.amazonaws.secretsmanager.sql.AWSSecretsManagerMySQLDriver" />
<property name="jdbcUrl" value="jdbc-secretsmanager:mysql://my-dummy-rds-
instance.rds.amazonaws.com:3306" />
<!-- The property below can take a secret-id as ARN or friendly name -->
<property name="user" value="demo-secret" />
</bean>
• C3P0 Connection pooling via Spring
• https://aws.amazon.com/blogs/security/use-aws-secrets-manager-client-side-caching-libraries-to-improve-t
he-availability-and-latency-of-using-your-secrets/
Connection pooling
<bean id="employeeDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method
="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://my-dummy-rds-instance.rds.amazonaws.com:3306" />
<property name="user" value="user" />
<property name="password" value="password" />
</bean>
82. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• JAVA
Secret Manager
String secretName = "secretName”;
String region = "ap-northeast-2";
AWSSecretsManager client = AWSSecretsManagerClientBuilder.standard().withRegion(region).build();
String secret;
ByteBuffer binarySecretData;
GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest().withSecretId(secretName).withVersionStage("AWSCURRENT");
GetSecretValueResult getSecretValueResult = null;
try {
getSecretValueResult = client.getSecretValue(getSecretValueRequest);
} catch (Exception e) {
System.out.println("The request had errors: " + e.getMessage());
}
if (getSecretValueResult.getSecretString() != null) {
secret = getSecretValueResult.getSecretString();
System.out.println(secret);
} else {
binarySecretData = getSecretValueResult.getSecretBinary();
System.out.println(binarySecretData.toString());
}
83. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Java
Parameter Store + Secret Manager
AWSSimpleSystemsManagement ssm = AWSSimpleSystemsManagementClientBuilder.defaultClient();
...
AmazonDynamoDB getDynamoDbClient() {
//Getting AWS credentials from Secrets Manager using GetParameter
BasicAWSCredentials differentAWSCreds = new BasicAWSCredentials(
getParameter("/aws/reference/secretsmanager/access-key"),
getParameter("/aws/reference/secretsmanager/secret-key"));
//Initialize the DDB Client with different credentials
final AmazonDynamoDB client = AmazonDynamoDBClient.builder()
.withCredentials(new AWSStaticCredentialsProvider(differentAWSCreds))
.withRegion(getParameter("region")) //Getting config from Parameter Store
.build();
return client;
}
public GetParameterResult getParameter(String parameterName) {
GetParameterRequest request = new GetParameterRequest();
request.setName(parameterName);
request.setWithDecryption(true);
return ssm.newGetParameterCall().call(request).getParameter().getValue();
}
84. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Amazon CodeGuru
Amazon CodeGuru
85. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
전통적인 소프트웨어 워크플로우
Write + Review Build + Test Deploy Measure Improve
86. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
릴리즈 프로세스 스테이지
Source Build Test Deploy
• 다른 시스템과 통합
테스트 진행
• 부하 테스트
• UI 테스트
• 보안 테스트
• 필요한 소스코드
체크 인
• 새로운 코드리뷰
진행
• 코드 컴파일
• 유닛 테스트
• 코스 스타일 체크
(Lint)
• 컨테이너 이미지
생성과 함수 배포
패키지
• 프로덕션환경으로
배포
• 프로덕션 코드
모니터링으로 신속
하게 오류 감지
87. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
릴리즈 프로세스 스테이지
Source Build Test Deploy
지속적인 통합(Continuous integration)
지속적인 서비스 제공/배포(Continuous Deploy)
지속적인 개발(Continuous Develop)
88. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
전통적인 소프트웨어 워크플로우
Write + Review Build + Test Deploy Measure Improve
Inefficient
Code
Logging Debugging
89. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
애플리케이션 수명주기의 어려움
코드 분석 도구에는 코드
품질 및 효율성에 대한 업계
표준 모범 사례가 없습니다.
개발자가 문제가 있는
코드를 식별하는데
시간이 걸립니다
가장 비용이 많이드는
코드 줄을 시각화하고
수정하는 방법은 어렵습니다.
90. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 코드 품질 개선 및 어플리케이션에서 가장 실행비용이 비싼 코드 라인을 식별을 위한
지능적인 추천을 제공하는 기계학습 기반의 개발자 도구
Amazon CodeGuru
91. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 어플리케이션 개발주기의 서로 다른 단계를 보강하는 두 가지 기능
Amazon CodeGuru 의 두 가지 기능
Amazon CodeGuru
Profiler
Amazon CodeGuru
Reviewer
가장 실행비용이 비싼 코드 라인을 식별하여
어플리케이션 성능을 최적화하고 고객의
컴퓨팅 및 인프라 비용을 절감합니다.
기계 학습을 사용하여 심각한 문제와
찾기 어려운 버그들을 식별하고 코드
품질을 개선하기 위한 수정 방법을
추천합니다.
92. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
소프트웨어 워크 플로에 Amazon CodeGuru 추가
운영 환경에서 성능 및 비용
개선을 쉽게 식별
Amazon CodeGuru Profiler
비효율적인 코드 라
인 감지 및 최적화
실행 가능한 권장 사항이 포
함된 기본 제공 코드 리뷰
Amazon CodeGuru Reviewer
Write+ Review Build + Test Deploy Measure Improve
93. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Amazon CodeGuru - Reviewer
94. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
일반적인 코드 리뷰 프로세스는 수동이며 복잡함
Reviewer
AWS
CodeCommit
AWS
Cloud9
Code Review
PULL
REQUEST
APPROVAL
GitHub
Atlassian
Bitbucket
95. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Amazon CodeGuru Reviewer를 통해 개발자는 머신 러닝을 활용하여 프로덕션 문제로 이
어질 수있는 모범 사례에서 벗어난 일반적인 문제를 자동으로 표시합니다.
• Amazon CodeGuru Reviewer는 예제 코드 및 관련 문서에 대한 링크를 포함하여 코드 품질
을 향상시키는 방법에 대한 특정 권장 사항을 제공합니다.
• 개발자는 일반적인 프로세스나 소프트웨어를 변경하지 않고도 Amazon CodeGuru Review
er를 Code Reviewer 중 하나로 추가 할 수 있습니다.
Amazon CodeGuru Reviewer
96. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
CodeGuru Reviewer Workflow
Code
Repository
CodeGuru
Reviewer
3. Recommendation
4. Developer
Feedback
5. Improvement
for better
recommendations
1. Repository
Association
Repo Admin
2. Pull
Request
Developer
97. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Amazon CodeGuru Reviewer를 사용한 코드 리뷰
Code Review
애플리케이션이 배포되기 전에
코드에서 문법 검사를 추가하는
것과 같습니다.
Reviewer
AWS
CodeCommit
AWS Cloud9
PULL
REQUEST
CodeGuru
Reviewer
APPROVAL
GitHub
Atlassian
Bitbucket
98. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• AWS Best Practices: Correct use of AWS APIs
• Concurrency: Correct implementation of concurrency constructs
• Resource Leaks: Correct resource handling
• Code defects discovered by mining data: Hard to find defects
CodeGuru Reviewer가 다루는 영역 - Java
99. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• AWS API Security Best Practices: For AWS APIs
• Java Crypto Library Best Practices: For common Java cryptography libraries
• Secure Web Application: Not sanitized user input (e.g., cross-site scripting, LDAP injecti
on, path traversal injection, etc.)
• Sensitive Information Leak: Compliance Issues (e.g., logging of credit card number)
• AWS security best practices: Bringing internal security expertise (e.g. AWS Crypto recom
mendations) to our customers
리뷰어가 해결하는 보안 문제 - Java
100. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 코드 리뷰 추천
애플리케이션의 보안 취약성 해결
101. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Amazon CodeGuru - Profiler
102. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• CodeGuru 프로파일러는 가장 성능이 떨어지는 코드 라인을 찾습니다
CodeGuru 프로파일러
성능 최적화 가능성이 높은
메서드를 찾습니다
프로덕션 시스템용으로
구축
• 높은 지연 시간 및 낮은 처리량
• 높은 CPU 사용률
• 실행 가능한 권장 사항 제공
• 낮은 오버헤드
• 강력한 시각화
• 지속적으로 성능 분석
Java 지원
• 개요, 핫스팟 및 포커스 뷰
• AWS 람다, AWS EC2, Amazon ECS, E
KS, Fargate 및 온프레미스 지원
103. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
CodeGuru Profiler – 동작
Customer’s
application
Profiler
thread
Customer’s
application
Profiler
thread
Customer’s
application
Profiler
thread
Customer’s
application
Profiler
thread
Customer Application
CodeGuru Profiler
backend
Console - Visualizations
Actionable
recommendations
Console –
Recommendation reports
104. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• Developer Workflow with CodeGuru
Best Practice : CodeGuru
Code Repository
CodeDeploy
..........
Cloud9
IDE
Developers
CodePipeline:
CICD Pipeline
CodeBuild
Manual Code Review
Pull Request Notification
Local Repository
Trigger
CodePipeline
App Performance Monitorin
g
..........
Application Hosting Infrastructure
Code Review Recommendations
1
2
3 5 6
7
8
9
3
4
10
11
4
105. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Wrap-up
106. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
안전한 애플리케이션 개발을 위해서
HTTP/HTTPS
클라이언트
API 인터페이스
IAM
API 요청
Cognito
AWS 서비스
AWS STS
Amazon S3
Amazon EC2
Systems Manager CodeGuru
Reviewer
Secret Manager
KMS
Encryption
SDK
107. © 2021, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Amazon CodeGuru
Amazon CodeGuru로 코드 품질을 개선하고
애플리케이션에서
가장 비효율적인 코드 라인을 식별
프리 티어 - 90일 무료 평가판
코드 품질 개선을 시작하세요
aws.amazon.com/codeguru