> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oasm.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Comporre le query

> Combina batch, righe correlate, liste, filtri e conteggi in Attack Surface Query per rispondere a domande reali sulla superficie di attacco

Gli elementi di base (`select`, `include`, `where`, finestre e aggregati) si combinano liberamente. Questa pagina parte dalle domande che le persone pongono davvero e mostra lo schema dietro ogni risposta, poi un ricettario di batch completi che puoi incollare nell'API.

## Schema 1: raggruppa le domande in un batch

Metti ogni parte di una domanda in un unico batch. Le query vengono eseguite in parallelo e una query che fallisce non blocca le altre.

```json theme={null}
{
  "window": { "since": "now-7d" },
  "queries": {
    "newHosts": { "from": "hosts", "select": ["value", "kind", "target.value"] },
    "newPorts": { "from": "services", "select": ["host.value", "port", "http.title"] },
    "newFindings": { "from": "vulnerabilities", "select": ["name", "severity", "host.value"],
                     "where": { "logic": "and", "items": [{ "field": "isOpen", "op": "eq", "value": "true" }] } },
    "allTimePorts": { "from": "services", "groupBy": ["port"], "aggregate": { "n": { "fn": "count" } }, "window": null }
  }
}
```

La `window` del batch è quella predefinita; `allTimePorts` la esclude con `"window": null`.

## Schema 2: arricchisci una riga con campi correlati

Parti dalla risorsa su cui verte la domanda e recupera il contesto tramite percorsi con il punto. *"Quali certificati TLS scadono questo mese, su quale host e porta, e cosa dice il sito?"*

```json theme={null}
{ "from": "tls",
  "select": ["subjectCn", "notAfter", "daysToExpiry", "service.host.value", "service.port"],
  "where": { "logic": "and", "items": [{ "field": "notAfter", "op": "lt", "value": "now+30d" }] },
  "orderBy": [{ "field": "notAfter", "dir": "asc" }] }
```

## Schema 3: filtra su una cosa, restituiscine un'altra

`where` può verificare righe correlate e liste che il risultato non mostra. *"Servizi che eseguono WordPress su un host che ha un finding critico."*

```json theme={null}
{ "from": "services",
  "select": ["host.value", "port", "http.title"],
  "where": { "logic": "and", "items": [
    { "field": "technologies.name", "op": "eq", "value": "WordPress" },
    { "field": "host.vulnerabilities.severity", "op": "eq", "value": "critical" } ] } }
```

Un percorso di filtro può attraversare righe correlate prima e dopo una lista (`host.vulnerabilities.severity`, `services.http.title`), ma **al massimo una lista**: `services.technologies.name` a partire da `hosts` viene rifiutato. Parti invece dalla risorsa più vicina di una lista, come sopra.

> [!NOTE]
>
> Ogni condizione su una lista viene verificata separatamente: l'host ha *qualche* finding critico, non necessariamente aperto, anche se aggiungi `host.vulnerabilities.isOpen` come seconda condizione. Per legare più condizioni alla stessa riga correlata, usa un [test di relazione](https://docs.oasm.io/it/attack-surface-query/filtering.md#relation-tests) (schema 9), oppure interroga invece la risorsa di quella riga (schema 4).

## Schema 4: interroga il figlio, non il padre

Quando la domanda riguarda i figli, leggili direttamente e recupera il padre tramite un campo correlato. È anche la via d'uscita da un include troppo grande. *"Ogni servizio che esegue una versione obsoleta di nginx, con il suo host."*

```json theme={null}
{ "from": "technologies",
  "select": ["name", "version", "service.host.value", "service.port"],
  "where": { "logic": "and", "items": [
    { "field": "name", "op": "eq", "value": "nginx" },
    { "field": "version", "op": "in", "value": ["1.18.0", "1.20.1", "1.22.0"] } ] },
  "limit": 200 }
```

## Schema 5: una riga con tutto ciò che la circonda

`include` allega liste a ogni riga; annidale per scendere di due livelli. Mantieni piccolo il `limit` del padre. *"Tutto ciò che si sa di api.example.com."*

```json theme={null}
{
  "queries": {
    "host": {
      "from": "hosts",
      "select": ["value", "kind", "firstSeen", "lastSeen", "target.value"],
      "limit": 1,
      "where": { "logic": "and", "items": [{ "field": "value", "op": "eq", "value": "api.example.com" }] },
      "include": {
        "services": {
          "select": ["port", "http.title", "http.statusCode", "http.webserver"],
          "limit": 20,
          "include": { "technologies": { "select": ["name", "version"] } }
        },
        "vulnerabilities": { "select": ["name", "severity", "detectionStatus"], "limit": 20 }
      }
    },
    "ips": {
      "from": "ips",
      "select": ["ip", "source"],
      "where": { "logic": "and", "items": [{ "field": "host.value", "op": "eq", "value": "api.example.com" }] }
    }
  }
}
```

Gli IP sono una seconda query dello stesso batch invece di un terzo include: una query ha al massimo cinque include in totale (tre per l'agente AI), compresi quelli annidati.

## Schema 6: filtra i figli inclusi

Il `where` di un include limita quali figli vengono allegati, senza filtrare i padri. *"Ogni host, con solo i suoi servizi che sembrano pannelli di admin."*

```json theme={null}
{ "from": "hosts", "select": ["value"], "limit": 50,
  "include": { "services": {
    "select": ["port", "http.title"], "limit": 5,
    "where": { "logic": "and", "items": [{ "field": "http.title", "op": "contains", "value": "admin" }] } } } }
```

Per mantenere solo gli host che *hanno* un servizio del genere, aggiungi la stessa condizione al `where` del padre come percorso di lista:

```json theme={null}
{ "from": "hosts", "select": ["value"], "limit": 50,
  "where": { "logic": "and", "items": [{ "field": "services.http.title", "op": "contains", "value": "admin" }] },
  "include": { "services": {
    "select": ["port", "http.title"], "limit": 5,
    "where": { "logic": "and", "items": [{ "field": "http.title", "op": "contains", "value": "admin" }] } } } }
```

## Schema 7: elenco e conteggio insieme

Un elenco e la sua distribuzione sono due query dello stesso batch, con lo stesso filtro.

```json theme={null}
{
  "queries": {
    "critical": { "from": "vulnerabilities", "select": ["name", "cvssScore", "cve", "host.value"],
      "where": { "logic": "and", "items": [
        { "field": "isOpen", "op": "eq", "value": "true" },
        { "field": "severity", "op": "eq", "value": "critical" } ] },
      "orderBy": [{ "field": "cvssScore", "dir": "desc" }], "limit": 100 },
    "criticalPerHost": { "from": "vulnerabilities", "groupBy": ["host.value"], "aggregate": { "n": { "fn": "count" } },
      "where": { "logic": "and", "items": [
        { "field": "isOpen", "op": "eq", "value": "true" },
        { "field": "severity", "op": "eq", "value": "critical" } ] } }
  }
}
```

## Schema 8: approfondisci con gli id

Ogni riga riporta un `id`. Usalo nel batch successivo per approfondire, oppure passalo ad altre API di OASM.

```json theme={null}
{ "from": "services", "select": ["port", "http.title"],
  "where": { "logic": "and", "items": [{ "field": "host.id", "op": "in", "value": ["1396ad91-…", "e4e5c8ca-…"] }] } }
```

## Schema 9: chiedi ciò che manca

Alcune delle domande di sicurezza più utili riguardano un'assenza: un host che serve HTTP ma non HTTPS, un target senza più host, un servizio di cui nessuno ha rilevato il fingerprint. I test di relazione lo esprimono direttamente. *"Host che rispondono sulla porta 80 ma non hanno nulla sulla 443."*

```json theme={null}
{ "from": "hosts", "select": ["value", "target.value"], "limit": 100,
  "where": { "logic": "and", "items": [
    { "relation": "services", "where": { "logic": "and", "items": [{ "field": "port", "op": "eq", "value": "80" }] } },
    { "relation": "services", "quantifier": "none", "where": { "logic": "and", "items": [{ "field": "port", "op": "eq", "value": "443" }] } } ] } }
```

La stessa forma copre *tutti* (`"quantifier": "every"`: tutte le porte di un host sono porte web) e *quanti* (`"count": { "op": "gte", "value": "10" }`: host con dieci o più porte aperte).

## Schema 10: una matrice in una sola query

Quando una tabella richiede una colonna per categoria, assegna a ogni aggregato il proprio `where` invece di eseguire una query per categoria. Poi mantieni solo le righe interessanti con `having`. *"Target ordinati per finding critici e alti aperti, solo quelli che ne hanno."*

```json theme={null}
{ "from": "vulnerabilities",
  "groupBy": ["host.target.value"],
  "where": { "logic": "and", "items": [{ "field": "isOpen", "op": "eq", "value": "true" }] },
  "aggregate": {
    "critical": { "fn": "count", "where": { "logic": "and", "items": [{ "field": "severity", "op": "eq", "value": "critical" }] } },
    "high": { "fn": "count", "where": { "logic": "and", "items": [{ "field": "severity", "op": "eq", "value": "high" }] } },
    "hosts": { "fn": "countDistinct", "field": "host.id" } },
  "having": { "logic": "or", "items": [
    { "field": "critical", "op": "gt", "value": "0" },
    { "field": "high", "op": "gt", "value": "0" } ] },
  "orderBy": [{ "field": "critical", "dir": "desc" }, { "field": "high", "dir": "desc" }] }
```

## Schema 11: un grafico senza buchi

Una serie per un grafico richiede un punto per giorno, compresi i giorni senza attività, nel fuso orario di chi la guarda. `fill` e `options.timezone` danno esattamente questo. *"Nuove porte e nuovi finding al giorno negli ultimi 30 giorni, ora di Hanoi."*

```json theme={null}
{
  "window": { "since": "now-30d" },
  "options": { "timezone": "Asia/Ho_Chi_Minh" },
  "queries": {
    "ports": { "from": "services", "groupBy": [{ "field": "firstSeen", "bucket": "day" }],
               "aggregate": { "n": { "fn": "count" } }, "fill": true },
    "findings": { "from": "vulnerabilities", "groupBy": [{ "field": "firstSeen", "bucket": "day" }],
                  "aggregate": { "n": { "fn": "count" },
                                 "critical": { "fn": "count", "where": { "logic": "and", "items": [{ "field": "severity", "op": "eq", "value": "critical" }] } } },
                  "fill": true }
  }
}
```

Entrambe le serie hanno gli stessi giorni nello stesso ordine, quindi si allineano su un unico grafico.

## Ricettario

> [accordion] Target e quanti host ha ciascuno
>
> ```json theme={null}
> { "queries": {
>   "targets": { "from": "targets", "select": ["value", "type", "firstSeen"], "limit": 200 },
>   "hostsPerTarget": { "from": "hosts", "groupBy": ["target.value"], "aggregate": { "hosts": { "fn": "count" } },
>                       "orderBy": [{ "field": "hosts", "dir": "desc" }], "limit": 200 } } }
> ```

> [accordion] Nuovi domini e porte degli ultimi 5 giorni
>
> ```json theme={null}
> { "window": { "since": "now-5d" }, "queries": {
>   "domains": { "from": "hosts", "select": ["value", "firstSeen", "target.value"],
>                "where": { "logic": "and", "items": [{ "field": "kind", "op": "eq", "value": "domain" }] } },
>   "ports": { "from": "services", "select": ["host.value", "port", "http.title", "http.statusCode"] } } }
> ```

> [accordion] Servizi rischiosi esposti
>
> ```json theme={null}
> { "from": "services", "select": ["host.value", "port", "http.title"], "limit": 200,
>   "where": { "logic": "and", "items": [
>     { "field": "port", "op": "in", "value": ["21", "23", "445", "3306", "3389", "5432", "6379", "9200", "27017"] } ] } }
> ```

> [accordion] Pagine di login e di admin
>
> ```json theme={null}
> { "from": "services", "select": ["host.value", "port", "http.url", "http.title"], "limit": 100,
>   "where": { "logic": "or", "items": [
>     { "field": "http.title", "op": "contains", "value": "admin" },
>     { "field": "http.title", "op": "contains", "value": "login" },
>     { "field": "technologies.name", "op": "in", "value": ["Jenkins", "Grafana", "Kibana", "phpMyAdmin"] } ] } }
> ```

> [accordion] Host in un intervallo di rete
>
> ```json theme={null}
> { "from": "ips", "select": ["ip", "host.value", "host.target.value"],
>   "where": { "logic": "and", "items": [{ "field": "ip", "op": "inSubnet", "value": ["203.0.113.0/24", "198.51.100.0/24"] }] } }
> ```

> [accordion] Versioni delle tecnologie in uso
>
> ```json theme={null}
> { "from": "technologies", "groupBy": ["name", "version"], "aggregate": { "services": { "fn": "count" } },
>   "orderBy": [{ "field": "services", "dir": "desc" }], "limit": 50 }
> ```

> [accordion] Dove è presente una CVE
>
> ```json theme={null}
> { "from": "vulnerabilities", "select": ["name", "severity", "host.value", "affectedUrl", "detectionStatus"],
>   "where": { "logic": "and", "items": [{ "field": "cve", "op": "eq", "value": "CVE-2024-3400" }] } }
> ```

> [accordion] Host che nessuna scansione vede da 30 giorni
>
> ```json theme={null}
> { "from": "hosts", "select": ["value", "lastSeen", "target.value"], "limit": 200,
>   "where": { "logic": "and", "items": [{ "field": "lastSeen", "op": "lt", "value": "now-30d" }] },
>   "orderBy": [{ "field": "lastSeen", "dir": "asc" }] }
> ```

> [accordion] Finding per settimana per severità
>
> ```json theme={null}
> { "window": { "since": "now-90d" }, "queries": { "trend": {
>   "from": "vulnerabilities",
>   "groupBy": [{ "field": "firstSeen", "bucket": "week" }, "severity"],
>   "aggregate": { "n": { "fn": "count" } }, "limit": 100 } } }
> ```

> [accordion] Certificati in scadenza entro 30 giorni, prima i wildcard
>
> ```json theme={null}
> { "from": "tls", "select": ["subjectCn", "notAfter", "wildcard", "service.host.value", "service.port"],
>   "where": { "logic": "and", "items": [{ "field": "notAfter", "op": "between", "value": ["now", "now+30d"] }] },
>   "orderBy": [{ "field": "notAfter", "dir": "asc" }] }
> ```

> [accordion] Servizi senza risposta HTTP
>
> ```json theme={null}
> { "from": "services", "select": ["host.value", "port", "lastSeen"], "limit": 200,
>   "where": { "logic": "and", "items": [{ "field": "http.title", "op": "isNull" }, { "field": "http.statusCode", "op": "isNull" }] } }
> ```

> [accordion] Solo host di produzione (esclusi nomi dev, staging e interni)
>
> ```json theme={null}
> { "from": "hosts", "select": ["value", "target.value"], "limit": 200,
>   "where": { "logic": "and", "items": [{ "not": { "logic": "or", "items": [
>     { "field": "value", "op": "startsWith", "value": "dev" },
>     { "field": "value", "op": "startsWith", "value": "staging" },
>     { "field": "value", "op": "endsWith", "value": ".internal" } ] } }] } }
> ```

> [accordion] Finding che riportano entrambe le CVE
>
> ```json theme={null}
> { "from": "vulnerabilities", "select": ["name", "cve", "host.value"],
>   "where": { "logic": "and", "items": [{ "field": "cve", "op": "containsAll", "value": ["CVE-2024-3400", "CVE-2024-3401"] }] } }
> ```

> [accordion] Host fuori dai tuoi intervalli noti
>
> ```json theme={null}
> { "from": "ips", "select": ["ip", "host.value"], "limit": 200,
>   "where": { "logic": "and", "items": [{ "field": "ip", "op": "notInSubnet", "value": ["10.0.0.0/8", "172.16.0.0/12", "203.0.113.0/24"] }] } }
> ```

> [accordion] Record DNS che puntano a un provider
>
> ```json theme={null}
> { "from": "dnsRecords", "select": ["recordType", "value", "host.value"],
>   "where": { "logic": "and", "items": [
>     { "field": "recordType", "op": "eq", "value": "CNAME" },
>     { "field": "value", "op": "contains", "value": "cloudfront.net" } ] } }
> ```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.