From a92cfb0e44b104a4f56bdee2236a7cfba1af5a5c Mon Sep 17 00:00:00 2001 From: "gabriel.alves" Date: Mon, 29 Jun 2026 14:49:07 -0300 Subject: [PATCH] Add monitoring and calibration guide for Bot Manager - Introduced a new guide on how to monitor and calibrate Bot Manager, detailing steps for enabling logging, reading logs, interpreting traffic classifications, and setting thresholds. - Updated existing documentation in English and Portuguese to include links to the new guide. - Added sections on monitoring and calibration in relevant Bot Manager documentation. --- src/content/docs/en/pages/guides/index.mdx | 1 + .../edge-firewall/azion-bot-manager.mdx | 10 +- .../manage-bots.mdx | 8 + .../monitor-and-calibrate-bot-manager.mdx | 449 ++++++++++++++++++ src/content/docs/pt-br/pages/guias/guides.mdx | 1 + .../edge-firewall/azion-bot-manager.mdx | 8 + .../gerenciar-bots.mdx | 8 + .../monitorar-e-calibrar-bot-manager.mdx | 449 ++++++++++++++++++ 8 files changed, 933 insertions(+), 1 deletion(-) create mode 100644 src/content/docs/en/pages/secure-journey/firewall-advanced-configurations/monitor-and-calibrate-bot-manager.mdx create mode 100644 src/content/docs/pt-br/pages/secure-jornada/firewall-configuracoes-avancadas/monitorar-e-calibrar-bot-manager.mdx diff --git a/src/content/docs/en/pages/guides/index.mdx b/src/content/docs/en/pages/guides/index.mdx index aa14eef055..fa43758f1b 100644 --- a/src/content/docs/en/pages/guides/index.mdx +++ b/src/content/docs/en/pages/guides/index.mdx @@ -159,6 +159,7 @@ permalink: /documentation/products/guides/ - [Creating Blacklists of IP Addresses in Edge, using Azion Network Shield](/en/documentation/products/guides/blocklists-ip-addresses-edge/) - [Protect restricted content from improper access with Azion Secure Token](/en/documentation/products/guides/secure-token/) - [Paywall with Function JWT](/en/documentation/products/guides/paywall-function-jwt/) +- [How to monitor and calibrate Bot Manager](/en/documentation/products/guides/secure/monitor-and-calibrate-bot-manager/) --- diff --git a/src/content/docs/en/pages/main-menu/reference/secure/edge-firewall/azion-bot-manager.mdx b/src/content/docs/en/pages/main-menu/reference/secure/edge-firewall/azion-bot-manager.mdx index 83dd056255..c85bdc2a93 100644 --- a/src/content/docs/en/pages/main-menu/reference/secure/edge-firewall/azion-bot-manager.mdx +++ b/src/content/docs/en/pages/main-menu/reference/secure/edge-firewall/azion-bot-manager.mdx @@ -455,4 +455,12 @@ This setup ensures that all access to the `/api/submit` endpoint goes through AL ### Custom rules -Azion will provide you with easy-to-go configurations, that should be enough for most of the cases. If you need a more detailed configuration, you can add new custom rules based on your business needs. It's also possible to add more criteria and behaviors to be executed by the [Rules Engine](/en/documentation/products/secure/firewall/rules-engine/), building more comprehensive responses to possible attacks. +Azion will provide you with easy-to-go configurations, that should be enough for most of the cases. If you need a more detailed configuration, you can add new custom rules based on your business needs. It's also possible to add more criteria and behaviors to be executed by the [Rules Engine](/en/documentation/products/secure/firewall/rules-engine/), building more comprehensive responses to possible attacks. + +--- + +## Monitoring and calibration + +After deploying Bot Manager, use the observability tools to read logs, interpret traffic classifications, and tune thresholds and rules to reduce false positives while blocking real threats. + + diff --git a/src/content/docs/en/pages/secure-journey/firewall-advanced-configurations/manage-bots.mdx b/src/content/docs/en/pages/secure-journey/firewall-advanced-configurations/manage-bots.mdx index eb5f032663..cd120e6274 100644 --- a/src/content/docs/en/pages/secure-journey/firewall-advanced-configurations/manage-bots.mdx +++ b/src/content/docs/en/pages/secure-journey/firewall-advanced-configurations/manage-bots.mdx @@ -71,6 +71,14 @@ You can query the [Bot Manager dataset](/en/documentation/products/guides/query- To set up an function, follow the steps in [Setting up the function](/en/documentation/products/guides/bot-manager-lite/#setting-up-the-function). Then, you can use [Data Stream](/en/documentation/products/observe/data-stream/) to integrate with stream processing, SIEM, and big data platforms by using the **Functions** source and the **Functions Event Collector** template. This way, you can send your logs to the connector you use and monitor Bot Manager events. + +--- + +## Monitoring and calibration + +After configuring Bot Manager, use the observability tools to read logs, interpret traffic classifications, and tune thresholds and rules to reduce false positives while blocking real threats. + +

--- diff --git a/src/content/docs/en/pages/secure-journey/firewall-advanced-configurations/monitor-and-calibrate-bot-manager.mdx b/src/content/docs/en/pages/secure-journey/firewall-advanced-configurations/monitor-and-calibrate-bot-manager.mdx new file mode 100644 index 0000000000..72d268531e --- /dev/null +++ b/src/content/docs/en/pages/secure-journey/firewall-advanced-configurations/monitor-and-calibrate-bot-manager.mdx @@ -0,0 +1,449 @@ +--- +title: How to monitor and calibrate Bot Manager +description: >- + Learn how to read Bot Manager logs, interpret traffic classifications, and + tune thresholds and rules to reduce false positives and block real threats. +meta_tags: 'bot manager, bot protection, logs, calibration, tuning, real-time events, graphql, firewall' +namespace: docs_guides_secure_monitor_calibrate_bot_manager +permalink: /documentation/products/guides/secure/monitor-and-calibrate-bot-manager/ +--- + +import LinkButton from 'azion-webkit/linkbutton' +import Tag from 'primevue/tag' + +After deploying [Bot Manager](/en/documentation/products/secure/firewall/bot-manager/), the next step is to understand what the data tells you and adjust the configuration to match your application's traffic patterns. This guide walks you through reading logs, interpreting classifications, and calibrating thresholds and rules to reduce false positives while blocking real threats. + +:::note +Bot Manager is a Firewall add-on. Contact the [Sales team](https://www.azion.com/en/contact-sales/) for subscription details. If you're using [Bot Manager Lite](/en/documentation/products/guides/bot-manager-lite/), the same observability tools apply, though some advanced configuration options differ. +::: + +--- + +## Prerequisites + +- [Bot Manager configured in a Firewall](/en/documentation/products/secure/firewall/bot-manager/) + +--- + +## Step 1: Enable full logging + +Before you can calibrate Bot Manager, you need complete visibility into every request it evaluates. By default, Bot Manager only writes logs for requests that exceed the threshold. To observe all traffic—including legitimate requests—set the action to `allow` and enable internal logs during the observation phase. + +In your Firewall, go to **Functions Instances**, select your Bot Manager instance, and update the **JSON Args**: + +```json +{ + "action": "allow", + "internal_logs": 2, + "log_tag": "bot_manager_calibration", + "log_headers": [ + "accept", + "accept-encoding", + "accept-language", + "content-type", + "host", + "referer", + "user-agent", + "x-forwarded-for", + "x-request-id" + ] +} +``` + +| Field | Purpose | +|-------|---------| +| `action: allow` | Lets all requests pass while you observe traffic patterns | +| `internal_logs: 2` | Writes a report log for every request, regardless of score | +| `log_tag` | Labels logs so you can filter them in Real-Time Events | +| `log_headers` | Captures request headers for deeper analysis | + +:::tip +Run in observation mode for at least 24–72 hours to capture representative traffic patterns, including peak hours, crawlers, and scheduled jobs. +::: + +--- + +## Step 2: Read logs in Real-Time Events + +[Real-Time Events](/en/documentation/products/observe/real-time-events/) is the fastest way to inspect individual Bot Manager decisions. + +1. Access [Azion Console](https://console.azion.com) > **Real-Time Events**. +2. Select the **Functions** data source. +3. Set the **Time Filter** to the period you want to analyze. +4. In the search bar, filter by your log tag: + +``` +log_tag = "bot_manager_calibration" +``` + +Each log entry is a JSON object. The key fields to focus on during calibration are: + +| Field | What it tells you | +|-------|-------------------| +| `classified` | Final verdict: `legitimate`, `good bot`, `bad bot`, or `under evaluation` | +| `bot_category` | The specific threat type or bot type detected | +| `score` | Numeric score assigned to the request | +| `action` | Action Bot Manager took (or would take if threshold were active) | +| `matched_rules` | IDs of static rules that fired and contributed to the score | +| `disabled_matched_rules` | IDs of disabled rules that matched (don't affect score) | +| `azion_fingerprint` | Device fingerprint hash—useful for tracking repeat offenders | +| `remote_addr` | Source IP address | +| `http_user_agent` | User-Agent string sent in the request | +| `request_uri` | The path that was requested | + +### Example log entry + +```json +{ + "action": "allow", + "classified": "bad bot", + "bot_category": "Bad Bot Signatures", + "score": 14, + "matched_rules": [10, 22], + "azion_fingerprint": "5f852499202f7fa889157ce8b39a613b", + "remote_addr": "203.0.113.42", + "http_user_agent": "python-requests/2.28.0", + "request_uri": "/api/v1/products", + "geoip_country": "United States", + "log_tag": "bot_manager_calibration" +} +``` + +**Reading this log**: A request from IP `203.0.113.42` using a Python HTTP library was scored `14` and classified as `bad bot` with category `Bad Bot Signatures`. Rules `10` and `22` fired. The action was `allow` because you're in observation mode—once you set a threshold below `14`, this request would be blocked. + +--- + +## Step 3: Interpret traffic classifications + +Bot Manager assigns every request one of four classifications: + +| Classification | Meaning | Recommended action | +|----------------|---------|-------------------| +| `legitimate` | Regular user traffic with no bot signals | No action needed | +| `good bot` | Known, trusted bots (search engines, monitors) | Verify the bot category; consider allowing explicitly | +| `bad bot` | Confirmed malicious or suspicious automation | Block or challenge once threshold is set | +| `under evaluation` | Insufficient fingerprint data to classify | Monitor; classification resolves within 15 minutes | + +### Understanding "under evaluation" + +When a new fingerprint appears, Bot Manager needs up to 15 minutes to consolidate enough data to classify it confidently. During this window, requests are marked `under evaluation`. This is expected behavior—it prevents premature blocking of legitimate new visitors. If you see a high volume of `under evaluation` traffic, it may indicate: + +- A large influx of new users (expected after a campaign or launch). +- Rotating IPs or User-Agents (a bot evasion technique worth investigating). + +### Good bot categories to recognize + +| Bot category | Examples | +|-------------|---------| +| `Search Engine Bot` | Googlebot, Bingbot, DuckDuckBot | +| `Monitoring Bot` | UptimeRobot, Pingdom, StatusCake | +| `Social Network Bot` | Facebookbot, Twitterbot | +| `Aggregator Bot` | Feedly, news aggregators | +| `Enterprise Bot` | Internal crawlers, partner integrations | + +If you see legitimate good bots being scored high, check whether their User-Agents are correctly recognized. You may need to add them to an exclusion rule. + +--- + +## Step 4: Analyze patterns with GraphQL + +For aggregate analysis across large volumes of traffic, use the [GraphQL API](/en/documentation/devtools/graphql-api/overview/) to query the `botManagerMetrics` dataset. + +### Query: traffic breakdown by classification and category + +Access the GraphiQL Playground at `https://api.azion.com/v4/metrics/graphql` and run: + +```graphql +query { + botManagerMetrics( + filter: { + tsRange: { + begin: "2024-10-01T00:00:00" + end: "2024-10-03T23:59:59" + } + } + aggregate: { + sum: requests + } + orderBy: [sum_DESC] + groupBy: [classified, botCategory, action] + limit: 10000 + ) { + classified + botCategory + action + sum + } +} +``` + +This query returns the total request count grouped by classification, category, and action—giving you a clear picture of your traffic composition. + +### Query: top URLs impacted by bad bots + +Use the `botManagerBreakdownMetrics` dataset to identify which endpoints are most targeted: + +```graphql +query { + botManagerBreakdownMetrics( + filter: { + tsRange: { + begin: "2024-10-01T00:00:00" + end: "2024-10-03T23:59:59" + } + } + aggregate: { + sum: botRequests + } + groupBy: [requestUrl] + orderBy: [sum_DESC] + limit: 10 + ) { + requestUrl + sum + } +} +``` + +If your login endpoint (`/api/auth/login`) or checkout path (`/checkout`) appears at the top, those are high-priority targets for stricter rules. + + +
+ + +--- + +## Step 5: Monitor with Real-Time Metrics dashboards + +[Real-Time Metrics](/en/documentation/products/observe/real-time-metrics/#bot-manager) provides pre-built dashboards for Bot Manager with two sections: + +### Overview section + +| Chart | What to look for | +|-------|-----------------| +| **Bad Bot Hits** | Spike indicates an active attack campaign | +| **Good Bot Hits** | Sudden drop may mean legitimate crawlers are being blocked | +| **Bot Traffic** | Ratio of legitimate vs. bad bot vs. under evaluation traffic | +| **Top Bot Action** | Distribution of actions taken (allow, deny, redirect, etc.) | +| **Bot CAPTCHA** | Challenge solve rate—low rates may indicate real bots | + +### Breakdown section + +| Chart | What to look for | +|-------|-----------------| +| **Top Bot Classifications** | Which attack types are most prevalent | +| **Bot Activity Map** | Geographic origin of attacks | +| **Top Impacted URLs** | Endpoints receiving the most bot traffic | +| **Top Bad Bot IPs** | Repeat offenders to add to network lists | + + + +--- + +## Step 6: Set and calibrate the threshold + +The `threshold` parameter is the most critical calibration lever. It defines the maximum score a request can reach before Bot Manager executes the configured action. + +### How scoring works + +Each static rule that fires adds points to the request score. The total score determines whether the request is blocked. A score of `0` means no rules matched; higher scores indicate more suspicious signals. + +### Choosing an initial threshold + +Start with a conservative (high) threshold and lower it gradually as you gain confidence in the data: + +| Threshold | Behavior | +|-----------|---------| +| `Infinity` (default) | All requests pass; no blocking occurs | +| `18` | Recommended starting point for most applications | +| `10–15` | Stricter; suitable for high-value endpoints like login or payment | +| `5–9` | Very strict; may produce false positives on unusual-but-legitimate traffic | +| `0` | Blocks all requests (use only for testing) | + +### Calibration workflow + +1. **Observe** (days 1–3): Run with `action: allow` and `internal_logs: 2`. Collect score distributions. +2. **Identify the score gap**: Find the score range where bad bots cluster vs. where legitimate traffic sits. The threshold should sit between these two clusters. +3. **Set threshold**: Update JSON Args with your chosen threshold and a blocking action. +4. **Monitor false positives**: Watch for legitimate traffic being blocked. Check `classified: legitimate` entries with scores near your threshold. +5. **Adjust**: Lower the threshold if too many bad bots pass; raise it if legitimate users are blocked. + +### Example: setting the threshold after observation + +After 48 hours of observation, your GraphQL data shows: + +- Legitimate traffic: scores between `0–8` +- Bad bots: scores between `15–30` +- A small cluster of ambiguous traffic: scores `9–14` + +Set the threshold to `15` to block confirmed bad bots while allowing the ambiguous cluster to pass for further observation: + +```json +{ + "threshold": 15, + "action": "deny", + "log_tag": "bot_manager_production", + "mode": "web", + "dynamic_rules_tolerance": "soft", + "reputation_network_lists": [], + "disabled_static_rules": [], + "log_headers": [ + "accept", + "accept-encoding", + "accept-language", + "content-type", + "host", + "referer", + "user-agent", + "x-forwarded-for", + "x-request-id" + ] +} +``` + +--- + +## Step 7: Tune static rules + +Static rules are predefined detection patterns. Each rule has an ID and contributes a fixed number of points to the request score when matched. You can disable specific rules that generate false positives without removing them from the detection engine. + +### Identifying problematic rules + +In Real-Time Events, filter for `classified: legitimate` entries that have a high score. Check the `matched_rules` array to identify which rule IDs are firing on legitimate traffic. + +For example, if rule `22` consistently fires on your internal monitoring tool's requests: + +```json +{ + "disabled_static_rules": [22] +} +``` + +Disabled rules still appear in `disabled_matched_rules` in the logs, so you can track their matches without affecting the score. + +:::tip +Disable rules conservatively. Each disabled rule reduces detection coverage. If a rule fires on both legitimate and malicious traffic, consider using a Rules Engine exclusion instead of disabling the rule globally. +::: + +--- + +## Step 8: Configure dynamic rules + +Dynamic rules use behavioral analysis to detect anomalies that static rules may miss. They adapt to your application's traffic baseline over time. + +### Dynamic rules parameters + +| Parameter | Default | Description | +|-----------|---------|-------------| +| `disable_dynamic_rules` | `false` | Set to `true` to disable dynamic rules entirely | +| `dynamic_rules_tolerance` | `soft` | Detection strictness: `soft`, `medium`, or `hard` | +| `dynamic_rules_baseline` | `0` | Fine-tune the baseline. Negative values = stricter; positive = more lenient | + +### Choosing tolerance + +| Tolerance | When to use | +|-----------|------------| +| `soft` | Starting point; least likely to produce false positives | +| `medium` | After validating `soft` produces no false positives | +| `hard` | High-security environments with well-understood traffic patterns | + +### Enabling dynamic rules debug logs + +During calibration, enable debug logs to understand dynamic rule decisions: + +```json +{ + "dynamic_rules_logs_enabled": true +} +``` + +:::note +Disable `dynamic_rules_logs_enabled` in production. Debug logs increase log volume significantly and are intended for calibration only. +::: + +--- + +## Step 9: Exclude static assets from bot analysis + +Bot Manager should not analyze requests for static files (images, CSS, JavaScript). These requests are never bots and add unnecessary processing overhead. Configure a Rules Engine rule to skip Bot Manager for static assets. + +In your Firewall's **Rules Engine**, create a rule with the following criteria: + +- **Criteria**: `Request URI` **does not match** the regex: + +``` +\.(png|jpg|jpeg|gif|ico|css|js|svg|woff|woff2|ttf|eot|otf|webp|avif|mp4|webm|pdf)(\?.*)?$ +``` + +- **Behavior**: `Run Function` > select your Bot Manager instance. + +This ensures Bot Manager only runs on dynamic requests, reducing noise in your logs and improving accuracy. + +--- + +## Step 10: Protect high-value endpoints with stricter rules + +Different endpoints have different risk profiles. Use multiple Bot Manager instances with different thresholds to apply stricter protection where it matters most. + +| Endpoint type | Recommended threshold | Recommended action | +|--------------|----------------------|-------------------| +| Login / authentication | `10` | `redirect` (to CAPTCHA) | +| Payment / checkout | `10` | `deny` | +| Account creation | `12` | `redirect` | +| API endpoints | `15` | `deny` | +| Public content | `18` | `deny` | + +To implement per-endpoint rules, create separate Rules Engine rules that run different Bot Manager instances based on `Request URI` criteria. + +--- + +## Step 11: Stream logs to external systems + +For long-term analysis and SIEM integration, use [Data Stream](/en/documentation/products/observe/data-stream/) to forward Bot Manager logs to your observability stack. + +1. Access [Azion Console](https://console.azion.com) > **Data Stream**. +2. Click **+ Stream**. +3. Configure the stream: + - **Source**: `Functions` + - **Template**: `Functions Event Collector` +4. Configure the **Destination** (Splunk, Datadog, Elastic, S3, or any HTTP endpoint). +5. Click **Save**. + +Bot Manager logs will be forwarded in real time, enabling you to build custom dashboards, set alerts on spike detection, and correlate bot activity with application performance metrics. + + + +--- + +## Calibration checklist + +Use this checklist after each calibration cycle: + +- [ ] Observation mode ran for at least 24 hours with `internal_logs: 2` +- [ ] Score distribution analyzed via GraphQL `botManagerMetrics` +- [ ] Top impacted URLs identified via `botManagerBreakdownMetrics` +- [ ] Threshold set between the legitimate and bad bot score clusters +- [ ] Static rules producing false positives added to `disabled_static_rules` +- [ ] Dynamic rules tolerance validated for your traffic profile +- [ ] Static assets excluded from Bot Manager via Rules Engine +- [ ] High-value endpoints configured with stricter thresholds +- [ ] Production logs streaming to external SIEM or observability platform +- [ ] Real-Time Metrics dashboards reviewed weekly + +--- + +## Related resources + + +
+ +
+ +
+ +
+ +
+ +
+ diff --git a/src/content/docs/pt-br/pages/guias/guides.mdx b/src/content/docs/pt-br/pages/guias/guides.mdx index faaf9b51e3..3a4e700f8f 100644 --- a/src/content/docs/pt-br/pages/guias/guides.mdx +++ b/src/content/docs/pt-br/pages/guias/guides.mdx @@ -162,6 +162,7 @@ permalink: /documentacao/produtos/guias/ - [Criando blacklists de endereços IP no Edge com Azion Network Shield](/pt-br/documentacao/produtos/guias/blocklists-enderecos-ip-edge/) - [Proteja conteúdo restrito contra acessos indevidos com Azion Secure Token](/pt-br/documentacao/produtos/guias/secure-token/) - [Paywall com Functions JWT](/pt-br/documentacao/produtos/guias/paywall-function-jwt/) +- [Como monitorar e calibrar o Bot Manager](/pt-br/documentacao/produtos/guias/secure/monitorar-e-calibrar-bot-manager/) --- diff --git a/src/content/docs/pt-br/pages/menu-principal/referencia/secure/edge-firewall/azion-bot-manager.mdx b/src/content/docs/pt-br/pages/menu-principal/referencia/secure/edge-firewall/azion-bot-manager.mdx index 2741bbd40c..c52d9a09ad 100644 --- a/src/content/docs/pt-br/pages/menu-principal/referencia/secure/edge-firewall/azion-bot-manager.mdx +++ b/src/content/docs/pt-br/pages/menu-principal/referencia/secure/edge-firewall/azion-bot-manager.mdx @@ -416,3 +416,11 @@ Esta configuração garante que todos os acessos ao endpoint `/api/submit` passa ### Regras personalizadas A Azion fornece configurações fáceis de usar, que devem ser suficientes para a maioria dos casos. Se você precisar de uma configuração mais detalhada, poderá editar o arquivo JSON da integração para personalizar e adicionar novas regras com base nas necessidades do seu negócio. Também é possível adicionar mais critérios e comportamentos a serem executados pelo [Rules Engine](/pt-br/documentacao/produtos/secure/firewall/rules-engine/), construindo respostas mais abrangentes para possíveis ataques. + +--- + +## Monitoramento e calibração + +Após implantar o Bot Manager, use as ferramentas de observabilidade para ler logs, interpretar classificações de tráfego e ajustar thresholds e regras para reduzir falsos positivos enquanto bloqueia ameaças reais. + + diff --git a/src/content/docs/pt-br/pages/secure-jornada/firewall-configuracoes-avancadas/gerenciar-bots.mdx b/src/content/docs/pt-br/pages/secure-jornada/firewall-configuracoes-avancadas/gerenciar-bots.mdx index ca0c77c641..4a2cb28f10 100644 --- a/src/content/docs/pt-br/pages/secure-jornada/firewall-configuracoes-avancadas/gerenciar-bots.mdx +++ b/src/content/docs/pt-br/pages/secure-jornada/firewall-configuracoes-avancadas/gerenciar-bots.mdx @@ -71,6 +71,14 @@ Você pode consultar o conjunto de dados do [Bot Manager](/pt-br/documentacao/pr Para configurar uma function, siga as etapas em [Configure a função](/pt-br/documentacao/produtos/guias/bot-manager-lite/#configure-a-funcao). Depois, você pode utilizar [Data Stream](/pt-br/documentacao/produtos/observe/data-stream/) para integrar com plataformas de stream, SIEM e big data usando o source **Functions** e o template **Functions Event Collector**. Assim, você pode enviar seus registros para o conector que você usa e monitorar os eventos do Bot Manager. + +--- + +## Monitoramento e calibração + +Após configurar o Bot Manager, use as ferramentas de observabilidade para ler logs, interpretar classificações de tráfego e ajustar thresholds e regras para reduzir falsos positivos enquanto bloqueia ameaças reais. + +

--- diff --git a/src/content/docs/pt-br/pages/secure-jornada/firewall-configuracoes-avancadas/monitorar-e-calibrar-bot-manager.mdx b/src/content/docs/pt-br/pages/secure-jornada/firewall-configuracoes-avancadas/monitorar-e-calibrar-bot-manager.mdx new file mode 100644 index 0000000000..53b9bb932a --- /dev/null +++ b/src/content/docs/pt-br/pages/secure-jornada/firewall-configuracoes-avancadas/monitorar-e-calibrar-bot-manager.mdx @@ -0,0 +1,449 @@ +--- +title: Como monitorar e calibrar o Bot Manager +description: >- + Aprenda a ler os logs do Bot Manager, interpretar as classificações de tráfego + e ajustar thresholds e regras para reduzir falsos positivos e bloquear ameaças reais. +meta_tags: 'bot manager, proteção contra bots, logs, calibração, tuning, real-time events, graphql, firewall' +namespace: docs_guides_secure_monitor_calibrate_bot_manager +permalink: /documentacao/produtos/guias/secure/monitorar-e-calibrar-bot-manager/ +--- + +import LinkButton from 'azion-webkit/linkbutton' +import Tag from 'primevue/tag' + +Após implantar o [Bot Manager](/pt-br/documentacao/produtos/secure/firewall/bot-manager/), o próximo passo é entender o que os dados indicam e ajustar a configuração para corresponder aos padrões de tráfego da sua aplicação. Este guia mostra como ler logs, interpretar classificações e calibrar thresholds e regras para reduzir falsos positivos enquanto bloqueia ameaças reais. + +:::note +O Bot Manager é um add-on do Firewall. Entre em contato com o [time de Vendas](https://www.azion.com/pt-br/contato-vendas/) para detalhes de assinatura. Se você estiver usando o [Bot Manager Lite](/pt-br/documentacao/produtos/guias/bot-manager-lite/), as mesmas ferramentas de observabilidade se aplicam, embora algumas opções avançadas de configuração sejam diferentes. +::: + +--- + +## Pré-requisitos + +- [Bot Manager configurado em um Firewall](/pt-br/documentacao/produtos/secure/firewall/bot-manager/) + +--- + +## Passo 1: Habilitar logging completo + +Antes de calibrar o Bot Manager, você precisa de visibilidade completa sobre cada requisição que ele avalia. Por padrão, o Bot Manager só grava logs para requisições que excedem o threshold. Para observar todo o tráfego—incluindo requisições legítimas—defina a ação como `allow` e habilite os logs internos durante a fase de observação. + +No seu Firewall, acesse **Functions Instances**, selecione sua instância do Bot Manager e atualize os **JSON Args**: + +```json +{ + "action": "allow", + "internal_logs": 2, + "log_tag": "bot_manager_calibracao", + "log_headers": [ + "accept", + "accept-encoding", + "accept-language", + "content-type", + "host", + "referer", + "user-agent", + "x-forwarded-for", + "x-request-id" + ] +} +``` + +| Campo | Finalidade | +|-------|-----------| +| `action: allow` | Permite que todas as requisições passem enquanto você observa os padrões de tráfego | +| `internal_logs: 2` | Grava um log de relatório para cada requisição, independentemente da pontuação | +| `log_tag` | Rotula os logs para que você possa filtrá-los no Real-Time Events | +| `log_headers` | Captura os headers da requisição para análise mais profunda | + +:::tip +Execute no modo de observação por pelo menos 24–72 horas para capturar padrões de tráfego representativos, incluindo horários de pico, crawlers e jobs agendados. +::: + +--- + +## Passo 2: Ler logs no Real-Time Events + +O [Real-Time Events](/pt-br/documentacao/produtos/observe/real-time-events/) é a forma mais rápida de inspecionar decisões individuais do Bot Manager. + +1. Acesse o [Azion Console](https://console.azion.com) > **Real-Time Events**. +2. Selecione o data source **Functions**. +3. Defina o **Filtro de Tempo** para o período que deseja analisar. +4. Na barra de pesquisa, filtre pela sua log tag: + +``` +log_tag = "bot_manager_calibracao" +``` + +Cada entrada de log é um objeto JSON. Os campos-chave para focar durante a calibração são: + +| Campo | O que indica | +|-------|-------------| +| `classified` | Veredicto final: `legitimate`, `good bot`, `bad bot` ou `under evaluation` | +| `bot_category` | O tipo específico de ameaça ou bot detectado | +| `score` | Pontuação numérica atribuída à requisição | +| `action` | Ação que o Bot Manager tomou (ou tomaria se o threshold estivesse ativo) | +| `matched_rules` | IDs das regras estáticas que dispararam e contribuíram para a pontuação | +| `disabled_matched_rules` | IDs das regras desabilitadas que corresponderam (não afetam a pontuação) | +| `azion_fingerprint` | Hash do fingerprint do dispositivo—útil para rastrear reincidentes | +| `remote_addr` | Endereço IP de origem | +| `http_user_agent` | String User-Agent enviada na requisição | +| `request_uri` | O caminho que foi requisitado | + +### Exemplo de entrada de log + +```json +{ + "action": "allow", + "classified": "bad bot", + "bot_category": "Bad Bot Signatures", + "score": 14, + "matched_rules": [10, 22], + "azion_fingerprint": "5f852499202f7fa889157ce8b39a613b", + "remote_addr": "203.0.113.42", + "http_user_agent": "python-requests/2.28.0", + "request_uri": "/api/v1/products", + "geoip_country": "Brazil", + "log_tag": "bot_manager_calibracao" +} +``` + +**Lendo este log**: Uma requisição do IP `203.0.113.42` usando uma biblioteca HTTP Python recebeu pontuação `14` e foi classificada como `bad bot` com categoria `Bad Bot Signatures`. As regras `10` e `22` dispararam. A ação foi `allow` porque você está no modo de observação—uma vez que você defina um threshold abaixo de `14`, esta requisição seria bloqueada. + +--- + +## Passo 3: Interpretar as classificações de tráfego + +O Bot Manager atribui a cada requisição uma das quatro classificações: + +| Classificação | Significado | Ação recomendada | +|--------------|------------|-----------------| +| `legitimate` | Tráfego regular de usuários sem sinais de bot | Nenhuma ação necessária | +| `good bot` | Bots conhecidos e confiáveis (mecanismos de busca, monitores) | Verifique a categoria do bot; considere permitir explicitamente | +| `bad bot` | Automação maliciosa ou suspeita confirmada | Bloquear ou desafiar após definir o threshold | +| `under evaluation` | Dados de fingerprint insuficientes para classificar | Monitorar; a classificação se resolve em até 15 minutos | + +### Entendendo "under evaluation" + +Quando um novo fingerprint aparece, o Bot Manager precisa de até 15 minutos para consolidar dados suficientes para classificá-lo com confiança. Durante essa janela, as requisições são marcadas como `under evaluation`. Esse é o comportamento esperado—evita o bloqueio prematuro de novos visitantes legítimos. Se você observar um alto volume de tráfego `under evaluation`, pode indicar: + +- Um grande influxo de novos usuários (esperado após uma campanha ou lançamento). +- IPs ou User-Agents rotativos (uma técnica de evasão de bots que vale investigar). + +### Categorias de bots bons para reconhecer + +| Categoria de bot | Exemplos | +|-----------------|---------| +| `Search Engine Bot` | Googlebot, Bingbot, DuckDuckBot | +| `Monitoring Bot` | UptimeRobot, Pingdom, StatusCake | +| `Social Network Bot` | Facebookbot, Twitterbot | +| `Aggregator Bot` | Feedly, agregadores de notícias | +| `Enterprise Bot` | Crawlers internos, integrações de parceiros | + +Se você observar bots bons legítimos recebendo pontuação alta, verifique se seus User-Agents estão sendo reconhecidos corretamente. Pode ser necessário adicioná-los a uma regra de exclusão. + +--- + +## Passo 4: Analisar padrões com GraphQL + +Para análise agregada em grandes volumes de tráfego, use a [API GraphQL](/pt-br/documentacao/devtools/graphql-api/visao-geral/) para consultar o dataset `botManagerMetrics`. + +### Query: breakdown de tráfego por classificação e categoria + +Acesse o GraphiQL Playground em `https://api.azion.com/v4/metrics/graphql` e execute: + +```graphql +query { + botManagerMetrics( + filter: { + tsRange: { + begin: "2024-10-01T00:00:00" + end: "2024-10-03T23:59:59" + } + } + aggregate: { + sum: requests + } + orderBy: [sum_DESC] + groupBy: [classified, botCategory, action] + limit: 10000 + ) { + classified + botCategory + action + sum + } +} +``` + +Esta query retorna a contagem total de requisições agrupadas por classificação, categoria e ação—fornecendo uma visão clara da composição do seu tráfego. + +### Query: top URLs impactadas por bots maliciosos + +Use o dataset `botManagerBreakdownMetrics` para identificar quais endpoints são mais visados: + +```graphql +query { + botManagerBreakdownMetrics( + filter: { + tsRange: { + begin: "2024-10-01T00:00:00" + end: "2024-10-03T23:59:59" + } + } + aggregate: { + sum: botRequests + } + groupBy: [requestUrl] + orderBy: [sum_DESC] + limit: 10 + ) { + requestUrl + sum + } +} +``` + +Se o seu endpoint de login (`/api/auth/login`) ou caminho de checkout (`/checkout`) aparecer no topo, esses são alvos de alta prioridade para regras mais rígidas. + + +
+ + +--- + +## Passo 5: Monitorar com os dashboards do Real-Time Metrics + +O [Real-Time Metrics](/pt-br/documentacao/produtos/observe/real-time-metrics/#bot-manager) fornece dashboards pré-construídos para o Bot Manager com duas seções: + +### Seção Overview + +| Gráfico | O que observar | +|---------|---------------| +| **Bad Bot Hits** | Pico indica uma campanha de ataque ativa | +| **Good Bot Hits** | Queda repentina pode significar que crawlers legítimos estão sendo bloqueados | +| **Bot Traffic** | Proporção de tráfego legítimo vs. bad bot vs. under evaluation | +| **Top Bot Action** | Distribuição das ações tomadas (allow, deny, redirect, etc.) | +| **Bot CAPTCHA** | Taxa de resolução do desafio—taxas baixas podem indicar bots reais | + +### Seção Breakdown + +| Gráfico | O que observar | +|---------|---------------| +| **Top Bot Classifications** | Quais tipos de ataque são mais prevalentes | +| **Bot Activity Map** | Origem geográfica dos ataques | +| **Top Impacted URLs** | Endpoints recebendo mais tráfego de bots | +| **Top Bad Bot IPs** | Reincidentes para adicionar às network lists | + + + +--- + +## Passo 6: Definir e calibrar o threshold + +O parâmetro `threshold` é a alavanca de calibração mais crítica. Ele define a pontuação máxima que uma requisição pode atingir antes que o Bot Manager execute a ação configurada. + +### Como funciona a pontuação + +Cada regra estática que dispara adiciona pontos à pontuação da requisição. A pontuação total determina se a requisição é bloqueada. Uma pontuação de `0` significa que nenhuma regra correspondeu; pontuações mais altas indicam mais sinais suspeitos. + +### Escolhendo um threshold inicial + +Comece com um threshold conservador (alto) e reduza-o gradualmente à medida que ganha confiança nos dados: + +| Threshold | Comportamento | +|-----------|-------------| +| `Infinity` (padrão) | Todas as requisições passam; nenhum bloqueio ocorre | +| `18` | Ponto de partida recomendado para a maioria das aplicações | +| `10–15` | Mais rígido; adequado para endpoints de alto valor como login ou pagamento | +| `5–9` | Muito rígido; pode produzir falsos positivos em tráfego incomum-mas-legítimo | +| `0` | Bloqueia todas as requisições (use apenas para testes) | + +### Fluxo de calibração + +1. **Observar** (dias 1–3): Execute com `action: allow` e `internal_logs: 2`. Colete distribuições de pontuação. +2. **Identificar a lacuna de pontuação**: Encontre o intervalo de pontuação onde os bots maliciosos se concentram vs. onde o tráfego legítimo está. O threshold deve ficar entre esses dois clusters. +3. **Definir o threshold**: Atualize os JSON Args com o threshold escolhido e uma ação de bloqueio. +4. **Monitorar falsos positivos**: Observe o tráfego legítimo sendo bloqueado. Verifique entradas `classified: legitimate` com pontuações próximas ao seu threshold. +5. **Ajustar**: Reduza o threshold se muitos bots maliciosos passarem; aumente-o se usuários legítimos estiverem sendo bloqueados. + +### Exemplo: definindo o threshold após observação + +Após 48 horas de observação, seus dados do GraphQL mostram: + +- Tráfego legítimo: pontuações entre `0–8` +- Bots maliciosos: pontuações entre `15–30` +- Um pequeno cluster de tráfego ambíguo: pontuações `9–14` + +Defina o threshold como `15` para bloquear bots maliciosos confirmados enquanto permite que o cluster ambíguo passe para observação adicional: + +```json +{ + "threshold": 15, + "action": "deny", + "log_tag": "bot_manager_producao", + "mode": "web", + "dynamic_rules_tolerance": "soft", + "reputation_network_lists": [], + "disabled_static_rules": [], + "log_headers": [ + "accept", + "accept-encoding", + "accept-language", + "content-type", + "host", + "referer", + "user-agent", + "x-forwarded-for", + "x-request-id" + ] +} +``` + +--- + +## Passo 7: Ajustar regras estáticas + +As regras estáticas são padrões de detecção predefinidos. Cada regra tem um ID e contribui com um número fixo de pontos para a pontuação da requisição quando correspondida. Você pode desabilitar regras específicas que geram falsos positivos sem removê-las do mecanismo de detecção. + +### Identificando regras problemáticas + +No Real-Time Events, filtre por entradas `classified: legitimate` que tenham pontuação alta. Verifique o array `matched_rules` para identificar quais IDs de regras estão disparando em tráfego legítimo. + +Por exemplo, se a regra `22` dispara consistentemente nas requisições da sua ferramenta de monitoramento interno: + +```json +{ + "disabled_static_rules": [22] +} +``` + +As regras desabilitadas ainda aparecem em `disabled_matched_rules` nos logs, para que você possa rastrear suas correspondências sem afetar a pontuação. + +:::tip +Desabilite regras de forma conservadora. Cada regra desabilitada reduz a cobertura de detecção. Se uma regra dispara tanto em tráfego legítimo quanto malicioso, considere usar uma exclusão no Rules Engine em vez de desabilitar a regra globalmente. +::: + +--- + +## Passo 8: Configurar regras dinâmicas + +As regras dinâmicas usam análise comportamental para detectar anomalias que as regras estáticas podem não capturar. Elas se adaptam à linha de base de tráfego da sua aplicação ao longo do tempo. + +### Parâmetros das regras dinâmicas + +| Parâmetro | Padrão | Descrição | +|-----------|--------|-----------| +| `disable_dynamic_rules` | `false` | Defina como `true` para desabilitar as regras dinâmicas completamente | +| `dynamic_rules_tolerance` | `soft` | Rigor da detecção: `soft`, `medium` ou `hard` | +| `dynamic_rules_baseline` | `0` | Ajuste fino da linha de base. Valores negativos = mais rígido; positivos = mais permissivo | + +### Escolhendo a tolerância + +| Tolerância | Quando usar | +|-----------|------------| +| `soft` | Ponto de partida; menos provável de produzir falsos positivos | +| `medium` | Após validar que `soft` não produz falsos positivos | +| `hard` | Ambientes de alta segurança com padrões de tráfego bem compreendidos | + +### Habilitando logs de debug das regras dinâmicas + +Durante a calibração, habilite os logs de debug para entender as decisões das regras dinâmicas: + +```json +{ + "dynamic_rules_logs_enabled": true +} +``` + +:::note +Desabilite `dynamic_rules_logs_enabled` em produção. Os logs de debug aumentam significativamente o volume de logs e são destinados apenas para calibração. +::: + +--- + +## Passo 9: Excluir assets estáticos da análise do bot + +O Bot Manager não deve analisar requisições de arquivos estáticos (imagens, CSS, JavaScript). Essas requisições nunca são bots e adicionam sobrecarga de processamento desnecessária. Configure uma regra no Rules Engine para ignorar o Bot Manager em assets estáticos. + +No **Rules Engine** do seu Firewall, crie uma regra com os seguintes critérios: + +- **Critério**: `Request URI` **não corresponde** à regex: + +``` +\.(png|jpg|jpeg|gif|ico|css|js|svg|woff|woff2|ttf|eot|otf|webp|avif|mp4|webm|pdf)(\?.*)?$ +``` + +- **Comportamento**: `Run Function` > selecione sua instância do Bot Manager. + +Isso garante que o Bot Manager só seja executado em requisições dinâmicas, reduzindo o ruído nos seus logs e melhorando a precisão. + +--- + +## Passo 10: Proteger endpoints de alto valor com regras mais rígidas + +Diferentes endpoints têm diferentes perfis de risco. Use múltiplas instâncias do Bot Manager com diferentes thresholds para aplicar proteção mais rígida onde é mais importante. + +| Tipo de endpoint | Threshold recomendado | Ação recomendada | +|-----------------|----------------------|-----------------| +| Login / autenticação | `10` | `redirect` (para CAPTCHA) | +| Pagamento / checkout | `10` | `deny` | +| Criação de conta | `12` | `redirect` | +| Endpoints de API | `15` | `deny` | +| Conteúdo público | `18` | `deny` | + +Para implementar regras por endpoint, crie regras separadas no Rules Engine que executam diferentes instâncias do Bot Manager com base em critérios de `Request URI`. + +--- + +## Passo 11: Transmitir logs para sistemas externos + +Para análise de longo prazo e integração com SIEM, use o [Data Stream](/pt-br/documentacao/produtos/observe/data-stream/) para encaminhar os logs do Bot Manager para sua stack de observabilidade. + +1. Acesse o [Azion Console](https://console.azion.com) > **Data Stream**. +2. Clique em **+ Stream**. +3. Configure o stream: + - **Source**: `Functions` + - **Template**: `Functions Event Collector` +4. Configure o **Destino** (Splunk, Datadog, Elastic, S3 ou qualquer endpoint HTTP). +5. Clique em **Save**. + +Os logs do Bot Manager serão encaminhados em tempo real, permitindo que você construa dashboards personalizados, configure alertas para detecção de picos e correlacione a atividade de bots com métricas de desempenho da aplicação. + + + +--- + +## Checklist de calibração + +Use este checklist após cada ciclo de calibração: + +- [ ] Modo de observação executado por pelo menos 24 horas com `internal_logs: 2` +- [ ] Distribuição de pontuação analisada via GraphQL `botManagerMetrics` +- [ ] Top URLs impactadas identificadas via `botManagerBreakdownMetrics` +- [ ] Threshold definido entre os clusters de pontuação de tráfego legítimo e bots maliciosos +- [ ] Regras estáticas produzindo falsos positivos adicionadas a `disabled_static_rules` +- [ ] Tolerância das regras dinâmicas validada para o perfil de tráfego +- [ ] Assets estáticos excluídos do Bot Manager via Rules Engine +- [ ] Endpoints de alto valor configurados com thresholds mais rígidos +- [ ] Logs de produção transmitindo para SIEM ou plataforma de observabilidade externa +- [ ] Dashboards do Real-Time Metrics revisados semanalmente + +--- + +## Recursos relacionados + + +
+ +
+ +
+ +
+ +
+ +
+