# Az - CosmosDB {{#include ../../../banners/hacktricks-training.md}} ## Azure CosmosDB **Azure Cosmos DB** ist eine vollständig **verwaltete NoSQL-, relationale und Vektordatenbank**, die Reaktionszeiten im einstelligen Millisekundenbereich, automatische Skalierbarkeit und SLA-unterstützte Verfügbarkeit mit Unternehmenssicherheit bietet. Es ermöglicht eine schnellere Anwendungsentwicklung durch schlüsselfertige, mehrregionale Datenverteilung, Open-Source-APIs, SDKs für beliebte Programmiersprachen und KI-Datenbankfunktionen wie integrierte Vektorsupport und nahtlose Azure KI-Integration. Azure Cosmos DB bietet mehrere Datenbank-APIs, um reale Daten mit Dokumenten, relationalen, Schlüssel-Wert-, Graph- und Spaltenfamilien-Datenmodellen zu modellieren. Diese APIs sind NoSQL, MongoDB, PostgreSQL, Cassandra, Gremlin und Table. Ein wichtiger Aspekt von CosmosDB ist das Azure Cosmos-Konto. **Azure Cosmos-Konto** fungiert als Einstiegspunkt zu den Datenbanken. Das Konto bestimmt wichtige Einstellungen wie globale Verteilung, Konsistenzstufen und die spezifische API, die verwendet werden soll, wie z.B. NoSQL. Über das Konto können Sie die globale Replikation konfigurieren, um sicherzustellen, dass Daten in mehreren Regionen für einen latenzarmen Zugriff verfügbar sind. Darüber hinaus können Sie eine Konsistenzstufe wählen, die zwischen Leistung und Datenakkuratheit balanciert, mit Optionen von starker bis eventualer Konsistenz. Azure Cosmos DB unterstützt **benutzerzugewiesene Identitäten** und **systemzugewiesene verwaltete Identitäten**, die automatisch erstellt und an den Lebenszyklus der Ressource gebunden sind. Cosmos DB hat jedoch keinen integrierten Mechanismus, um direkt externe Datenquellen wie Azure Blob Storage abzufragen. Im Gegensatz zu den externen Tabellenfunktionen von SQL Server erfordert Cosmos DB, dass Daten mit externen Tools wie Azure Data Factory, dem Data Migration Tool oder benutzerdefinierten Skripten in seine Container aufgenommen werden, bevor sie mit den nativen Abfragefähigkeiten abgefragt werden können. ### NoSQL Die Azure Cosmos DB NoSQL-API ist eine dokumentenbasierte API, die JSON als Datenformat verwendet. Sie bietet eine SQL-ähnliche Abfragesyntax zum Abfragen von JSON-Objekten, was sie geeignet macht, um mit strukturierten und semi-strukturierten Daten zu arbeiten. Der Endpunkt des Dienstes ist: ```bash https://.documents.azure.com:443/ ``` #### Datenbanken Innerhalb eines Kontos können Sie eine oder mehrere Datenbanken erstellen, die als logische Gruppierungen von Containern dienen. Eine Datenbank fungiert als Grenze für das Ressourcenmanagement und die Benutzerberechtigungen. Datenbanken können entweder mehreren Containern einen gemeinsamen Pool von Leistungsressourcen zur Verfügung stellen oder jedem Container seine eigene dedizierte Leistung geben. #### Container Die zentrale Einheit der Datenspeicherung ist der Container, der JSON-Dokumente enthält und automatisch für effiziente Abfragen indiziert wird. Container sind elastisch skalierbar und über Partitionen verteilt, die durch einen benutzerdefinierten Partitionierungsschlüssel bestimmt werden. Der Partitionierungsschlüssel ist entscheidend für die Gewährleistung optimaler Leistung und gleichmäßiger Datenverteilung. Zum Beispiel könnte ein Container Kundendaten speichern, wobei "customerId" als Partitionierungsschlüssel dient. #### Hauptmerkmale - **Globale Verteilung**: Aktivieren oder Deaktivieren von Geo-Redundanz für die Replikation über Regionen hinweg und Multi-Regionen-Schreibvorgänge für verbesserte Verfügbarkeit. - **Netzwerk & Sicherheit**: zwischen öffentlichen (alle/ausgewählte Netzwerke) oder privaten Endpunkten für die Konnektivität. Sichere Verbindungen mit TLS 1.2-Verschlüsselung. Unterstützt CORS (Cross-Origin Resource Sharing) für kontrollierten Zugriff auf Ressourcen. Microsoft Defender für Cloud kann aktiviert werden. Um die Verbindung herzustellen, können Sie Schlüssel verwenden. - **Backup & Wiederherstellung**: von periodischen, kontinuierlichen (7 Tage) oder kontinuierlichen (30 Tage) Backup-Richtlinien mit konfigurierbaren Intervallen und Aufbewahrung. - **Datenverschlüsselung**: Standarddienstverwaltete Schlüssel oder kundenverwaltete Schlüssel (CMK) zur Verschlüsselung (CMK-Auswahl ist irreversibel). #### Aufzählung {{#tabs }} {{#tab name="az cli" }} ```bash # CosmoDB Account ## List Azure Cosmos DB database accounts. az cosmosdb list --resource-group az cosmosdb show --resource-group --name ## Lists the virtual network accounts associated with a Cosmos DB account az cosmosdb network-rule list --resource-group --name ## List the access keys or connection strings for a Azure Cosmos DB az cosmosdb keys list --name --resource-group ## List all the database accounts that can be restored. az cosmosdb restorable-database-account list --account-name ## Show the identities for a Azure Cosmos DB database account. az cosmosdb identity show --resource-group --name # CosmoDB (NoSQL) ## List the NoSQL databases under an Azure Cosmos DB account. az cosmosdb sql database list --resource-group --account-name ## List the NoSQL containers under an Azure Cosmos DB NoSQL database. az cosmosdb sql container list --account-name --database-name --resource-group ## List all NoSQL role assignments under an Azure Cosmos DB az cosmosdb sql role assignment list --resource-group --account-name ## List all NoSQL role definitions under an Azure Cosmos DB az cosmosdb sql role definition list --resource-group --account-name ## List the NoSQL stored procedures under an Azure Cosmos DB az cosmosdb sql stored-procedure list --account-name --container-name --database-name --resource-group ## List the NoSQL triggers under an Azure Cosmos DB NoSQL container. az cosmosdb sql trigger list --account-name --container-name --database-name --resource-group ## List the NoSQL user defined functions under an Azure Cosmos DB NoSQL container az cosmosdb sql user-defined-function list --account-name --container-name --database-name --resource-group ## 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 --resource-group # Get firewall rules az cosmosdb mongocluster firewall rule list --cluster-name --resource-group # Connect to in brew install mongosh mongosh "mongodb://:@.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retryWrites=false" --username --password ``` {{#endtab }} {{#tab name="Az Powershell" }} ```bash Get-Command -Module Az.CosmosD # List all Cosmos DB accounts in a specified resource group. Get-AzCosmosDBAccount -ResourceGroupName "" # Get the access keys for a specific Cosmos DB account. Get-AzCosmosDBAccountKey -ResourceGroupName "" -Name "" # Retrieve the client encryption keys for a specific Cosmos DB account. Get-AzCosmosDbClientEncryptionKey -ResourceGroupName "" -AccountName "" -DatabaseName "" # List all SQL containers in a specific Cosmos DB SQL database. Get-AzCosmosDBSqlContainer -ResourceGroupName "" -AccountName "" -DatabaseName "" # Get backup information for a specific Cosmos DB SQL container. Get-AzCosmosDBSqlContainerBackupInformation -ResourceGroupName "" -AccountName "" -DatabaseName "" -Name "" -Location "" # Get the throughput (RU/s) settings for a specific Cosmos DB SQL container. Get-AzCosmosDBSqlContainerThroughput -ResourceGroupName "" -AccountName "" -DatabaseName "" -Name "" # List all SQL databases under a specific Cosmos DB account. Get-AzCosmosDBSqlDatabase -ResourceGroupName "" -AccountName "" # Get the throughput (RU/s) settings for a specific Cosmos DB SQL database. Get-AzCosmosDBSqlDatabaseThroughput -ResourceGroupName "" -AccountName "" -Name "" # List all SQL role assignments for a specific Cosmos DB account. Get-AzCosmosDBSqlRoleAssignment -ResourceGroupName "" -AccountName "" # List all SQL role definitions for a specific Cosmos DB account. Get-AzCosmosDBSqlRoleDefinition -ResourceGroupName "" -AccountName "" # List all stored procedures in a specific Cosmos DB SQL container. Get-AzCosmosDBSqlStoredProcedure -ResourceGroupName "" -AccountName "" -DatabaseName "" -ContainerName "" # List all triggers in a specific Cosmos DB SQL container. Get-AzCosmosDBSqlTrigger -ResourceGroupName "" -AccountName "" -DatabaseName "" -ContainerName "" # List all user-defined functions (UDFs) in a specific Cosmos DB SQL container. Get-AzCosmosDBSqlUserDefinedFunction -ResourceGroupName "" -AccountName "" -DatabaseName "" -ContainerName "" ``` {{#endtab }} {{#endtabs }} #### Verbindung Es gibt 2 Schlüsseltypen, Lese-Schreib (voll) und Nur-Lesen. Sie gewähren den angegebenen Zugriff auf alle Datenbanken, Sammlungen und Daten innerhalb des Cosmos DB-Kontos. Um sich zu verbinden, wird die azure-cosmosDB-Bibliothek (pip install azure-cosmos) benötigt. Darüber hinaus sind der Endpunkt und der Schlüssel entscheidende Komponenten, um die Verbindung herzustellen. ```python from azure.cosmos import CosmosClient, PartitionKey # Connection details endpoint = "" key = "" # Initialize Cosmos Client client = CosmosClient(endpoint, key) # Access existing database and container database_name = '' container_name = '' 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) ``` Eine weitere Möglichkeit, eine Verbindung herzustellen, besteht darin, **DefaultAzureCredential()** zu verwenden. Es muss sich nur mit dem Konto angemeldet werden (az login), das die Berechtigungen hat, und es auszuführen. In diesem Fall muss eine Rollen zuweisung vorgenommen werden, um die erforderlichen Berechtigungen zu gewähren (siehe für mor) ```python from azure.identity import DefaultAzureCredential from azure.cosmos import CosmosClient # Use Azure AD for authentication credential = DefaultAzureCredential() endpoint = "" client = CosmosClient(endpoint, credential) # Access database and container database_name = "" container_name = "" 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 Die MongoDB NoSQL-API ist eine dokumentenbasierte API, die JSON-ähnliches BSON (Binary JSON) als Datenformat verwendet. Sie bietet eine Abfragesprache mit Aggregationsfähigkeiten, die sie für die Arbeit mit strukturierten, semi-strukturierten und unstrukturierten Daten geeignet macht. Der Endpunkt des Dienstes folgt typischerweise diesem Format: ```bash mongodb://:/ ``` #### Datenbanken In MongoDB können Sie eine oder mehrere Datenbanken innerhalb einer Instanz erstellen. Jede Datenbank dient als logische Gruppierung von Sammlungen und bietet eine Grenze für die Organisation und Verwaltung von Ressourcen. Datenbanken helfen, Daten logisch zu trennen und zu verwalten, beispielsweise für verschiedene Anwendungen oder Projekte. #### Sammlungen Die zentrale Einheit der Datenspeicherung in MongoDB ist die Sammlung, die Dokumente enthält und für effiziente Abfragen sowie flexibles Schema-Design konzipiert ist. Sammlungen sind elastisch skalierbar und können hochgradig durchsatzstarke Operationen über mehrere Knoten in einer verteilten Umgebung unterstützen. #### Hauptmerkmale des Request Unit (RU) Typs **Globale Verteilung**: Aktivieren oder Deaktivieren von Geo-Redundanz für die Replikation über Regionen hinweg und Multi-Region-Schreibvorgänge für verbesserte Verfügbarkeit. **Netzwerk & Sicherheit**: zwischen öffentlichen (alle/ausgewählte Netzwerke) oder privaten Endpunkten für die Konnektivität. Sichere Verbindungen mit TLS 1.2-Verschlüsselung. Unterstützt CORS (Cross-Origin Resource Sharing) für kontrollierten Zugriff auf Ressourcen. Um die Verbindung herzustellen, können Sie Schlüssel verwenden. **Backup & Wiederherstellung**: von periodischen, kontinuierlichen (7 Tage, kostenlos) oder kontinuierlichen (30 Tage, kostenpflichtig) Backup-Richtlinien mit konfigurierbaren Intervallen und Aufbewahrung. **Datenverschlüsselung**: Standardmäßig verwaltete Dienstschlüssel oder vom Kunden verwaltete Schlüssel (CMK) zur Verschlüsselung (CMK-Auswahl ist irreversibel). #### Hauptmerkmale des vCore-Cluster-Typs **Globale Verteilung**: Aktivieren Sie ein Lese-Replica in einer anderen Azure-Region für hohe Verfügbarkeit und Failover-Unterstützung. Konfigurieren Sie den Replikatnamen, die Region und den Speicher pro Shard. **Netzwerk & Sicherheit**: Unterstützt den öffentlichen Zugriff mit zugewiesenen öffentlichen IPs und privaten Zugriff. Beschränken Sie Verbindungen mithilfe von Firewall-Regeln – standardmäßig sind keine öffentlichen IPs erlaubt. **Verschlüsselte Verbindungen**: Erzwingt TLS-Verschlüsselung für sichere Datenübertragung. #### Aufzählung {{#tabs }} {{#tab name="az cli" }} ```bash # CosmoDB Account ## List Azure Cosmos DB database accounts. az cosmosdb list --resource-group az cosmosdb show --resource-group --name ## Lists the virtual network accounts associated with a Cosmos DB account az cosmosdb network-rule list --resource-group --name ## List the access keys or connection strings for a Azure Cosmos DB az cosmosdb keys list --name --resource-group ## List all the database accounts that can be restored. az cosmosdb restorable-database-account list --account-name ## Show the identities for a Azure Cosmos DB database account. az cosmosdb identity show --resource-group --name ## MongoDB # List all MongoDB databases in a specified Azure Cosmos DB account az cosmosdb mongodb database list --account-name --resource-group # List all collections in a specific MongoDB database within an Azure Cosmos DB account az cosmosdb mongodb collection list --account-name --database-name --resource-group #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 --resource-group # List all user definitions for MongoDB within an Azure Cosmos DB account az cosmosdb mongodb user definition list --account-name --resource-group ## 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 --resource-group # Get firewall rules az cosmosdb mongocluster firewall rule list --cluster-name --resource-group # Connect to in brew install mongosh mongosh "mongodb://:@.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retryWrites=false" --username --password ``` {{#endtab }} {{#tab name="Az Powershell" }} ```bash Get-Command -Module Az.CosmosDB # List all Cosmos DB accounts in a specified resource group. Get-AzCosmosDBAccount -ResourceGroupName "" # Get the access keys for a specific Cosmos DB account. Get-AzCosmosDBAccountKey -ResourceGroupName "" -Name "" # Retrieve the client encryption keys for a specific Cosmos DB account. Get-AzCosmosDbClientEncryptionKey -ResourceGroupName "" -AccountName "" -DatabaseName "" # List all MongoDB collections in a specific database. Get-AzCosmosDBMongoDBCollection -AccountName -ResourceGroupName -DatabaseName # Retrieve backup information for a specific MongoDB collection in a database. Get-AzCosmosDBMongoDBCollectionBackupInformation -AccountName -ResourceGroupName -DatabaseName -Name -Location # Get the throughput (RU/s) of a specific MongoDB collection in a database. Get-AzCosmosDBMongoDBCollectionThroughput -AccountName -ResourceGroupName -DatabaseName -Name # List all MongoDB databases in a specified Cosmos DB account. Get-AzCosmosDBMongoDBDatabase -AccountName -ResourceGroupName # Get the throughput (RU/s) of a specific MongoDB database. Get-AzCosmosDBMongoDBDatabaseThroughput -AccountName -ResourceGroupName -DatabaseName # Retrieve the role definitions for MongoDB users in a specified Cosmos DB account. Get-AzCosmosDBMongoDBRoleDefinition -AccountName -ResourceGroupName ``` {{#endtab }} {{#endtabs }} #### Verbindung Der RU MongoDB-Typ in CosmoDB hat 2 Schlüsseltypen, Lese-Schreib (voll) und Nur-Lesen. Sie gewähren den angegebenen Zugriff auf alle Datenbanken, Sammlungen und Daten innerhalb des Cosmos DB-Kontos. Für das Passwort können Sie die Schlüssel oder die im Privesc-Abschnitt beschriebene Methode verwenden. ```python from pymongo import MongoClient # Updated connection string with retryWrites=false connection_string = "mongodb://.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="", password="") # Access the database db = client[''] # Access a collection collection = db[''] # 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}") ``` Oder einen Benutzer innerhalb des mongo verwenden: ```bash mongosh "mongodb://:@.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false" ``` ## Referenzen - [https://learn.microsoft.com/en-us/azure/cosmos-db/choose-api](https://learn.microsoft.com/en-us/azure/cosmos-db/choose-api) - [https://learn.microsoft.com/en-us/azure/cosmos-db/](https://learn.microsoft.com/en-us/azure/cosmos-db/) - [https://learn.microsoft.com/en-us/azure/cosmos-db/introduction](https://learn.microsoft.com/en-us/azure/cosmos-db/introduction) - [https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/security/how-to-grant-data-plane-role-based-access?tabs=built-in-definition%2Ccsharp&pivots=azure-interface-cli](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/security/how-to-grant-data-plane-role-based-access?tabs=built-in-definition%2Ccsharp&pivots=azure-interface-cli) ## Privilegieneskalation {{#ref}} ../az-privilege-escalation/az-cosmosDB-privesc.md {{#endref}} ## Post-Exploitation {{#ref}} ../az-post-exploitation/az-sql-post-exploitation.md {{#endref}} ## ToDo * Der Rest der DB hier, Tabellen, Cassandra, Gremlin... * Einen Blick auf die Post-Exploitation "Microsoft.DocumentDB/databaseAccounts/mongodbUserDefinitions/write" && "Microsoft.DocumentDB/databaseAccounts/mongodbUserDefinitions/read" und Rollendefinitionen werfen, da hier möglicherweise eine Privilegieneskalation vorliegt * Einen Blick auf Wiederherstellungen werfen {{#include ../../../banners/hacktricks-training.md}}