> ## 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.

# Составление запросов

> Комбинируйте пакеты, связанные строки, списки, фильтры и подсчёты в Attack Surface Query, чтобы отвечать на реальные вопросы о поверхности атаки

Базовые элементы — `select`, `include`, `where`, окна и агрегаты — свободно комбинируются. Эта страница начинает с вопросов, которые задают на практике, и показывает шаблон, стоящий за каждым ответом, а затем приводит сборник готовых пакетов, которые можно вставить в API.

## Шаблон 1: объединяйте вопросы в пакет

Поместите все части вопроса в один пакет. Запросы выполняются параллельно, и ошибка в одном не останавливает остальные.

```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 }
  }
}
```

`window` пакета задаёт значение по умолчанию; `allTimePorts` отказывается от него через `"window": null`.

## Шаблон 2: расширяйте строку связанными полями

Начните с ресурса, о котором вопрос, и подтяните контекст через пути с точками. *«Какие TLS-сертификаты истекают в этом месяце, на каком хосте и порту и что пишет сайт?»*

```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" }] }
```

## Шаблон 3: фильтруйте по одному, возвращайте другое

`where` может проверять связанные строки и списки, которых нет в результате. *«Сервисы с WordPress на хосте, у которого есть критическая находка».*

```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" } ] } }
```

Путь фильтра может проходить через связанные строки до и после списка (`host.vulnerabilities.severity`, `services.http.title`), но не более чем через **один список**: `services.technologies.name` от `hosts` отклоняется. Вместо этого начните с ресурса на один список ближе, как выше.

> [!NOTE]
>
> Каждое условие по списку проверяется отдельно: у хоста есть *какая-то* критическая находка, не обязательно открытая, даже если добавить `host.vulnerabilities.isOpen` вторым условием. Чтобы привязать несколько условий к одной и той же связанной строке, используйте [проверку связи](https://docs.oasm.io/ru/attack-surface-query/filtering.md#relation-tests) (шаблон 9) или запрашивайте ресурс этой строки (шаблон 4).

## Шаблон 4: запрашивайте дочерние строки, а не родителя

Когда вопрос о дочерних строках, читайте их напрямую и подтягивайте родителя через связанное поле. Это же выход из слишком большого include. *«Все сервисы с устаревшим nginx и их хосты».*

```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 }
```

## Шаблон 5: одна строка со всем, что вокруг неё

`include` прикрепляет списки к каждой строке; вложите их, чтобы спуститься на два уровня. Держите `limit` родителя небольшим. *«Всё, что известно об 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" }] }
    }
  }
}
```

IP-адреса вынесены во второй запрос того же пакета, а не в третий include: в запросе может быть не более пяти include в сумме (три для ИИ-агента), включая вложенные.

## Шаблон 6: фильтруйте прикреплённые дочерние строки

Собственный `where` у include ограничивает, какие дочерние строки прикрепляются, не фильтруя родителей. *«Все хосты, но только с сервисами, похожими на админку».*

```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" }] } } } }
```

Чтобы оставить только хосты, у которых *есть* такой сервис, добавьте то же условие в `where` родителя как путь через список:

```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" }] } } } }
```

## Шаблон 7: список и подсчёт вместе

Список и его распределение — два запроса одного пакета с одинаковым фильтром.

```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" } ] } }
  }
}
```

## Шаблон 8: продолжайте по id

Каждая строка содержит `id`. Используйте его в следующем пакете, чтобы углубиться, или передайте в другие API OASM.

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

## Шаблон 9: спрашивайте о том, чего нет

Одни из самых полезных вопросов безопасности — об отсутствии: хост, который отдаёт HTTP, но не HTTPS, цель без единого оставшегося хоста, сервис, который никто не идентифицировал. Проверки связей выражают это напрямую. *«Хосты, которые отвечают на порту 80, но ничего не имеют на 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" }] } } ] } }
```

Та же форма покрывает *все* (`"quantifier": "every"`: все порты хоста — веб-порты) и *сколько* (`"count": { "op": "gte", "value": "10" }`: хосты с десятью и более открытыми портами).

## Шаблон 10: матрица в одном запросе

Когда таблице нужен столбец на каждую категорию, задайте каждому агрегату собственный `where` вместо отдельного запроса на категорию. Затем оставьте только интересные строки через `having`. *«Цели, ранжированные по открытым критическим и высоким находкам, только те, где они есть».*

```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" }] }
```

## Шаблон 11: график без пропусков

Серии для графика нужна одна точка на день, включая тихие дни, в часовом поясе зрителя. `fill` и `options.timezone` дают именно это. *«Новые порты и новые находки по дням за последние 30 дней по времени Ханоя».*

```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 }
  }
}
```

Обе серии содержат одни и те же дни в одном порядке, поэтому совпадают на одном графике.

## Сборник рецептов

> [accordion] Цели и количество хостов у каждой
>
> ```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] Новые домены и порты за последние 5 дней
>
> ```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] Открытые рискованные сервисы
>
> ```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] Страницы входа и админки
>
> ```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] Хосты в диапазоне сети
>
> ```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] Используемые версии технологий
>
> ```json theme={null}
> { "from": "technologies", "groupBy": ["name", "version"], "aggregate": { "services": { "fn": "count" } },
>   "orderBy": [{ "field": "services", "dir": "desc" }], "limit": 50 }
> ```

> [accordion] Где присутствует 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] Хосты, которые ни одно сканирование не видело 30 дней
>
> ```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] Находки по неделям и критичности
>
> ```json theme={null}
> { "window": { "since": "now-90d" }, "queries": { "trend": {
>   "from": "vulnerabilities",
>   "groupBy": [{ "field": "firstSeen", "bucket": "week" }, "severity"],
>   "aggregate": { "n": { "fn": "count" } }, "limit": 100 } } }
> ```

> [accordion] Сертификаты, истекающие в течение 30 дней, сначала 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] Сервисы без 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] Только продакшен-хосты (без dev, staging и внутренних имён)
>
> ```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] Находки, содержащие оба из двух 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] Хосты вне известных вам диапазонов
>
> ```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] DNS-записи, указывающие на провайдера
>
> ```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.