Azure Pentesting

htARTE (HackTricks AWS Red Team Expert)를 통해 **제로부터 영웅까지 AWS 해킹 배우기**!

HackTricks를 지원하는 다른 방법:

아직 AZURE 방법론을 구축 중입니다

기본 정보

pageAz - Basic Information

Azure Pentester/Red Team 방법론

AZURE 환경을 감사하기 위해서는 사용 중인 서비스, 노출된 것, 누가 무엇에 액세스 권한을 가지고 있는지, 그리고 내부 Azure 서비스와 외부 서비스가 어떻게 연결되어 있는지를 알아야 합니다.

레드팀 관점에서 Azure 환경을 침해하는 첫 번째 단계는 Azure AD의 일부 자격 증명을 획들하는 것입니다. 다음은 그 방법에 대한 아이디어입니다:

  • github(또는 유사한 곳)의 누설 - OSINT

  • 사회 공학

  • 비밀번호 재사용 (비밀번호 누설)

  • Azure-호스팅 애플리케이션의 취약점

  • 서버 측 요청 위조(SSRF) - 메타데이터 엔드포인트에 액세스

  • 로컬 파일 읽기

  • /home/USERNAME/.azure

  • C:\Users\USERNAME\.azure

  • 2.30 이전의 az cliaccessTokens.json 파일 - 2022년 1월 - 액세스 토큰을 평문으로 저장

  • azureProfile.json 파일은 로그인한 사용자에 대한 정보를 포함

  • **az logout**은 토큰을 제거합니다.

  • 이전 버전의 **Az PowerShell**은 **TokenCache.dat**에 액세스 토큰평문으로 저장했습니다. 또한 **AzureRmContext.json**에 ServicePrincipalSecret평문으로 저장합니다. Save-AzContext cmdlet을 사용하여 토큰을 저장할 수 있습니다. Disconnect-AzAccount를 사용하여 제거합니다.

  • 3rd party 침입

  • 내부 직원

  • 일반적인 피싱 (자격 증명 또는 Oauth 앱)

Azure 테넌트 내에서 어떤 사용자도 침해하지 않았더라도, 몇 가지 정보를 수집할 수 있습니다:

pageAz - Unauthenticated Enum & Initial Entry

자격 증명을 획득한 후, 해당 자격 증명이 누구에게 속하는지무엇에 액세스 권한이 있는지 알아야 하므로 몇 가지 기본 열거를 수행해야 합니다:

기본 열거

열거 자체보다는 로그인이 가장 시끄러운 부분임을 기억하세요.

SSRF

Azure 내부의 기계에서 SSRF를 발견했다면 다음 페이지에서 트릭을 확인하세요:

로그인 조건 우회

일부 유효한 자격 증명이 있지만 로그인할 수 없는 경우, 다음과 같은 일반적인 보호 조치가 있을 수 있습니다:

  • IP 화이트리스트 -- 유효한 IP를 침해해야 함

  • 지리 제한 -- 사용자가 사는 곳이나 회사의 사무실이 어디인지 찾아 해당 도시(또는 적어도 국가)의 IP를 얻으세요

  • 브라우저 -- 특정 OS(Windows, Linux, Mac, Android, iOS)에서만 브라우저가 허용될 수 있습니다. 피해자/회사가 사용하는 OS를 확인하세요.

  • Service Principal 자격 증명을 침해해보세요. 일반적으로 덜 제한되며 로그인이 덜 검토됩니다

우회한 후에 초기 설정으로 돌아갈 수 있고 여전히 액세스 권한을 가질 수 있습니다.

서브도메인 탈취

Whoami

Az - AzureAD 섹션에서 az cli, AzureAD 및 Az PowerShell을 설치하는 방법을 배우세요.

알아야 할 첫 번째 사항 중 하나는 누구인지(어떤 환경에 있는지)를 알아야 합니다:

az account list
az account tenant list # Current tenant info
az account subscription list # Current subscription info
az ad signed-in-user show # Current signed-in user
az ad signed-in-user list-owned-objects # Get owned objects by current user
az account management-group list #Not allowed by default

AzureAD Security Best Practices ==============================

AzureAD is a critical component of many organizations' cloud infrastructure. Ensuring its security is paramount to protect sensitive data and resources. Here are some best practices to enhance AzureAD security:

  1. Enable Multi-Factor Authentication (MFA): Require users to provide additional verification beyond their password to access AzureAD.

  2. Regularly Review User Permissions: Periodically review and update user permissions to ensure least privilege access.

  3. Monitor Sign-In Logs: Keep track of sign-in logs and set up alerts for any suspicious activities.

  4. Enable Conditional Access Policies: Implement policies based on conditions like user location, device health, etc., to control access to AzureAD.

  5. Use Secure Password Policies: Enforce strong password policies, including password complexity and expiration.

  6. Enable Identity Protection: Utilize AzureAD Identity Protection to detect and respond to potential identity risks.

  7. Regularly Update and Patch: Keep AzureAD and associated systems up to date with the latest security patches.

  8. Educate Users: Train users on security best practices, such as recognizing phishing attempts and protecting their credentials.

By following these best practices, organizations can significantly improve the security of their AzureAD environment and reduce the risk of unauthorized access and data breaches.

#Get the current session state
Get-AzureADCurrentSessionInfo
#Get details of the current tenant
Get-AzureADTenantDetail

Azure PowerShell은 Azure 리소스를 관리하고 제어하기 위한 강력한 도구입니다. Azure PowerShell을 사용하면 스크립트를 작성하여 Azure 리소스를 자동화하고 구성할 수 있습니다. Azure PowerShell을 사용하면 Azure의 다양한 기능을 활용할 수 있으며, 특히 대규모 또는 반복적인 작업을 수행할 때 매우 유용합니다.

Azure PowerShell을 사용하면 가상 머신, 네트워크, 웹 앱, 데이터베이스 등과 같은 다양한 Azure 서비스를 관리할 수 있습니다. Azure PowerShell은 Azure Resource Manager(ARM)을 기반으로 하며, Azure의 모든 기능을 PowerShell 스크립트로 제어할 수 있습니다.

Azure PowerShell을 사용하면 Azure 환경을 효율적으로 관리하고 보안을 강화할 수 있습니다. PowerShell을 통해 Azure 리소스를 프로비저닝하고 모니터링하며, 보안 설정을 자동화하여 Azure 환경을 안전하게 유지할 수 있습니다.

Azure PowerShell은 다양한 운영 체제에서 사용할 수 있으며, Azure CLI와 함께 사용하여 Azure 환경을 효율적으로 관리할 수 있습니다.

# Get the information about the current context (Account, Tenant, Subscription etc.)
Get-AzContext
# List all available contexts
Get-AzContext -ListAvailable
# Enumerate subscriptions accessible by the current user
Get-AzSubscription
#Get Resource group
Get-AzResourceGroup
# Enumerate all resources visible to the current user
Get-AzResource
# Enumerate all Azure RBAC role assignments
Get-AzRoleAssignment # For all users
Get-AzRoleAssignment -SignInName test@corp.onmicrosoft.com # For current user

Azure를 열거하는 데 가장 중요한 명령 중 하나는 Az PowerShell의 **Get-AzResource**이며, 현재 사용자가 볼 수 있는 리소스를 알려줍니다.

동일한 정보를 웹 콘솔에서 얻을 수 있으며 https://portal.azure.com/#view/HubsExtension/BrowseAll로 이동하거나 "모든 리소스"를 검색할 수 있습니다.

AzureAD 열거

기본적으로 사용자는 사용자, 그룹, 역할, 서비스 주체 등을 열거할 충분한 권한을 갖고 있어야 합니다 (기본 AzureAD 권한을 확인하려면 기본 AzureAD 권한을 확인하십시오). 가이드를 여기에서 찾을 수 있습니다:

pageAz - AzureAD (AAD)

이제 자격 증명에 대한 일부 정보를 가지고 있으므로 (그리고 레드팀인 경우 감지되지 않았으면 좋겠습니다). 환경에서 사용되는 서비스를 확인해야 합니다. 다음 섹션에서는 일반적인 서비스를 열거하는 몇 가지 방법을 확인할 수 있습니다.

서비스 주체 및 액세스 정책

Azure 서비스는 시스템 ID(서비스 자체)를 가질 수도 있고 사용자 지정 관리 ID를 사용할 수도 있습니다. 이 ID는 예를 들어 KeyVault에 액세스 정책을 가질 수 있어 비밀을 읽을 수 있습니다. 이러한 액세스 정책은 제한되어야 하지만 필요한 것보다 더 많은 권한을 가질 수도 있습니다. 일반적으로 App Service는 비밀과 인증서를 검색하기 위해 KeyVault를 사용합니다.

따라서 이러한 ID를 탐색하는 것이 유용합니다.

App Service SCM

App Service '컨테이너'에 로그인하기 위한 Kudu 콘솔.

웹 쉘

portal.azure.com을 사용하여 쉘을 선택하거나 bash 또는 powershell을 위해 shell.azure.com을 사용합니다. 이 쉘의 '디스크'는 저장소 계정에 이미지 파일로 저장됩니다.

Azure DevOps

Azure DevOps는 Azure와 별도입니다. 저장소, 파이프라인 (yaml 또는 릴리스), 보드, 위키 등이 있습니다. 변수 그룹은 변수 값과 비밀을 저장하는 데 사용됩니다.

자동화된 Recon 도구

cd ROADTools
pipenv shell
roadrecon auth -u test@corp.onmicrosoft.com -p "Welcome2022!"
roadrecon gather
roadrecon gui

Import-Module monkey365
Get-Help Invoke-Monkey365
Get-Help Invoke-Monkey365 -Detailed
Invoke-Monkey365 -IncludeAzureActiveDirectory -ExportTo HTML -Verbose -Debug -InformationAction Continue
Invoke-Monkey365 - Instance Azure -Analysis All -ExportTo HTML

# Start Backend
cd stormspotter\backend\
pipenv shell
python ssbackend.pyz

# Start Front-end
cd stormspotter\frontend\dist\spa\
quasar.cmd serve -p 9091 --history

# Run Stormcollector
cd stormspotter\stormcollector\
pipenv shell
az login -u test@corp.onmicrosoft.com -p Welcome2022!
python stormspotter\stormcollector\sscollector.pyz cli
# This will generate a .zip file to upload in the frontend (127.0.0.1:9091)

# You need to use the Az PowerShell and Azure AD modules:
$passwd = ConvertTo-SecureString "Welcome2022!" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ("test@corp.onmicrosoft.com", $passwd)
Connect-AzAccount -Credential $creds

Import-Module AzureAD\AzureAD.psd1
Connect-AzureAD -Credential $creds

# Launch AzureHound
. AzureHound\AzureHound.ps1
Invoke-AzureHound -Verbose

# Simple queries
## All Azure Users
MATCH (n:AZUser) return n.name
## All Azure Applications
MATCH (n:AZApp) return n.objectid
## All Azure Devices
MATCH (n:AZDevice) return n.name
## All Azure Groups
MATCH (n:AZGroup) return n.name
## All Azure Key Vaults
MATCH (n:AZKeyVault) return n.name
## All Azure Resource Groups
MATCH (n:AZResourceGroup) return n.name
## All Azure Service Principals
MATCH (n:AZServicePrincipal) return n.objectid
## All Azure Virtual Machines
MATCH (n:AZVM) return n.name
## All Principals with the ‘Contributor’ role
MATCH p = (n)-[r:AZContributor]->(g) RETURN p

# Advanced queries
## Get Global Admins
MATCH p =(n)-[r:AZGlobalAdmin*1..]->(m) RETURN p
## Owners of Azure Groups
MATCH p = (n)-[r:AZOwns]->(g:AZGroup) RETURN p
## All Azure Users and their Groups
MATCH p=(m:AZUser)-[r:MemberOf]->(n) WHERE NOT m.objectid CONTAINS 'S-1-5' RETURN p
## Privileged Service Principals
MATCH p = (g:AZServicePrincipal)-[r]->(n) RETURN p
## Owners of Azure Applications
MATCH p = (n)-[r:AZOwns]->(g:AZApp) RETURN p
## Paths to VMs
MATCH p = (n)-[r]->(g: AZVM) RETURN p
## Paths to KeyVault
MATCH p = (n)-[r]->(g:AZKeyVault) RETURN p
## Paths to Azure Resource Group
MATCH p = (n)-[r]->(g:AZResourceGroup) RETURN p
## On-Prem users with edges to Azure
MATCH  p=(m:User)-[r:AZResetPassword|AZOwns|AZUserAccessAdministrator|AZContributor|AZAddMembers|AZGlobalAdmin|AZVMContributor|AZOwnsAZAvereContributor]->(n) WHERE m.objectid CONTAINS 'S-1-5-21' RETURN p
## All Azure AD Groups that are synchronized with On-Premise AD
MATCH (n:Group) WHERE n.objectid CONTAINS 'S-1-5' AND n.azsyncid IS NOT NULL RETURN n

# You should use an account with at least read-permission on the assets you want to access
git clone https://github.com/nccgroup/azucar.git
PS> Get-ChildItem -Recurse c:\Azucar_V10 | Unblock-File

PS> .\Azucar.ps1 -AuthMode UseCachedCredentials -Verbose -WriteLog -Debug -ExportTo PRINT
PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000
PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -CertFilePassword MySuperP@ssw0rd! -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000

# resolve the TenantID for an specific username
PS> .\Azucar.ps1 -ResolveTenantUserName user@company.com

Import-Module .\MicroBurst.psm1
Import-Module .\Get-AzureDomainInfo.ps1
Get-AzureDomainInfo -folder MicroBurst -Verbose

Connect-AzAccount
ipmo C:\Path\To\Powerzure.psd1
Get-AzureTarget

# Reader
$ Get-Runbook, Get-AllUsers, Get-Apps, Get-Resources, Get-WebApps, Get-WebAppDetails

# Contributor
$ Execute-Command -OS Windows -VM Win10Test -ResourceGroup Test-RG -Command "whoami"
$ Execute-MSBuild -VM Win10Test  -ResourceGroup Test-RG -File "build.xml"
$ Get-AllSecrets # AllAppSecrets, AllKeyVaultContents
$ Get-AvailableVMDisks, Get-VMDisk # Download a virtual machine's disk

# Owner
$ Set-Role -Role Contributor -User test@contoso.com -Resource Win10VMTest

# Administrator
$ Create-Backdoor, Execute-Backdoor
htARTE (HackTricks AWS Red Team Expert)와 함께 **제로부터 영웅까지 AWS 해킹 배우기**!

다른 방법으로 HackTricks를 지원하는 방법:

最終更新