IT/Infra&Cloud

[aws] backup using cross account cmk key

Hayley Shim 2023. 12. 3. 23:59

안녕하세요. 이번에는 AWS의 서로 다른 계정 간 KMS 키를 공유하여 AWS Backup Vault에 백업을 해보겠습니다.

 

서로 다른 계정 간 키 공유

https://repost.aws/ko/knowledge-center/share-kms-account

 

AWS 계정 간 KMS 키 공유

다른 AWS 계정에 내 AWS Key Management Service(AWS KMS) 키에 대한 액세스 권한을 안전하게 부여하고 싶습니다.

repost.aws

 

위 글을 참고하여 다른 계정과 KMS 키를 공유하려면 아래와 같은 절차가 필요합니다.

 

AWS KMS 키를 다른 계정과 공유하려면 보조 계정에 다음 권한을 부여해야 합니다.

  • 키 정책: 보조 계정에는 AWS KMS 키 정책을 사용할 수 있는 권한이 있어야 합니다. 이 정책은 키를 소유한 계정에 존재합니다. 자세한 내용과 주요 정책 설명 예시는 로컬 계정에 주요 정책 설명 추가를 참조하세요 .
  • AWS Identity and Access Management(IAM) 정책: 보조 계정에는 키 사용에 대한 액세스 권한을 부여하는 정책에 대한 권한이 있어야 합니다.

보다 자세하게 키 정책 및 IAM 정책을 사용하여 키에 대한 액세스 권한을 부여하는 방법에 대해서는 다른 계정의 사용자가 AWS KMS 키를 사용하도록 허용 을 참조하세요.

 

다른 AWS 계정의 사용자나 역할이 자신의 계정에서 KMS 키를 사용하도록 허용할 수 있습니다. 교차 계정 액세스에는 KMS 키의 키 정책과 외부 사용자 계정의 IAM 정책에 대한 권한이 필요합니다.

 

다른 계정의 사용자 및 역할에 KMS 키 사용 권한을 부여하려면 두 가지 유형의 정책을 사용해야 합니다.

  • KMS 키에 대한 키 정책은 외부 계정(또는 외부 계정의 사용자 및 역할)에게 KMS 키를 사용할 수 있는 권한을 부여해야 합니다. 키 정책은 KMS 키를 소유한 계정에 있습니다.
  • 외부 계정의 IAM 정책은 주요 정책 권한을 해당 사용자 및 역할에 위임해야 합니다. 이러한 정책은 외부 계정에 설정되며 해당 계정의 사용자 및 역할에 권한을 부여합니다.

키 정책은 KMS 키에 액세스 할 수 있는 사람을 결정합니다. IAM 정책은 KMS 키에 액세스할 수 있는 사람을 결정합니다. 키 정책이나 IAM 정책만으로는 충분하지 않습니다. 둘 다 변경해야 합니다.

 

아래와 같은 단계로 다른 계정에서 KMS 키를 사용할 수 있도록 해줍니다.

 

1단계: 로컬 계정에 주요 정책 설명 추가

KMS 키에 대한 키 정책 KMS 키에 액세스할 수 있는 사람 이들이 수행할 수 있는 작업을 결정하는 주요 요소입니다. 

1. 키 정책은 항상 KMS 키를 소유한 계정에 있습니다. 

2. IAM 정책과 달리 주요 정책은 리소스를 지정하지 않습니다. 

3. 리소스는 키 정책과 연결된 KMS 키입니다. 

4. 교차 계정 권한을 제공할 때 KMS 키에 대한 키 정책은 외부 계정(또는 외부 계정의 사용자 및 역할)에게 KMS 키를 사용할 수 있는 권한을 부여해야 합니다.

- 다음 예는 KMS 키를 다른 계정과 공유하기 위한 샘플 키 정책을 나타냅니다. 예제 Sid, Principal및 Action값을 KMS 키의 용도에 맞는 유효한 값으로 바꿉니다.
{
    "Sid": "Allow an external account to use this KMS key",
    "Effect": "Allow",
    "Principal": {
        "AWS": [
            "arn:aws:iam::444455556666:root"
        ]
    },
    "Action": [
        "kms:Encrypt",
        "kms:Decrypt",
        "kms:ReEncrypt*",
        "kms:GenerateDataKey*",
        "kms:DescribeKey"
    ],
    "Resource": "*"
}
 

2단계: 외부 계정에 IAM 정책 추가

외부 계정의 사용자와 역할은 해당 권한을 위임하는 IAM 정책을 연결하거나 권한 부여를 사용하여 KMS 키에 대한 액세스를 관리할 때까지 KMS 키를 사용할 수 없습니다. IAM 정책은 외부 계정에 설정됩니다. 

키 정책이 외부 계정에 권한을 부여하는 경우 계정의 모든 사용자 또는 역할에 IAM 정책을 연결할 수 있습니다.

 

- 다음 예는 KMS 키를 다른 계정과 공유하기 위한 샘플 IAM 정책을 나타냅니다. 예제 Sid, Resource및 Action값을 KMS 키의 용도에 맞는 유효한 값으로 바꿉니다.

{
    "Sid": "AllowUseOfKeyInAccount111122223333",
    "Effect": "Allow",
    "Action": [
      "kms:Encrypt",
      "kms:Decrypt",
      "kms:ReEncrypt*",
      "kms:GenerateDataKey*",
      "kms:DescribeKey"
    ],
    "Resource": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
}

 

다른 계정에서 사용할 수 있는 KMS 키 만들기

AWS Management Console에서 KMS 키를 생성하면 해당 키 정책도 생성됩니다. 키 관리자  키 사용자 섹션 에서 자격 증명을 선택하면 AWS KMS는 해당 자격 증명에 대한 정책 설명을 KMS 키의 키 정책에 추가합니다.

주요 사용자 섹션에서는 외부 계정을 주요 사용자로 추가할 수도 있습니다.

 

외부 계정의 계정 ID를 입력하면 AWS KMS는 키 정책에 두 개의 문을 추가합니다. 이 작업은 키 정책에만 영향을 미칩니다. 외부 계정의 사용자 및 역할은 IAM 정책을 연결하여 이러한 권한 중 일부 또는 전부를 부여할 때까지 KMS 키를 사용할 수 없습니다 .

1. 암호화 작업에 KMS 키를 사용할 수 있는 권한을 외부 계정에 부여합니다.

- 다음 예는 KMS 키를 다른 계정과 공유하기 위한 샘플 키 정책을 나타냅니다. 예제 Sid, Principal및 Action값을 KMS 키의 용도에 맞는 유효한 값으로 바꿉니다.

{
    "Sid": "Allow use of the key",
    "Effect": "Allow",
    "Principal": {
        "AWS": "arn:aws:iam::444455556666:root"
    },
    "Action": [
        "kms:Encrypt",
        "kms:Decrypt",
        "kms:ReEncrypt*",
        "kms:GenerateDataKey*",
        "kms:DescribeKey"
    ],
    "Resource": "*"
}

 

 2. 두 번째 주요 정책 설명은 외부 계정이 KMS 키에 대한 권한 부여를 생성, 보기 및 취소할 수 있도록 허용합니다.

{
    "Sid": "Allow attachment of persistent resources",
    "Effect": "Allow",
    "Principal": {
        "AWS": "arn:aws:iam::444455556666:root"
    },
    "Action": [
        "kms:CreateGrant",
        "kms:ListGrants",
        "kms:RevokeGrant"
    ],
    "Resource": "*",
    "Condition": {
        "Bool": {
            "kms:GrantIsForAWSResource": "true"
        }
    }
}

 

우선 위 설명과 같이 다른 계정(B계정)에서 사용할 KMS 키를 A 계정에서 생성해줍니다. 

 

 

 

 

 

 

위와 같이 KMS 키를 사용할 수 있는 다른 AWS 계정을 추가해줍니다.

 

 

사용자 정의 키를 사용하기 위해 외부 계정에 대한 액세스 권한을 부여할 때 다음 네 가지 중요한 사항에 유의합니다. [참고]. 

  1. 암호화된 리소스를 생성할 때 외부 계정 관리자가 직접 관리하거나 선택할 수 있도록 AWS Management Console 어디에도 키가 표시되지 않습니다. 외부 계 정의 관리자는 키를 사용하여 암호화된 리소스를 생성하려면 키의 ARN을 지정해야 합니다.(The key will not appear anywhere in the AWS Management Console for administrators of the external account to directly manage or select when creating encrypted resources. The administrator of the external account will need to specify the key’s ARN to use the key to create encrypted resources.)
  2. 외부 계정에 대한 액세스 권한을 부여한 후 해당 외부 계정의 루트 사용자는 키를 사용하여 Encrypt , Decrypt , ReEncrypt , GenerateDataKey  DescriptionKey 작업을 실행할 수 있습니다 . 이러한 KMS API는 지원되는 AWS 서비스 콘솔에서 키를 선택하고 이를 사용하여 이러한 서비스 또는 자체 애플리케이션의 데이터를 암호화하는 데 필요합니다. 사용 권한 설명은 이 키를 사용하여 Encrypt , Decrypt , ReEncrypt , GenerateDataKey  DescriptionKey 작업을 사용할 권한이 있는 사용자 또는 계정을 정의합니다. 다음 예에서는 상위 계정 109876543210과 외부 계정 012345678901이 모두 이러한 권한을 가진 보안 주체입니다.(After you grant access to external accounts, root users of those external accounts can execute the following actions using your key: Encrypt, Decrypt, ReEncrypt, GenerateDataKey, and DescribeKey. These KMS APIs are the ones needed to select keys from the console of supported AWS services and use them to encrypt data in these services or in your own applications. The usage permissions statement defines which users or accounts have permissions to use Encrypt, Decrypt, ReEncrypt, GenerateDataKey, and DescribeKey operations with this key. In the following example, both the parent account, 109876543210, and the external account, 012345678901, are principals with these permissions.)
  {
	                  "Sid": "AllowUseOfTheKey",
	              "Effect": "Allow",
	              "Principal": {
	                "AWS": [
	                  "arn:aws:iam:: 109876543210:user/User1","arn:aws:iam::012345678901:root"
	                ]
	              },
	              "Action": [
	                "kms:Encrypt",
	                "kms:Decrypt",
	                "kms:ReEncrypt*",
	                "kms:GenerateDataKey*",
	                "kms:DescribeKey"
	              ],
	              "Resource": "*"
                  }

- 명령줄 인터페이스(CLI)를 사용하면 PutPolicy 호출을 사용하여 이 키 정책을 편집하여 허용 가능한 작업을 이러한 작업의 하위 집합으로 추가로 제한할 수 있습니다. 예를 들어, 계정이 KMS 키를 사용하여 암호화만 하고 암호 해독은 허용하지 않으려는 사용 사례가 있을 수 있습니다.

 

3. KMS와 통합된 AWS 서비스는 교차 계정 액세스를 활성화한 외부 계정을 대신하여 키를 사용할 수 있습니다. 이러한 권한을 통해 KMS와 통합된 AWS 서비스는 지정된 보안 주체(이 경우 상위 계정 109876543210 및 외부 계정 012345678901)를 대신하여 이 키를 사용할 수 있습니다. 특히 이 명령문을 통해 AWS 서비스는 사용자에 대한 권한 부여를 생성하고 관리할 수 있습니다. 열쇠. 이러한 부여는 AWS 서비스가 특정 암호화된 리소스를 보다 안전한 방식으로 관리하는 데 사용하는 추가 범위 축소 권한입니다. 이 키 정책의 조건은 AWS 서비스가 AWS 계정의 리소스에 대해 이러한 권한만 적용하도록 설계된 컨텍스트 키를 사용합니다.(AWS services integrated with KMS can use your key on behalf of external accounts for which you have enabled cross-account access. These permissions enable AWS services integrated with KMS to use this key on behalf of the specified principals—in this case, the parent account, 109876543210, and the external account, 012345678901. Specifically, this statement permits AWS services to create and manage grants on your key. These grants are additional scoped-down permissions that AWS services use to manage certain encrypted resources in a more secure fashion. The condition in this key policy uses a context key that is designed to ensure that AWS services apply only these permissions on resources in your AWS account.)

 

 {    
                      "Sid": "AllowAttachmentOfPersistentResources",
		      "Effect": "Allow",
		      "Principal": {
		        "AWS": [
		          "arn:aws:iam::109876543210:user/User1","arn:aws:iam::012345678901:root"
		        ]
		      },
		      "Action": [
		        "kms:CreateGrant",
		        "kms:ListGrants",
		        "kms:RevokeGrant"
		      ],
		      "Resource": "*",
		      "Condition": {"Bool": {"kms:GrantIsForAWSResource": true}}  
                    }

 

4. 외부 계정의 IAM 사용자 및 역할은 외부 계정의 계정 관리자가 KMS 키 ARN 및 허용된 작업을 지정하는 리소스 수준 정책을 생성하고 연결하지 않는 한 해당 키를 사용할 수 없습니다 . 키의 ARN은 외부 계정(이 예에서는 012345678901)의 IAM 사용자와 연결된 정책에서만 참조할 수 있습니다. 허용되는 작업은 위의 1단계에서 정의한 대로 관리자가 액세스할 수 있는 작업의 하위 집합입니다. 외부 계정 012345678901의 IAM 사용자 또는 역할이 사용자 지정 키를 사용할 수 있어야 하는 경우 외부 계정의 IAM 관리자는 다음 IAM 정책을 해당 사용자 또는 역할에 연결해야 합니다.(IAM users and roles in the external account will not be able to use the key unless the account administrator of the external account creates and attaches a resource-level policy that specifies the KMS key ARN and permitted actions. The key’s ARN can be referenced only in a policy associated with IAM users under the external account (012345678901, in this example).The permitted actions will be a subset of the actions that the administrator has access to, as defined in step 1 above. If IAM users or roles in the external account, 012345678901, need to be able to use your custom key, the following IAM policy should be attached to those users or roles by the IAM administrator of the external account:)

 

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowUseOfTheKey",
            "Effect": "Allow",
            "Action": [
                "kms:Encrypt",
                "kms:Decrypt",
                "kms:ReEncrypt*",
                "kms:GenerateDataKey*",
                "kms:DescribeKey"
            ],
            "Resource": [
                "arn:aws:kms:us-east-1:109876543210:key/1a345678-1234-1234-1234-12345678901c"
            ]
        },
        {
            "Sid": "AllowAttachmentOfPersistentResources",
            "Effect": "Allow",
            "Action": [
                "kms:CreateGrant",
                "kms:ListGrants",
                "kms:RevokeGrant"
            ],
            "Resource": [
                "arn:aws:kms:us-east-1:109876543210:key/1a345678-1234-1234-1234-12345678901c"
            ],
            "Condition": {
                "Bool": {
                    "kms:GrantIsForAWSResource": true
                }
          }
        }
    ]
}

이 키 정책의 첫 번째 설명에 있는 리소스는 사용자 지정 키의 Amazon 리소스 이름 (ARN)을 나타냅니다. 두 번째 문을 사용하면 IAM 사용자가 권한 부여를 생성할 수 있습니다. IAM 사용자 또는 역할이 KMS와 통합되는 AWS 서비스를 사용해야 하는 경우 이 정책에서 허용되는 작업을 변경하지 않는 것이 좋습니다. 이러한 서비스는 사용자 또는 역할에 대해 모든 기본 작업이 활성화되어 있다고 가정합니다. 누락된 작업이 있으면 사용자는 예상치 못한 결과를 경험하게 됩니다. 그러나 IAM 사용자 또는 역할이 KMS SDK를 사용하는 사용자 지정 애플리케이션 내에서만 키를 사용한다는 것을 알고 있다면 사용 사례 목표를 충족하기 위해 허용되는 API 작업을 제어할 수 있습니다.

 

계정 A에서 생성한 CMK

 

 

해당 키를 다른 계정의 리소스에 적용해보겠습니다.

AWS 특정 서비스가 AWS KMS를 사용하는 방법을 참고합니다.[참고 ]

 

A 계정에서 생성한 CMK 키를 사용하여  AWS Backup Vault에서 사용할 수 있도록 cloudformation, cli, sdk 등의 방법으로 해당 backup vault 리소스를 생성해줍니다. 

계정 A에서 생성한 CMK를 적용한 AWS Backup Vault

 

이전 블로그 글([aws]Organization policy-backup)에서 작성한 방법대로 백업을 진행해줍니다. 

AWS Organization - Cross account monitoring
계정 내 backup job

 

A 계정에서 공유한 CMK를 사용하여 EC2 Backup 완료

 

위와 같이 A 계정에서 공유한 CMK를 사용하여 다른 계정 내 Backup을 완료했습니다. 

 

참고로 같은 조직(OU)에 속한 계정 간 KMS 키 공유를 위해서는 아래와 같은 방법을 참고합니다.

 

아래 조건 추가

"Condition" : { "ForAnyValue:StringLike" : {
     "aws:PrincipalOrgPaths":["o-a1b2c3d4e5/r-ab12/ou-ab12-11111111/ou-ab12-22222222/*"]
}}

 

{
    "Version": "2012-10-17",
    "Id": "key-consolepolicy-3",
    "Statement": [
        {
            "Sid": "Enable IAM User Permissions",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::6XXXXXXXXXXX:root"
            },
            "Action": "kms:*",
            "Resource": "*"
        },
        {
            "Sid": "Allow access for Key Administrators",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::6XXXXXXXXXXX:user/SecurityAccountAdminUser"
            },
            "Action": [
                "kms:Create*",
                "kms:Describe*",
                "kms:Enable*",
                "kms:List*",
                "kms:Put*",
                "kms:Update*",
                "kms:Revoke*",
                "kms:Disable*",
                "kms:Get*",
                "kms:Delete*",
                "kms:TagResource",
                "kms:UntagResource",
                "kms:ScheduleKeyDeletion",
                "kms:CancelKeyDeletion"
            ],
            "Resource": "*"
        },
        {
            "Sid": "Allow attachment of persistent resources",
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::6XXXXXXXXXXX:user/SecurityAccountAdminUser",
                    "arn:aws:iam::3XXXXXXXXXXX:root"
                ]
            },
            "Action": [
                "kms:CreateGrant",
                "kms:ListGrants",
                "kms:RevokeGrant"
            ],
            "Resource": "*",
            "Condition": {
                "Bool": {
                    "kms:GrantIsForAWSResource": "true"
                }
            }
        },
        {
            "Sid": "Allow use of the KMS key for organization",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": [
                "kms:Decrypt",
                "kms:DescribeKey",
                "kms:Encrypt",
                "kms:ReEncrypt*",
                "kms:GetKeyPolicy"
            ],
            "Resource": "*",
            "Condition": {
                "ForAnyValue:StringLike": {
                    "aws:PrincipalOrgPaths": "o-XXXXXXX/r-iwhm/ou-iwhm-XXXXXXXX/*"
                }
            }
        }
    ]
}

 

 

해당 OU에 속한 계정에서 API로 확인

 

aws kms describe-key --key-id arn값

 

https://repost.aws/knowledge-center/kms-key-organization-account

 

 

 

Allow all AWS Organization accounts to use an AWS KMS key

I want to restrict AWS Key Management Service (AWS KMS) key access to only the principals that belong to my AWS Organization.

repost.aws

https://docs.aws.amazon.com/ko_kr/IAM/latest/UserGuide/reference_policies_condition-keys.html

 

AWS 글로벌 조건 컨텍스트 키 - AWS Identity and Access Management

이 키를 사용할 때는 주의해야 합니다. aws:UserAgent 값은 HTTP 헤더의 호출자가 제공하기 때문에, 권한이 없는 사용자가 수정된 브라우저나 사용자 지정 브라우저를 사용하여 원하는 aws:UserAgent 값

docs.aws.amazon.com

 

 

error)

AWS Backup Vault 서비스에 적용하며 아래와 같은 에러가 발생했습니다.

Cross-Account KMS Key Alias ARN - Invalid Key provided by the user Error

 

관련 블로그)

https://repost.aws/questions/QUdEcESWqFQrGIhLxNiL5png/cross-account-kms-key-alias-arn-invalid-key-provided-by-the-user-error

 

error)

policy contains a statement with one or more invalid principals

https://repost.aws/knowledge-center/kms-policy-error-invalid-principals

 

Resolve KMS key policy error "Policy contains a statement with one or more invalid principals"

I tried to modify my AWS Key Management Service (AWS KMS) key policy, and I received an error in the AWS Management Console similar to the following: "PutKeyPolicy request failed MalformedPolicyDoc...

repost.aws

 

error)

지정된 키 정책이 구문상 또는 의미상 올바르지 않기 때문에 요청이 거부되면 AWS KMS API 호출 PutKeyPolicy 요청이 실패합니다. 

 

PutKeyPolicy - AWS Key Management Service

In the following list, the required parameters are described first.

docs.aws.amazon.com

 

참고

https://dev.to/aws-builders/how-to-configure-cross-account-aws-backup-2ca2

 

How to configure cross-account AWS Backup

Introduction This blog post will describe how to set up cross-account AWS Backup. Let's im...

dev.to

https://aws.amazon.com/ko/blogs/storage/create-and-share-encrypted-backups-across-accounts-and-regions-using-aws-backup/

 

Create and share encrypted backups across accounts and Regions using AWS Backup | Amazon Web Services

Enterprises and organizations in more security-conscious industries often protect their data through encryption, restricting data access to those with the necessary permissions and improving their security posture. Creating backups of data resources is oft

aws.amazon.com

https://medium.com/gargee-bhatnagar/store-and-retrieve-secrets-for-cross-account-services-using-kms-permission-policy-and-iam-roles-33f0f18cf44b