Az - CosmosDB

Reading time: 14 minutes

tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기

Azure CosmosDB

Azure Cosmos DB는 단일 밀리초 응답 시간, 자동 확장성 및 엔터프라이즈급 보안이 보장된 SLA를 제공하는 완전 관리형 NoSQL, 관계형 및 벡터 데이터베이스입니다. 이는 다중 지역 데이터 분배, 오픈 소스 API, 인기 있는 언어를 위한 SDK 및 통합 벡터 지원과 원활한 Azure AI 통합과 같은 AI 데이터베이스 기능을 통해 더 빠른 앱 개발을 가능하게 합니다.

Azure Cosmos DB는 문서, 관계형, 키-값, 그래프 및 열 패밀리 데이터 모델을 사용하여 실제 데이터를 모델링하기 위해 여러 데이터베이스 API를 제공합니다. 이 API는 NoSQL, MongoDB, PostgreSQL, Cassandra, Gremlin 및 Table입니다.

CosmosDB의 주요 측면 중 하나는 Azure Cosmos Account입니다. Azure Cosmos Account는 데이터베이스에 대한 진입점 역할을 합니다. 계정은 글로벌 분배, 일관성 수준 및 사용할 특정 API(예: NoSQL)와 같은 주요 설정을 결정합니다. 계정을 통해 여러 지역에서 데이터에 대한 저지연 액세스를 보장하기 위해 글로벌 복제를 구성할 수 있습니다. 또한 성능과 데이터 정확성 간의 균형을 맞추는 일관성 수준을 선택할 수 있으며, 옵션은 Strong에서 Eventual consistency까지 다양합니다.

Azure Cosmos DB는 사용자 할당 ID시스템 할당 관리 ID를 지원하며, 이는 자동으로 생성되어 리소스의 수명 주기에 연결됩니다. 그러나 Cosmos DB는 Azure Blob Storage와 같은 외부 데이터 소스를 직접 쿼리하는 내장 메커니즘이 없습니다. SQL Server의 외부 테이블 기능과 달리, Cosmos DB는 데이터가 네이티브 쿼리 기능으로 쿼리될 수 있도록 Azure Data Factory, 데이터 마이그레이션 도구 또는 사용자 지정 스크립트와 같은 외부 도구를 사용하여 컨테이너에 수집되어야 합니다.

NoSQL

Azure Cosmos DB NoSQL API는 JSON을 데이터 형식으로 사용하는 문서 기반 API입니다. 이는 JSON 객체를 쿼리하기 위한 SQL 유사 쿼리 구문을 제공하여 구조화된 데이터 및 반구조화된 데이터 작업에 적합합니다. 서비스의 엔드포인트는:

bash
https://<Account-Name>.documents.azure.com:443/

데이터베이스

계정 내에서 하나 이상의 데이터베이스를 생성할 수 있으며, 이는 컨테이너의 논리적 그룹으로 작용합니다. 데이터베이스는 리소스 관리 및 사용자 권한의 경계 역할을 합니다. 데이터베이스는 여러 컨테이너가 공유 성능 용량 풀을 사용할 수 있도록 하거나 각 컨테이너에 전용 성능을 제공할 수 있습니다.

컨테이너

데이터 저장의 핵심 단위는 컨테이너로, JSON 문서를 보유하고 효율적인 쿼리를 위해 자동으로 인덱싱됩니다. 컨테이너는 탄력적으로 확장 가능하며, 사용자 정의 파티션 키에 의해 결정된 파티션에 분산됩니다. 파티션 키는 최적의 성능과 균등한 데이터 분포를 보장하는 데 중요합니다. 예를 들어, 컨테이너는 고객 데이터를 저장할 수 있으며, "customerId"가 파티션 키로 사용될 수 있습니다.

주요 기능

  • 글로벌 배포: 지역 간 복제를 위한 Geo-Redundancy를 활성화 또는 비활성화하고, 가용성을 향상시키기 위한 Multi-region Writes를 지원합니다.
  • 네트워킹 및 보안: 공용(모든/선택 네트워크) 또는 개인 엔드포인트 간의 연결을 제공합니다. TLS 1.2 암호화를 통한 안전한 연결을 지원합니다. 리소스에 대한 제어된 접근을 위해 CORS(Cross-Origin Resource Sharing)를 지원합니다. Microsoft Defender for Cloud를 활성화할 수 있습니다. 연결을 위해 키를 사용할 수 있습니다.
  • 백업 및 복구: 주기적, 지속적(7일), 또는 지속적(30일) 백업 정책을 통해 구성 가능한 간격과 보존 기간을 제공합니다.
  • 데이터 암호화: 기본 서비스 관리 키 또는 고객 관리 키(CMK)를 통한 암호화(CMK 선택은 되돌릴 수 없습니다).

열거

bash
# CosmoDB Account
## List Azure Cosmos DB database accounts.
az cosmosdb list --resource-group <ResourceGroupName>
az cosmosdb show --resource-group <ResourceGroupName> --name <AccountName>

## Lists the virtual network accounts associated with a Cosmos DB account
az cosmosdb network-rule list --resource-group <ResourceGroupName> --name <AccountName>
## List the access keys or connection strings for a Azure Cosmos DB
az cosmosdb keys list --name <AccountName> --resource-group <ResourceGroupName>
## List all the database accounts that can be restored.
az cosmosdb restorable-database-account list --account-name <AccountName>
## Show the identities for a Azure Cosmos DB database account.
az cosmosdb identity show --resource-group <ResourceGroupName> --name <AccountName>


# CosmoDB (NoSQL)
## List the NoSQL databases under an Azure Cosmos DB account.
az cosmosdb sql database list --resource-group <ResourceGroupName> --account-name <AccountName>
## List the NoSQL containers under an Azure Cosmos DB NoSQL database.
az cosmosdb sql container list --account-name <AccountName> --database-name <DatabaseName> --resource-group <ResourceGroupName>

## List all NoSQL role assignments under an Azure Cosmos DB
az cosmosdb sql role assignment list --resource-group <ResourceGroupName> --account-name <AccountName>
## List all NoSQL role definitions under an Azure Cosmos DB
az cosmosdb sql role definition list --resource-group <ResourceGroupName> --account-name <AccountName>

## List the NoSQL stored procedures under an Azure Cosmos DB
az cosmosdb sql stored-procedure list --account-name <AccountName> --container-name <ContainerName> --database-name <DatabaseName> --resource-group <ResourceGroupName>
## List the NoSQL triggers under an Azure Cosmos DB NoSQL container.
az cosmosdb sql trigger list --account-name <AccountName> --container-name <ContainerName> --database-name <DatabaseName> --resource-group <ResourceGroupName>
## List the NoSQL user defined functions under an Azure Cosmos DB NoSQL container
az cosmosdb sql user-defined-function list --account-name <AccountName> --container-name <ContainerName> --database-name <DatabaseName> --resource-group <ResourceGroupName>


## MongoDB (vCore)
# Install az cli extension
az extension add --name cosmosdb-preview
# List all MongoDB databases in a specified Azure Cosmos DB account
az cosmosdb mongocluster list
az cosmosdb mongocluster show --cluster-name <name> --resource-group <ResourceGroupName>
# Get firewall rules
az cosmosdb mongocluster firewall rule list --cluster-name <name> --resource-group <ResourceGroupName>
# Connect to in
brew install mongosh
mongosh "mongodb://<username>:<password>@<account-name>.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retryWrites=false" --username <username> --password <password>

연결

2가지 키 유형이 있습니다: 읽기-쓰기(전체) 및 읽기 전용. 이들은 Cosmos DB 계정 내의 모든 데이터베이스, 컬렉션 및 데이터에 대한 액세스를 제공합니다. azure-cosmosDB에 연결하려면 (pip install azure-cosmos) 라이브러리가 필요합니다. 또한 엔드포인트와 키는 연결을 만드는 데 중요한 구성 요소입니다.

python
from azure.cosmos import CosmosClient, PartitionKey

# Connection details
endpoint = "<your-account-endpoint>"
key = "<your-account-key>"

# Initialize Cosmos Client
client = CosmosClient(endpoint, key)

# Access existing database and container
database_name = '<SampleDB>'
container_name = '<SampleContainer>'
database = client.get_database_client(database_name)
container = database.get_container_client(container_name)

# Insert multiple documents
items_to_insert = [
{"id": "1", "name": "Sample Item", "description": "This is a sample document."},
{"id": "2", "name": "Another Sample Item", "description": "This is another sample document."},
{"id": "3", "name": "Sample Item", "description": "This is a duplicate name sample document."},
]

for item in items_to_insert:
container.upsert_item(item)

# Query all documents
query = "SELECT * FROM c"
all_items = list(container.query_items(
query=query,
enable_cross_partition_query=True
))

# Print all queried items
print("All items in the container:")
for item in all_items:
print(item)

연결을 설정하는 또 다른 방법은 **DefaultAzureCredential()**을 사용하는 것입니다. 권한이 있는 계정으로 로그인(az login)하고 실행하기만 하면 됩니다. 이 경우 필요한 권한을 부여하는 역할 할당이 이루어져야 합니다(자세한 내용은 참조).

python
from azure.identity import DefaultAzureCredential
from azure.cosmos import CosmosClient

# Use Azure AD for authentication
credential = DefaultAzureCredential()
endpoint = "<your-account-endpoint>"
client = CosmosClient(endpoint, credential)

# Access database and container
database_name = "<mydatabase>"
container_name = "<mycontainer>"
database = client.get_database_client(database_name)
container = database.get_container_client(container_name)

# Insert a document
item = {
"id": "1",
"name": "Sample Item",
"description": "This is a test item."
}
container.create_item(item)
print("Document inserted.")

MongoDB

MongoDB NoSQL API는 JSON과 유사한 BSON(이진 JSON)을 데이터 형식으로 사용하는 문서 기반 API입니다. 이 API는 집계 기능이 있는 쿼리 언어를 제공하여 구조화된, 반구조화된 및 비구조화된 데이터 작업에 적합합니다. 서비스의 엔드포인트는 일반적으로 다음 형식을 따릅니다:

bash
mongodb://<hostname>:<port>/<database>

데이터베이스

MongoDB에서는 인스턴스 내에서 하나 이상의 데이터베이스를 생성할 수 있습니다. 각 데이터베이스는 컬렉션의 논리적 그룹으로 작용하며 리소스 조직 및 관리를 위한 경계를 제공합니다. 데이터베이스는 서로 다른 애플리케이션이나 프로젝트를 위해 데이터를 논리적으로 분리하고 관리하는 데 도움을 줍니다.

컬렉션

MongoDB에서 데이터 저장의 핵심 단위는 컬렉션으로, 문서를 보유하며 효율적인 쿼리 및 유연한 스키마 설계를 위해 설계되었습니다. 컬렉션은 탄력적으로 확장 가능하며 분산 설정에서 여러 노드에 걸쳐 높은 처리량 작업을 지원할 수 있습니다.

요청 단위(RU) 유형의 주요 기능

글로벌 분산: 지역 간 복제를 위한 Geo-Redundancy를 활성화하거나 비활성화하고 가용성을 개선하기 위한 다중 지역 쓰기를 지원합니다.
네트워킹 및 보안: 공용(모든/선택 네트워크) 또는 개인 엔드포인트 간의 연결을 지원합니다. TLS 1.2 암호화를 통한 안전한 연결을 제공합니다. 리소스에 대한 제어된 접근을 위해 CORS(교차 출처 리소스 공유)를 지원합니다. 연결을 위해 키를 사용할 수 있습니다.
백업 및 복구: 주기적, 지속적(7일, 무료) 또는 지속적(30일, 유료) 백업 정책을 통해 구성 가능한 간격 및 보존 기간으로 백업합니다.
데이터 암호화: 기본 서비스 관리 키 또는 고객 관리 키(CMK)를 통한 암호화(CMK 선택은 되돌릴 수 없습니다).

vCore 클러스터 유형의 주요 기능

글로벌 분산: 고가용성과 장애 조치를 지원하기 위해 다른 Azure 지역에 읽기 복제본을 활성화합니다. 복제본 이름, 지역 및 샤드당 저장소를 구성합니다.
네트워킹 및 보안: 할당된 공용 IP와 개인 접근을 통해 공용 접근을 지원합니다. 기본적으로 공용 IP는 허용되지 않도록 방화벽 규칙을 사용하여 연결을 제한합니다.
암호화된 연결: 안전한 데이터 전송을 위해 TLS 암호화를 시행합니다.

열거

bash
# CosmoDB Account
## List Azure Cosmos DB database accounts.
az cosmosdb list --resource-group <ResourceGroupName>
az cosmosdb show --resource-group <ResourceGroupName> --name <AccountName>

## Lists the virtual network accounts associated with a Cosmos DB account
az cosmosdb network-rule list --resource-group <ResourceGroupName> --name <AccountName>
## List the access keys or connection strings for a Azure Cosmos DB
az cosmosdb keys list --name <AccountName> --resource-group <ResourceGroupName>
## List all the database accounts that can be restored.
az cosmosdb restorable-database-account list --account-name <AccountName>
## Show the identities for a Azure Cosmos DB database account.
az cosmosdb identity show --resource-group <ResourceGroupName> --name <AccountName>

## MongoDB
# List all MongoDB databases in a specified Azure Cosmos DB account
az cosmosdb mongodb database list --account-name <AccountName> --resource-group <ResourceGroupName>
# List all collections in a specific MongoDB database within an Azure Cosmos DB account
az cosmosdb mongodb collection list --account-name <AccountName> --database-name <DatabaseName> --resource-group <ResourceGroupName>

#RBAC FUNCTIONALITIES MUST BE ENABLED TO USE THIS
# List all role definitions for MongoDB within an Azure Cosmos DB account
az cosmosdb mongodb role definition list --account-name <AccountName> --resource-group <ResourceGroupName>
# List all user definitions for MongoDB within an Azure Cosmos DB account
az cosmosdb mongodb user definition list --account-name <AccountName> --resource-group <ResourceGroupName>

## MongoDB (vCore)
# Install az cli extension
az extension add --name cosmosdb-preview
# List all MongoDB databases in a specified Azure Cosmos DB account
az cosmosdb mongocluster list
az cosmosdb mongocluster show --cluster-name <name> --resource-group <ResourceGroupName>
# Get firewall rules
az cosmosdb mongocluster firewall rule list --cluster-name <name> --resource-group <ResourceGroupName>
# Connect to in
brew install mongosh
mongosh "mongodb://<username>:<password>@<account-name>.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retryWrites=false" --username <username> --password <password>

연결

CosmoDB의 RU MongoDB 유형에는 2가지 키 유형이 있습니다: 읽기-쓰기(전체) 및 읽기 전용. 이들은 Cosmos DB 계정 내의 모든 데이터베이스, 컬렉션 및 데이터에 대한 액세스를 제공합니다. 비밀번호는 키를 사용하거나 권한 상승 섹션에 설명된 방법을 사용할 수 있습니다.

python
from pymongo import MongoClient

# Updated connection string with retryWrites=false
connection_string = "mongodb://<account-name>.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retryWrites=false"

# Create the client. The password and username is a custom one if the type is "vCore cluster".
# In case that is a Request unit (RU) the username is the account name and the password is the key of the cosomosDB account.
client = MongoClient(connection_string, username="<username>", password="<password>")

# Access the database
db = client['<database>']

# Access a collection
collection = db['<collection>']

# Insert a single document
document = {
"name": "John Doe",
"email": "johndoe@example.com",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Somewhere",
"state": "CA",
"zip": "90210"
}
}

# Insert document
result = collection.insert_one(document)
print(f"Inserted document with ID: {result.inserted_id}")

mongo 내에서 사용자를 사용하는 경우:

bash
mongosh "mongodb://<myUser>:<mySecurePassword>@<account_name>.mongo.cosmos.azure.com:10255/<mymongodatabase>?ssl=true&replicaSet=globaldb&retrywrites=false"

References

Privilege Escalation

Az - CosmosDB Privesc

Post Exploitation

Az - SQL Post Exploitation

ToDo

  • 여기 DB의 나머지, 테이블, 카산드라, 그렘린...
  • 포스트 익스플로잇 "Microsoft.DocumentDB/databaseAccounts/mongodbUserDefinitions/write" && "Microsoft.DocumentDB/databaseAccounts/mongodbUserDefinitions/read" 및 역할 정의를 살펴보세요. 여기서 권한 상승이 있을 수 있습니다.
  • 복원 살펴보기

tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기