

**Introducing a new console experience for AWS WAF**

You can now use the updated experience to access AWS WAF functionality anywhere in the console. For more details, see [Working with the console](https://docs.aws.amazon.com/waf/latest/developerguide/working-with-console.html). 

# Intelligent threat mitigation in AWS WAF
Intelligent threat mitigationRenamed the top-level section: Managed protections

The section is now named AWS WAF intelligent threat mitigation, which aligns with our marketing pages. 

This section covers the managed intelligent threat mitigation features provided by AWS WAF. These are advanced, specialized protections that you can implement to protect against threats such as malicious bots and account takeover attempts. 

**Note**  
The features described here incur additional costs, beyond the basic fees for using AWS WAF. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

The guidance provided in this section is intended for users who know generally how to create and manage AWS WAF web ACLs, rules, and rule groups. Those topics are covered in prior sections of this guide. 

**Topics**
+ [

# Options for intelligent threat mitigation in AWS WAF
](waf-managed-protections-comparison-table.md)
+ [

# Best practices for intelligent threat mitigation in AWS WAF
](waf-managed-protections-best-practices.md)
+ [

# Token use in AWS WAF intelligent threat mitigation
](waf-tokens.md)
+ [

# AWS WAF Fraud Control account creation fraud prevention (ACFP)
](waf-acfp.md)
+ [

# AWS WAF Fraud Control account takeover prevention (ATP)
](waf-atp.md)
+ [

# AWS WAF Bot Control
](waf-bot-control.md)
+ [

# AWS WAF Distributed Denial of Service (DDoS) prevention
](waf-anti-ddos.md)
+ [

# Client application integrations in AWS WAF
](waf-application-integration.md)
+ [

# CAPTCHA and Challenge in AWS WAF
](waf-captcha-and-challenge.md)

# Options for intelligent threat mitigation in AWS WAF
Mitigation options

This section provides a detailed comparison of the options for implementing intelligent threat mitigation. 

AWS WAF offers the following types of protections for intelligent threat mitigation.
+ **AWS WAF Fraud Control account creation fraud prevention (ACFP)** – Detects and manages malicious account creation attempts on your application's sign-up page. The core functionality is provided by the ACFP managed rule group. For more information, see [AWS WAF Fraud Control account creation fraud prevention (ACFP)](waf-acfp.md) and [AWS WAF Fraud Control account creation fraud prevention (ACFP) rule group](aws-managed-rule-groups-acfp.md).
+ **AWS WAF Fraud Control account takeover prevention (ATP)** – Detects and manages malicious takeover attempts on your application's login page. The core functionality is provided by the ATP managed rule group. For more information, see [AWS WAF Fraud Control account takeover prevention (ATP)](waf-atp.md) and [AWS WAF Fraud Control account takeover prevention (ATP) rule group](aws-managed-rule-groups-atp.md).
+ **AWS WAF Bot Control** – Identifies, labels, and manages both friendly and malicious bots. This feature provides management for common bots with signatures that are unique across applications, and also for targeted bots that have signatures specific to an application. The core functionality is provided by the Bot Control managed rule group. For more information, see [AWS WAF Bot Control](waf-bot-control.md) and [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md).
+ **Client application integration SDKs** – Validate client sessions and end users on your web pages and acquire AWS WAF tokens for clients to use in their web requests. If you use ACFP, ATP, or Bot Control, implement the application integration SDKs in your client application if you can, to take full advantage of all of the rule group features. We only recommend using these rule groups without an SDK integration as a temporary measure, when a critical resource needs to be quickly secured and there isn’t enough time for the SDK integration. For information about implementing the SDKs, see [Client application integrations in AWS WAF](waf-application-integration.md). 
+ **Challenge and CAPTCHA rule actions** – Validate client sessions and end users and acquire AWS WAF tokens for clients to use in their web requests. You can implement these anywhere that you specify a rule action, in your rules and as overrides in rule groups that you use. These actions use AWS WAF JavaScript interstitials to interrogate the client or end user, and they require client applications that support JavaScript. For more information, see [CAPTCHA and Challenge in AWS WAF](waf-captcha-and-challenge.md).

The intelligent threat mitigation AWS Managed Rules rule groups ACFP, ATP, and Bot Control use tokens for advanced detection. For information about the features that tokens enable in the rule groups, see [Using application integration SDKs with ACFP](waf-acfp-with-tokens.md), [Using application integration SDKs with ATP](waf-atp-with-tokens.md), and [Using application integration SDKs with Bot Control](waf-bot-with-tokens.md). 

Your options for implementing intelligent threat mitigation run from the basic use of rule actions to run challenges and enforce token acquisition, to the advanced features offered by the intelligent threat mitigation AWS Managed Rules rule groups.

The following tables provide detailed comparisons of the options for the basic and advanced features. 

**Topics**
+ [

# Options for challenges and token acquisition
](waf-managed-protections-comparison-table-token.md)
+ [

# Options for intelligent threat mitigation managed rule groups
](waf-managed-protections-comparison-table-rg.md)
+ [

# Options for rate limiting in rate-based rules and targeted Bot Control rules
](waf-rate-limiting-options.md)

# Options for challenges and token acquisition
Challenges and token acquisition

This section compares challenge and token management options.

You can provide challenges and acquire tokens using the AWS WAF application integration SDKs or the rule actions Challenge and CAPTCHA. Broadly speaking, the rule actions are easier to implement, but they incur added costs, intrude more on your customer experience, and require JavaScript. The SDKs require programming in your client applications, but they can provide a better customer experience, they're free to use, and they can be used with JavaScript or in Android or iOS applications. You can only use the application integration SDKs with protection packs (web ACLs) that use one of the paid intelligent threat mitigation managed rule groups, described in the following section. 


**Comparison of options for challenges and token acquisition**  

|  | Challenge rule action | CAPTCHA rule action | JavaScript SDK challenge | Mobile SDK challenge | 
| --- | --- | --- | --- | --- | 
| What it is | Rule action that enforces acquisition of the AWS WAF token by presenting the browser client with a silent challenge interstitial  | Rule action that enforces acquisition of the AWS WAF token by presenting the client end user with a visual or audio challenge interstitial  |  Application integration layer, for client browsers and other devices that execute JavaScript. Renders the silent challenge and acquires a token  |  Application integration layer, for Android and iOS applications. Natively renders the silent challenge and acquires a token  | 
| Good choice for... | Silent validation against bot sessions and enforcement of token acquisition for clients that support JavaScript  | End user and silent validation against bot sessions and enforcement of token acquisition, for clients that support JavaScript | Silent validation against bot sessions and enforcement of token acquisition for clients that support JavaScript. The SDKs provide the lowest latency and best control over where the challenge script runs in the application. | Silent validation against bot sessions and enforcement of token acquisition for native mobile applications on Android and iOS. The SDKs provide the lowest latency and best control over where the challenge script runs in the application. | 
| Implementation considerations | Implemented as a rule action setting | Implemented as a rule action setting | Requires one of the ACFP, ATP, or Bot Control paid rule groups in the protection pack (web ACL). Requires coding in the client application. | Requires one of the ACFP, ATP, or Bot Control paid rule groups in the protection pack (web ACL). Requires coding in the client application. | 
| Runtime considerations | Intrusive flow for requests without valid tokens. Client is redirected to an AWS WAF challenge interstitial. Adds network round trips and requires a second evaluation of the web request.  | Intrusive flow for requests without valid tokens. Client is redirected to an AWS WAF CAPTCHA interstitial. Adds network round trips and requires a second evaluation of the web request.  | Can be run behind the scenes. Gives you more control over the challenge experience.  | Can be run behind the scenes. Gives you more control over the challenge experience.  | 
| Requires JavaScript | Yes | Yes | Yes | No | 
| Supported clients | Browser and devices that execute Javascript | Browser and devices that execute Javascript | Browser and devices that execute Javascript | Android and iOS devices | 
| Supports single-page applications (SPA) | Enforcement only. You can use the Challenge action in conjunction with the SDKs, to ensure that requests have a valid challenge token. You can't use the rule action to deliver the challenge script to the page.  | Enforcement only. You can use the CAPTCHA action in conjunction with the SDKs, to ensure that requests have a valid CAPTCHA token. You can't use the rule action to deliver the CAPTCHA script to the page.  | Yes | N/A | 
| Additional cost | Yes, for action settings that you explicitly specify, either in the rules that you define or as rule action overrides in rule groups that you use. No in all other cases.  | Yes, for action settings that you explicitly specify, either in the rules that you define or as rule action overrides in rule groups that you use. No in all other cases.  | No, but requires one of the paid rule groups ACFP, ATP, or Bot Control. | No, but requires one of the paid rule groups ACFP, ATP, or Bot Control . | 

For details about costs associated with these options, see the intelligent threat mitigation information at [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

It can be simpler to run challenges and provide basic token enforcement by just adding a rule with a Challenge or CAPTCHA action. You might be required to use the rule actions, for example if you don't have access to the application code. 

If you can implement the SDKs however, you can save costs and reduce latency in your protection pack (web ACL) evaluation of client web requests, compared to using the Challenge action: 
+ You can write your SDK implementation to run the challenge at any point in your application. You can acquire the token in the background, prior to any customer action that would send a web request to your protected resource. This way, the token is available to send with your client's first request. 
+ If instead you acquire tokens by implementing a rule with the Challenge action, the rule and action require additional web request evaluation and processing when the client first sends a request and anytime the token expires. The Challenge action blocks the request that doesn't have a valid, unexpired token, and sends the challenge interstitial back to the client. After the client successfully responds to the challenge, the interstitial resends the original web request with the valid token, which is then evaluated a second time by the protection pack (web ACL). 

# Options for intelligent threat mitigation managed rule groups
Managed rule groups

This section compares managed rule group options.

The intelligent threat mitigation AWS Managed Rules rule groups provide management of basic bots, detection and mitigation of sophisticated, malicious bots, detection and mitigation of account takeover attempts, and detection and mitigation of fraudulent account creation attempts. These rule groups, combined with the application integration SDKs described in the prior section, provide the most advanced protections and secure coupling with your client applications. 


**Comparison of the managed rules group options**  

|  | ACFP  | ATP  | Bot Control common level | Bot Control targeted level | 
| --- | --- | --- | --- | --- | 
| What it is | Manages requests that might be part of fraudulent account creation attempts on an application's registration and sign-up pages.Does not manage bots. See [AWS WAF Fraud Control account creation fraud prevention (ACFP) rule group](aws-managed-rule-groups-acfp.md). | Manages requests that might be part of malicious takeover attempts on an application's login page.Does not manage bots. See [AWS WAF Fraud Control account takeover prevention (ATP) rule group](aws-managed-rule-groups-atp.md). | Manages common bots that self-identify, with signatures that are unique across applications.See [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md). | Manages targeted bots that don't self-identify, with signatures that are specific to an application.See [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md). | 
| Good choice for... | Inspection of account creation traffic for fraudulent account creation attacks such creation attempts with username traversal and many new accounts created from a single IP address. | Inspection of login traffic for account takeover attacks such login attempts with password traversal and many login attempts from the same IP address. When used with tokens, also provides aggregate protections such as rate limiting of IPs and client sessions for high volumes of failed login attempts. | Basic bot protection and labeling of common, automated bot traffic. | Targeted protection against sophisticated bots, including rate limiting at the client session level and detection and mitigation of browser automation tools such as Selenium and Puppeteer.  | 
| Adds labels that indicate evaluation results | Yes | Yes | Yes | Yes | 
| Adds token labels | Yes | Yes | Yes | Yes | 
| Blocking for requests that don't have a valid token | Not included. See [Blocking requests that don't have a valid AWS WAF token](waf-tokens-block-missing-tokens.md). | Not included. See [Blocking requests that don't have a valid AWS WAF token](waf-tokens-block-missing-tokens.md). | Not included. See [Blocking requests that don't have a valid AWS WAF token](waf-tokens-block-missing-tokens.md). | Blocks client sessions that send 5 requests without a token. | 
| Requires the AWS WAF token aws-waf-token | Required for all rules.See [Using application integration SDKs with ACFP](waf-acfp-with-tokens.md). | Required for many rules.See [Using application integration SDKs with ATP](waf-atp-with-tokens.md). | No | Yes | 
| Acquires the AWS WAF token aws-waf-token | Yes, enforced by the rule AllRequests | No | No | Some rules use Challenge or CAPTCHA rule actions, which acquire tokens. | 

For details about costs associated with these options, see the intelligent threat mitigation information at [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

# Options for rate limiting in rate-based rules and targeted Bot Control rules
Rate limiting

This section compares rate-based mitigation options.

The targeted level of the AWS WAF Bot Control rule group and the AWS WAF rate-based rule statement both provide web request rate limiting. The following table compares the two options.


**Comparison of options for rate-based detection and mitigation**  

|  | AWS WAF rate-based rule | AWS WAF Bot Control targeted rules | 
| --- | --- | --- | 
| How rate limiting is applied | Acts on groups of requests that are coming at too high a rate. You can apply any action except for Allow.  | Enforces human-like access patterns and applies dynamic rate limiting, through the use of request tokens.  | 
| Based on historical traffic baselines?  | No  | Yes  | 
| Time required to accumulate historic traffic baselines  | N/A  | Five minutes for dynamic thresholds. N/A for token absent. | 
| Mitigation lag  | Usually 30-50 seconds. Can be up to several minutes.  | Usually less than 10 seconds. Can be up to several minutes.  | 
| Mitigation targets  | Configurable. You can group requests using a scope-down statement and by one or more aggregation keys, such as IP address, HTTP method, and query string. | IP addresses and client sessions  | 
| Traffic volume level required to trigger mitigations  | Medium - can be as low as 10 requests in the specified time window  | Low - intended to detect client patterns such as slow scrapers  | 
| Customizable thresholds  | Yes  | No  | 
| Default mitigation action | Console default is Block. No default setting in the API; the setting is required. You can set this to any rule action except Allow. | The rule group rule action settings are Challenge for token absent and CAPTCHA for high volume traffic from a single client session. You can set either of these rules to any valid rule action.  | 
| Resiliency against highly distributed attacks  | Medium - 10,000 IP address maximum for IP address limiting on its own | Medium - limited to 50,000 total between IP addresses and tokens  | 
| [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/) | Included in the standard fees for AWS WAF.  | Included in the fees for the targeted level of Bot Control intelligent threat mitigation.  | 
| For more information | [Using rate-based rule statements in AWS WAF](waf-rule-statement-type-rate-based.md) | [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md) | 

# Best practices for intelligent threat mitigation in AWS WAF
Best practicesBest practices for intelligent threat mitigation

Added a section with best practices for implementing Bot Control, ATP, and other intelligent threat mitigation features. 

Follow the best practices in this section for the most efficient, cost-effective implementation of the intelligent threat mitigation features. 
+ **Implement the JavaScript and mobile application integration SDKs** – Implement application integration to enable the full set of ACFP, ATP, or Bot Control functionality in the most effective way possible. The managed rule groups use the tokens provided by the SDKs to separate legitimate client traffic from unwanted traffic at the session level. The application integration SDKs ensure that these tokens are always available. For details, see the following: 
  + [Using application integration SDKs with ACFP](waf-acfp-with-tokens.md)
  + [Using application integration SDKs with ATP](waf-atp-with-tokens.md)
  + [Using application integration SDKs with Bot Control](waf-bot-with-tokens.md)

  Use the integrations to implement challenges in your client and, for JavaScript, to customize how CAPTCHA puzzles are presented to your end users. For details, see [Client application integrations in AWS WAF](waf-application-integration.md). 

  If you customize CAPTCHA puzzles using the JavaScript API and you use the CAPTCHA rule action anywhere in your protection pack (web ACL), follow the guidance for handling the AWS WAF CAPTCHA response in your client at [Handling a CAPTCHA response from AWS WAF](waf-js-captcha-api-conditional.md). This guidance applies to any rules that use the CAPTCHA action, including those in the ACFP managed rule group and the targeted protection level of the Bot Control managed rule group. 
+ **Limit the requests that you send to the ACFP, ATP, and Bot Control rule groups** – You incur additional fees for using the intelligent threat mitigation AWS Managed Rules rule groups. The ACFP rule group inspects requests to the account registration and creation endpoints that you specify. The ATP rule group inspects requests to the login endpoint that you specify. The Bot Control rule group inspects every request that reaches it in the protection pack (web ACL) evaluation. 

  Consider the following approaches to reduce your use of these rule groups: 
  + Exclude requests from inspection with a scope-down statement in the managed rule group statement. You can do this with any nestable statement. For information, see [Using scope-down statements in AWS WAF](waf-rule-scope-down-statements.md).
  + Exclude requests from inspection by adding rules before the rule group. For rules that you can't use in a scope-down statement and for more complex situations, such as labeling followed by label matching, you might want to add rules that run before the rule groups. For information, see [Using scope-down statements in AWS WAF](waf-rule-scope-down-statements.md) and [Using rule statements in AWS WAF](waf-rule-statements.md).
  + Run the rule groups after less expensive rules. If you have other standard AWS WAF rules that block requests for any reason, run them before these paid rule groups. For more information about rules and rule management, see [Using rule statements in AWS WAF](waf-rule-statements.md).
  + If you're using more than one of the intelligent threat mitigation managed rule groups, run them in the following order to keep costs down: Bot Control, ATP, ACFP.

  For detailed pricing information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).
+ **Do not limit the requests that you send to the Anti-DDoS rule group ** – This rule group operates best when you configure it in to monitor all web traffic that you aren't explicitly allowing through. Position it in your web ACL to be evaluated only after rules with the Allow rule action and before all other rules. 
+ **For distributed denial of service (DDoS) protection, use either Anti-DDoS or Shield Advanced automatic application layer DDoS mitigation** – The other intelligent threat mitigation rule groups don't provide DDoS protection. ACFP protects against fraudulent account creation attempts to your application's sign-up page. ATP protects against account takeover attempts to your login page. Bot Control focuses on enforcing human-like access patterns using tokens and dynamic rate limiting on client sessions.

  Anti-DDoS allows you to monitor and control DDoS attacks, allowing for quick response and mitigation of threats. Shield Advanced with automatic application layer DDoS mitigation automatically responds to detected DDoS attacks by creating, evaluating, and deploying custom AWS WAF mitigations on your behalf.

  For more information about Shield Advanced, see [AWS Shield Advanced overview](ddos-advanced-summary.md), and [Protecting the application layer (layer 7) with AWS Shield Advanced and AWS WAF](ddos-app-layer-protections.md).

  For more information about Distributed Denial of Service (DDoS) prevention, see [Anti-DDoS rule group](aws-managed-rule-groups-anti-ddos.md) and [Distributed Denial of Service (DDoS) prevention](waf-anti-ddos.md).
+  **Enable the Anti-DDoS rule group and the targeted protection level of the Bot Control rule group during normal web traffic** – These rule categories need time to establish baselines for normal traffic. 

   **Enable the targeted protection level of the Bot Control rule group during normal web traffic** – Some rules of the targeted protection level need time to establish baselines for normal traffic patterns before they can recognize and respond to irregular or malicious traffic patterns. For example, the `TGT_ML_*` rules need up to 24 hours to warm up. 

  Add these protections when you are not experiencing an attack and give them time to establish their baselines before expecting them to respond appropriately. If you add these rules during an attack, you will need to enable the Anti-DDoS rule group in count mode. After the attack subsides, the time to establish a baseline is usually from double to triple the normal required time, because of the skewing added by the attack traffic. For additional information about the rules and any warm-up times that they require, see [Rules listing](aws-managed-rule-groups-bot.md#aws-managed-rule-groups-bot-rules).
+ **For distributed denial of service (DDoS) protection, use Shield Advanced automatic application layer DDoS mitigation** – The intelligent threat mitigation rule groups don't provide DDoS protection. ACFP protects against fraudulent account creation attempts to your application's sign-up page. ATP protects against account takeover attempts to your login page. Bot Control focuses on enforcing human-like access patterns using tokens and dynamic rate limiting on client sessions.

  When you use Shield Advanced with automatic application layer DDoS mitigation enabled, Shield Advanced automatically responds to detected DDoS attacks by creating, evaluating, and deploying custom AWS WAF mitigations on your behalf. For more information about Shield Advanced, see [AWS Shield Advanced overview](ddos-advanced-summary.md), and [Protecting the application layer (layer 7) with AWS Shield Advanced and AWS WAF](ddos-app-layer-protections.md).
+ **Use production traffic loads when you establish baselines for the Anti-DDoS rule group** – It is common practice to test other rule groups using artificial test traffic. However, when you test and establish baselines for the Anti-DDoS rule group, we recommend that you use traffic flows that reflect the loads in your production environment. Establishing Anti-DDoS baselines using typical traffic is the best way to ensure your resources will be protected when the rule group is enabled in a production environment.
+ **Tune and configure token handling** – Adjust the protection pack (web ACL)'s token handling for the best user experience. 
  + To reduce operating costs and improve your end user's experience, tune your token management immunity times to the longest that your security requirements permit. This keeps the use of CAPTCHA puzzles and silent challenges to a minimum. For information, see [Setting timestamp expiration and token immunity times in AWS WAF](waf-tokens-immunity-times.md).
  + To enable token sharing between protected applications, configure a token domain list for your protection pack (web ACL). For information, see [Specifying token domains and domain lists in AWS WAF](waf-tokens-domains.md).
+ **Reject requests with arbitrary host specifications** – Configure your protected resources to require that the `Host` headers in web requests match the targeted resource. You can accept one value or a specific set of values, for example `myExampleHost.com` and `www.myExampleHost.com`, but don’t accept arbitrary values for the host. 
+ **For Application Load Balancers that are origins for CloudFront distributions, configure CloudFront and AWS WAF for proper token handling** – If you associate your protection pack (web ACL) to an Application Load Balancer and you deploy the Application Load Balancer as the origin for a CloudFront distribution, see [Required configuration for Application Load Balancers that are CloudFront origins](waf-tokens-with-alb-and-cf.md).
+ **Test and tune before deploying** – Before you implement any changes to your protection pack (web ACL), follow the testing and tuning procedures in this guide to be sure that you're getting the behavior you expect. This is especially important for these paid features. For general guidance, see [Testing and tuning your AWS WAF protections](web-acl-testing.md). For information specific to the paid managed rule groups, see [Testing and deploying ACFP](waf-acfp-deploying.md), [Testing and deploying ATP](waf-atp-deploying.md), and [Testing and deploying AWS WAF Bot Control](waf-bot-control-deploying.md).

# Token use in AWS WAF intelligent threat mitigation
Tokens in intelligent threat mitigationNew section on AWS WAF tokens

Understand how AWS WAF uses tokens for intelligent threat mitigation. 

This section explains what AWS WAF tokens do.

AWS WAF tokens are an integral part of the enhanced protections offered by AWS WAF intelligent threat mitigation. A token, sometimes called a fingerprint, is a collection of information about a single client session that the client stores and provides with every web request that it sends. AWS WAF uses tokens to identify and separate malicious client sessions from legitimate sessions, even when both originate from a single IP address. Token use imposes costs that are negligible for legitimate users, but expensive at scale for botnets. 

AWS WAF uses tokens to support its browser and end user challenge functionality, which is provided by the application integration SDKs and by the rule actions Challenge and CAPTCHA. Additionally, tokens enable features of the AWS WAF Bot Control and account takeover prevention managed rule groups.

AWS WAF creates, updates, and encrypts tokens for clients that successfully respond to silent challenges and CAPTCHA puzzles. When a client with a token sends a web request, it includes the encrypted token, and AWS WAF decrypts the token and verifies its contents. 

**Topics**
+ [

# How AWS WAF uses tokens
](waf-tokens-usage.md)
+ [

# AWS WAF token characteristics
](waf-tokens-details.md)
+ [

# Setting timestamp expiration and token immunity times in AWS WAF
](waf-tokens-immunity-times.md)
+ [

# Specifying token domains and domain lists in AWS WAF
](waf-tokens-domains.md)
+ [

# Types of token labels in AWS WAF
](waf-tokens-labeling.md)
+ [

# Blocking requests that don't have a valid AWS WAF token
](waf-tokens-block-missing-tokens.md)
+ [

# Required configuration for Application Load Balancers that are CloudFront origins
](waf-tokens-with-alb-and-cf.md)

# How AWS WAF uses tokens
How AWS WAF uses tokens

This section explains how AWS WAF uses tokens.

AWS WAF uses tokens to record and verify the following types of client session validation: 
+ **CAPTCHA** – CAPTCHA puzzles help distinguish bots from human users. A CAPTCHA is run only by the CAPTCHA rule action. Upon successful completion of the puzzle, the CAPTCHA script updates the token's CAPTCHA timestamp. For more information, see [CAPTCHA and Challenge in AWS WAF](waf-captcha-and-challenge.md).
+ **Challenge** – Challenges run silently to help distinguish regular client sessions from bot sessions and to make it more costly for bots to operate. When the challenge completes successfully, the challenge script automatically procures a new token from AWS WAF if needed, and then updates the token's challenge timestamp. 

  AWS WAF runs challenges in the following situations: 
  + **Application integration SDKs** – The application integration SDKs run inside your client application sessions and help ensure that login attempts are only allowed after the client has successfully responded to a challenge. For more information, see [Client application integrations in AWS WAF](waf-application-integration.md).
  + **Challenge rule action** – For more information, see [CAPTCHA and Challenge in AWS WAF](waf-captcha-and-challenge.md).
  + **CAPTCHA** – When a CAPTCHA interstitial runs, if the client doesn't have a token yet, the script automatically runs a challenge first, to verify the client session and to initialize the token. 

Tokens are required by many of the rules in the intelligent threat AWS Managed Rules rule groups. The rules use tokens to do things like distinguish between clients at the session level, to determine browser characteristics, and to understand the level of human interactivity on the application web page. These rule groups invoke AWS WAF token management, which applies token labeling that the rule groups then inspect. 
+ **AWS WAF Fraud Control account creation fraud prevention (ACFP)** – The ACFP rules require web requests with valid tokens. For more information about the rules, see [AWS WAF Fraud Control account creation fraud prevention (ACFP) rule group](aws-managed-rule-groups-acfp.md).
+ **AWS WAF Fraud Control account takeover prevention (ATP)** – The ATP rules that prevent high volume and long lasting client sessions require web requests that have a valid token with an unexpired challenge timestamp. For more information, see [AWS WAF Fraud Control account takeover prevention (ATP) rule group](aws-managed-rule-groups-atp.md).
+ **AWS WAF Bot Control** – The targeted rules in this rule group place a limit on the number of web requests that a client can send without a valid token, and they use token session tracking for session-level monitoring and management. As needed, the rules apply the Challenge and CAPTCHA rule actions to enforce token acquisition and valid client behavior. For more information, see [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md).

# AWS WAF token characteristics
Token characteristics

Each token has the following characteristics: 
+ The token is stored in a cookie named `aws-waf-token`.
+ The token is encrypted.
+ The token fingerprints the client session with a sticky granular identifier that contains the following information: 
  + The timestamp of the client's latest successful response to a silent challenge. 
  + The timestamp of the end user's latest successful response to a CAPTCHA. This is only present if you use CAPTCHA in your protections. 
  + Additional information about the client and client behavior that can help separate your legitimate clients from unwanted traffic. The information includes various client identifiers and client-side signals that can be used to detect automated activities. The information gathered is non-unique and can't be mapped to an individual human being. 
    + All tokens include data from client browser interrogation, such as indications of automation and browser setting inconsistencies. This information is retrieved by the scripts that are run by the Challenge action and by the client application SDKs. The scripts actively interrogate the browser and put the results into the token. 
    + Additionally, when you implement a client application integration SDK, the token includes passively collected information about the end user's interactivity with the application page. Interactivity includes mouse movements, key presses, and interactions with any HTML form that's present on the page. This information helps AWS WAF detect the level of human interactivity in the client, to challenge users that do not seem to be human. For information about client side integrations, see [Client application integrations in AWS WAF](waf-application-integration.md).

For security reasons, AWS doesn't provide a complete description of the contents of AWS WAF tokens or detailed information about the token encryption process. 

# Setting timestamp expiration and token immunity times in AWS WAF
Setting timestamp expiration and token immunity times

This section explains how challenge and CAPTCHA timestamps expire.

AWS WAF uses challenge and CAPTCHA immunity times to control how frequently a single client session can be presented with a challenge or CAPTCHA. After an end user successfully responds to a CAPTCHA, the CAPTCHA immunity time determines how long the end user remains immune from being presented with another CAPTCHA. Similarly, the challenge immunity time determines how long a client session remains immune from being challenged again after successfully responding to a challenge. 

**How AWS WAF token immunity times work**

AWS WAF records a successful response to a challenge or CAPTCHA by updating the corresponding timestamp inside the token. When AWS WAF inspects the token for challenge or CAPTCHA, it subtracts the timestamp from the current time. If the result is greater than the configured immunity time, the timestamp is expired. 

**Configurable aspects of AWS WAF token immunity times**

You can configure the challenge and CAPTCHA immunity times in the protection pack (web ACL) and also in any rule that uses the CAPTCHA or Challenge rule action. 
+ The default protection pack (web ACL) setting for both immunity times is 300 seconds. 
+ You can specify the immunity time for any rule that uses the CAPTCHA or Challenge action. If you don't specify the immunity time for the rule, it inherits the setting from the protection pack (web ACL). 
+ For a rule inside a rule group that uses the CAPTCHA or Challenge action, if you don't specify the immunity time for the rule, it will inherit the setting from each protection pack (web ACL) where you use the rule group.
+ The application integration SDKs use the protection pack (web ACL)'s challenge immunity time. 
+ The minimum value for the challenge immunity time is 300 seconds. The minimum value for the CAPTCHA immunity time is 60 seconds. The maximum value for both immunity times is 259,200 seconds, or three days. 

You can use the protection pack (web ACL) and rule level immunity time settings to tune the CAPTCHA action, Challenge, or SDK challenge management behavior. For example, you might configure rules that control access to highly sensitive data with low immunity times, and then set higher immunity times in your protection pack (web ACL) for your other rules and the SDKs to inherit. 

In particular for CAPTCHA, solving a puzzle can degrade your customer's website experience, so tuning the CAPTCHA immunity time can help you mitigate the impact on customer experience while still providing the protections that you want. 

For additional information about tuning the immunity times for your use of the Challenge and CAPTCHA rule actions, see [Best practices for using the CAPTCHA and Challenge actions](waf-captcha-and-challenge-best-practices.md).

# Where to set the AWS WAF token immunity times
Where to set the immunity times

You can set the immunity times in your protection pack (web ACL) and in your rules that use the Challenge and CAPTCHA rule actions. 

For general information about managing a protection pack (web ACL) and its rules, see [Viewing web traffic metrics in AWS WAF](web-acl-working-with.md).

**Where to set the immunity time for a protection pack (web ACL)**
+ **Console** – When you edit the protection pack (web ACL), in the **Rules** tab, edit and change the settings in the **protection pack (web ACL) CAPTCHA configuration** and **protection pack (web ACL) Challenge configuration** panes. In the console, you can configure the protection pack (web ACL) CAPTCHA and challenge immunity times only after you've created the protection pack (web ACL).
+ **Outside of the console** – The protection pack (web ACL) data type has CAPTCHA and challenge configuration parameters, which you can configure and provide to your create and update operations on the protection pack (web ACL). 

**Where to set the immunity time for a rule**
+ **Console** – When you create or edit a rule and specify the CAPTCHA or Challenge action, you can modify the rule's immunity time setting. 
+ **Outside of the console** – The rule data type has CAPTCHA and challenge configuration parameters, which you can configure when you define the rule. 

# Specifying token domains and domain lists in AWS WAF
Specifying token domains and domain listsAWS WAF allows token sharing across multiple protected applications

You can enable the use of tokens across multiple protected applications by configuring a token domain list for your protection pack (web ACL). 

This section explains how to configure the domains that AWS WAF uses in tokens and that it accepts in tokens.

When AWS WAF creates a token for a client, it configures it with a token domain. When AWS WAF inspects a token in a web request, it rejects the token as invalid if its domain doesn't match any of the domains that are considered valid for the protection pack (web ACL). 

By default, AWS WAF only accepts tokens whose domain setting exactly matches the host domain of the resource that's associated with the protection pack (web ACL). This is the value of the `Host` header in the web request. In a browser, you can find this domain in the JavaScript `window.location.hostname` property and in the address that your user sees in their address bar. 

You can also specify acceptable token domains in your protection pack (web ACL) configuration, as described in the following section. In this case, AWS WAF accepts both exact matches with the host header and matches with domains in the token domain list.

You can specify token domains for AWS WAF to use when setting the domain and when evaluating a token in a protection pack (web ACL). The domains that you specify can't be public suffixes such as `gov.au`. For the domains that you can't use, see the list [https://publicsuffix.org/list/public_suffix_list.dat](https://publicsuffix.org/list/public_suffix_list.dat) under [Public suffix list](https://publicsuffix.org/list/).

## AWS WAF protection pack (web ACL) token domain list configuration
AWS WAF protection pack (web ACL) token domain list

You can configure a protection pack (web ACL) to share tokens across multiple protected resources by providing a token domain list with the additional domains that you want AWS WAF to accept. With a token domain list, AWS WAF still accepts the resource's host domain. Additionally, it accepts all domains in the token domain list, including their prefixed subdomains. 

For example, a domain specification `example.com` in your token domain list matches `example.com` (from `http://example.com/`), `api.example.com`, (from `http://api.example.com/`), and `www.example.com` (from `http://www.example.com/`). It doesn't match `example.api.com`, (from `http://example.api.com/`), or `apiexample.com` (from `http://apiexample.com/`).

You can configure the token domain list in your protection pack (web ACL) when you create or edit it. For general information about managing a protection pack (web ACL), see [Viewing web traffic metrics in AWS WAF](web-acl-working-with.md).

## AWS WAF token domain settings
Token domain settings

AWS WAF creates tokens at the request of the challenge scripts, which are run by the application integration SDKs and the Challenge and CAPTCHA rule actions. 

The domain that AWS WAF sets in a token is determined by the type of challenge script that's requesting it and any additional token domain configuration that you provide. AWS WAF sets the domain in the token to the shortest, most general setting that it can find in the configuration.
+ **JavaScript SDK** – You can configure the JavaScript SDK with a token domain specification, which can include one or more domains. The domains that you configure must be domains that AWS WAF will accept, based on the protected host domain and the protection pack (web ACL)'s token domain list. 

  When AWS WAF issues a token for the client, it sets the token domain to one that matches the host domain and is the shortest, from among the host domain and the domains in your configured list. For example, if the host domain is `api.example.com` and the token domain list has `example.com`, AWS WAF uses `example.com` in the token, because it matches the host domain and is shorter. If you don't provide a token domain list in the JavaScript API configuration, AWS WAF sets the domain to the host domain of the protected resource.

  For more information, see [Providing domains for use in the tokens](waf-js-challenge-api-set-token-domain.md). 
+ **Mobile SDK** – In your application code, you must configure the mobile SDK with a token domain property. This property must be a domain that AWS WAF will accept, based on the protected host domain and the protection pack (web ACL)'s token domain list. 

  When AWS WAF issues a token for the client, it uses this property as the token domain. AWS WAF doesn't use the host domain in the tokens that it issues for the mobile SDK client. 

  For more information, see the `WAFConfiguration` `domainName` setting at [AWS WAF mobile SDK specification](waf-mobile-sdk-specification.md). 
+ **Challenge action** – If you specify a token domain list in the protection pack (web ACL), AWS WAF sets the token domain to one that matches the host domain and is the shortest, from among the host domain and the domains in the list. For example, if the host domain is `api.example.com` and the token domain list has `example.com`, AWS WAF uses `example.com` in the token, because it matches the host domain and is shorter. If you don't provide a token domain list in the protection pack (web ACL), AWS WAF sets the domain to the host domain of the protected resource. 

# Types of token labels in AWS WAF
Types of token labelsAWS WAF challenge and CAPTCHA token labeling

Token management now adds labels for the CAPTCHA token and has enhanced the token labeling for the challenge token. AWS WAF token labeling adds browser fingerprint

Token management now adds a label for the browser fingerprint. 

This section describes the labels that AWS WAF token management adds to web requests. For general information about labels, see [Web request labeling in AWS WAF](waf-labels.md).

When you use any of the AWS WAF bot or fraud control managed rule groups, the rule groups use AWS WAF token management to inspect the web request tokens and apply token labeling to the requests. For information about the managed rule groups, see [AWS WAF Fraud Control account creation fraud prevention (ACFP) rule group](aws-managed-rule-groups-acfp.md), [AWS WAF Fraud Control account takeover prevention (ATP) rule group](aws-managed-rule-groups-atp.md), and [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md) .

**Note**  
AWS WAF applies token labels only when you use one of these intelligent threat mitigation managed rule groups. 

Token management can add the following labels to web requests.

**Client session label**  
The label `awswaf:managed:token:id:identifier` contains a unique identifier that AWS WAF token management uses to identify the client session. The identifier can change if the client acquires a new token, for example after discarding the token it was using. 

**Note**  
AWS WAF doesn't report Amazon CloudWatch metrics for this label.

**Browser fingerprint label**  
The label `awswaf:managed:token:fingerprint:fingerprint-identifier` contains a robust browser fingerprint identifier that AWS WAF token management computes from various client browser signals. This identifier stays the same across multiple token acquisition attempts. The fingerprint identifier is not unique to a single client.

**Note**  
AWS WAF doesn't report Amazon CloudWatch metrics for this label.

**Token status labels: Label namespace prefixes**  
Token status labels report on the status of the token and of the challenge and CAPTCHA information that it contains. 

Each token status label begins with one of the following namespace prefixes: 
+ `awswaf:managed:token:` – Used to report the general status of the token and to report on the status of the token's challenge information. 
+ `awswaf:managed:captcha:` – Used to report on the status of the token's CAPTCHA information. 

**Token status labels: Label names**  
Following the prefix, the rest of the label provides detailed token status information: 
+ `accepted` – The request token is present and contains the following: 
  + A valid challenge or CAPTCHA solution.
  + An unexpired challenge or CAPTCHA timestamp.
  + A domain specification that's valid for the protection pack (web ACL). 

  Example: The label `awswaf:managed:token:accepted` indicates that the web requests's token has a valid challenge solution, an unexpired challenge timestamp, and a valid domain.
+ `rejected` – The request token is present but doesn't meet the acceptance criteria. 

  Along with the rejected label, token management adds a custom label namespace and name to indicate the reason. 
  + `rejected:not_solved` – The token is missing the challenge or CAPTCHA solution. 
  + `rejected:expired` – The token's challenge or CAPTCHA timestamp has expired, according to your protection pack (web ACL)'s configured token immunity times. 
  + `rejected:domain_mismatch` – The token's domain isn't a match for your protection pack (web ACL)'s token domain configuration. 
  + `rejected:invalid` – AWS WAF couldn't read the indicated token. 

  Example: The labels `awswaf:managed:captcha:rejected` and `awswaf:managed:captcha:rejected:expired` together indicate that the request didn't have a valid CAPTCHA solve because the CAPTCHA timestamp in the token has exceeded the CAPTCHA token immunity time that's configured in the protection pack (web ACL).
+ `absent` – The request doesn't have the token or the token manager couldn't read it. 

  Example: The label `awswaf:managed:captcha:absent` indicates that the request doesn't have the token. 

# Blocking requests that don't have a valid AWS WAF token
Blocking requests that don't have a valid token

This section explains how to block login requests that are missing their tokens when using the AWS WAF mobile SDK.

When you use the intelligent threat AWS Managed Rules rule groups `AWSManagedRulesACFPRuleSet`, `AWSManagedRulesATPRuleSet`, and `AWSManagedRulesBotControlRuleSet`, the rule groups invoke AWS WAF token management to evaluate the status of the web request token and to label the requests accordingly. 

**Note**  
Token labeling is only applied to web requests that you evaluate using one of these managed rule groups.

For information about the labeling that token management applies, see the preceding section, [Types of token labels in AWS WAF](waf-tokens-labeling.md). 

The intelligent threat mitigation managed rule groups then handle token requirements as follows:
+ The `AWSManagedRulesACFPRuleSet` `AllRequests` rule is configured to run the Challenge action against all requests, effectively blocking any that don't have the `accepted` token label. 
+ The `AWSManagedRulesATPRuleSet` blocks requests that have the `rejected` token label, but it doesn't block requests with the `absent` token label. 
+ The `AWSManagedRulesBotControlRuleSet` targeted protection level challenges clients after they send five requests without an `accepted` token label. It doesn't block an individual request that doesn't have a valid token. The common protection level of the rule group doesn't manage token requirements. 

For additional details about the intelligent threat rule groups, see [AWS WAF Fraud Control account creation fraud prevention (ACFP) rule group](aws-managed-rule-groups-acfp.md), [AWS WAF Fraud Control account takeover prevention (ATP) rule group](aws-managed-rule-groups-atp.md) and [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md). 

**To block requests that are missing tokens when using the Bot Control or ATP managed rule group**  
With the Bot Control and ATP rule groups, it's possible for a request without a valid token to exit the rule group evaluation and continue to be evaluated by the protection pack (web ACL). 

To block all requests that are missing their token or whose token is rejected, add a rule to run immediately after the managed rule group to capture and block requests that the rule group doesn't handle for you. 

The following is an example JSON listing for a protection pack (web ACL) that uses the ATP managed rule group. The protection pack (web ACL) has an added rule to capture the `awswaf:managed:token:absent` label and handle it. The rule narrows its evaluation to web requests going to the login endpoint, to match the scope of the ATP rule group. The added rule is listed in bold. 

```
{
  "Name": "exampleWebACL",
  "Id": "55555555-6666-7777-8888-999999999999",
  "ARN": "arn:aws:wafv2:us-east-1:111111111111:regional/webacl/exampleWebACL/55555555-4444-3333-2222-111111111111",
  "DefaultAction": {
    "Allow": {}
  },
  "Description": "",
  "Rules": [
    {
      "Name": "AWS-AWSManagedRulesATPRuleSet",
      "Priority": 1,
      "Statement": {
        "ManagedRuleGroupStatement": {
          "VendorName": "AWS",
          "Name": "AWSManagedRulesATPRuleSet",
          "ManagedRuleGroupConfigs": [
            {
              "AWSManagedRulesATPRuleSet": {
                "LoginPath": "/web/login",
                "RequestInspection": {
                  "PayloadType": "JSON",
                  "UsernameField": {
                    "Identifier": "/form/username"
                  },
                  "PasswordField": {
                    "Identifier": "/form/password"
                  }
                },
                "ResponseInspection": {
                  "StatusCode": {
                    "SuccessCodes": [
                      200
                    ],
                    "FailureCodes": [
                      401,
                      403,
                      500
                    ]
                  }
                }
              }  
            }
          ]
        }
      },
      "OverrideAction": {
        "None": {}
      },
      "VisibilityConfig": {
        "SampledRequestsEnabled": true,
        "CloudWatchMetricsEnabled": true,
        "MetricName": "AWS-AWSManagedRulesATPRuleSet"
      }
    },
    {
      "Name": "RequireTokenForLogins",
      "Priority": 2,
      "Statement": {
        "AndStatement": {
          "Statements": [
            {
              "Statement": {
                "LabelMatchStatement": {
                  "Scope": "LABEL",
                  "Key": "awswaf:managed:token:absent"
                }
              }
            },
            {
              "ByteMatchStatement": {
                "SearchString": "/web/login",
                "FieldToMatch": {
                  "UriPath": {}
                },
                "TextTransformations": [
                  {
                    "Priority": 0,
                    "Type": "NONE"
                 }
                ],
                "PositionalConstraint": "STARTS_WITH"
              }
            },
            {
              "ByteMatchStatement": {
                "SearchString": "POST",
                "FieldToMatch": {
                  "Method": {}
                },
                "TextTransformations": [
                  {
                    "Priority": 0,
                    "Type": "NONE"
                  }
                ],
                "PositionalConstraint": "EXACTLY"
              }
            }
          ]
        }
      },
      "Action": {
        "Block": {}
      },
      "VisibilityConfig": {
        "SampledRequestsEnabled": true,
        "CloudWatchMetricsEnabled": true,
        "MetricName": "RequireTokenForLogins"
      } 
    }
  ],
  "VisibilityConfig": {
    "SampledRequestsEnabled": true,
    "CloudWatchMetricsEnabled": true,
    "MetricName": "exampleWebACL"
  },
  "Capacity": 51,
  "ManagedByFirewallManager": false,
  "RetrofittedByFirewallManager": false,
  "LabelNamespace": "awswaf:111111111111:webacl:exampleWebACL:"
}
```

# Required configuration for Application Load Balancers that are CloudFront origins
Configuration for Application Load Balancers that are CloudFront origins

Read this section if you associate your protection pack (web ACL) to an Application Load Balancer and you deploy the Application Load Balancer as the origin for a CloudFront distribution.

With this architecture, you need to provide the following additional configuration in order for the token information to be handled correctly.
+ Configure CloudFront to forward the `aws-waf-token` cookie to the Application Load Balancer. By default, CloudFront removes cookies from the web request before forwarding it to the origin. To keep the token cookie with the web request, configure CloudFront cache behavior to include either just the token cookie or all cookies. For information about how to do this, see [Caching content based on cookies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Cookies.html) in the *Amazon CloudFront Developer Guide*.
+ Configure AWS WAF so that it recognizes the domain of the CloudFront distribution as a valid token domain. By default, CloudFront sets the `Host` header to the Application Load Balancer origin, and AWS WAF uses that as the domain of the protected resource. The client browser, however, sees the CloudFront distribution as the host domain, and tokens that are generated for the client use the CloudFront domain as the token domain. Without any additional configuration, when AWS WAF checks the protected resource domain against the token domain, it will get a mismatch. To fix this, add the CloudFront distribution domain name to the token domain list in your protection pack (web ACL) configuration. For information about how to do this, see [AWS WAF protection pack (web ACL) token domain list configuration](waf-tokens-domains.md#waf-tokens-domain-lists).

# AWS WAF Fraud Control account creation fraud prevention (ACFP)
AWS WAF Fraud Control account creation fraud prevention (ACFP)New AWS WAF Fraud Control account creation fraud prevention (ACFP)

You can detect and block fraudulent account creation attempts with the new AWS WAF Fraud Control account creation fraud prevention (ACFP) managed rule group `AWSManagedRulesACFPRuleSet`. With protected CloudFront distributions, you can also use ACFP to block new account creation attempts from clients that have recently submitted too many failed account creation attempts. 

This section explains what AWS WAF Fraud Control account creation fraud prevention (ACFP) does.

Account creation fraud is an online illegal activity in which an attacker tries to create one or more fake accounts. Attackers use fake accounts for fraudulent activities such as abusing promotional and sign up bonuses, impersonating someone, and cyberattacks like phishing. The presence of fake accounts can negatively impact your business by damaging your reputation with customers and exposure to financial fraud. 

You can monitor and control account creation fraud attempts by implementing the ACFP feature. AWS WAF offers this feature in the AWS Managed Rules rule group `AWSManagedRulesACFPRuleSet` with companion application integration SDKs. 

The ACFP managed rule group labels and manages requests that might be part of malicious account creation attempts. The rule group does this by inspecting account creation attempts that clients send to your application's account sign-up endpoint. 

ACFP protects your account sign-up pages by monitoring account sign-up requests for anomalous activity and by automatically blocking suspicious requests. The rule group uses request identifiers, behavioral analysis, and machine learning to detect fraudulent requests. 
+ **Request inspection** – ACFP gives you visibility and control over anomalous account creation attempts and attempts that use stolen credentials, to prevent the creation of fraudulent accounts. ACFP checks email and password combinations against its stolen credential database, which is updated regularly as new leaked credentials are found on the dark web. ACFP evaluates the domains used in email addresses, and monitors the use of phone numbers and address fields to verify the entries and to detects fraudulent behavior. ACFP aggregates data by IP address and client session, to detect and block clients that send too many requests of a suspicious nature. 
+ **Response inspection** – For CloudFront distributions, in addition to inspecting incoming account creation requests, the ACFP rule group inspects your application's responses to account creation attempts, to track success and failure rates. Using this information, ACFP can temporarily block client sessions or IP addresses that have too many failed attempts. AWS WAF performs response inspection asynchronously, so this doesn't increase latency in your web traffic. 

**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

**Note**  
The ACFP feature is not available for Amazon Cognito user pools.

**Topics**
+ [

# AWS WAF ACFP components
](waf-acfp-components.md)
+ [

# Using application integration SDKs with ACFP
](waf-acfp-with-tokens.md)
+ [

# Adding the ACFP managed rule group to your web ACL
](waf-acfp-rg-using.md)
+ [

# Testing and deploying ACFP
](waf-acfp-deploying.md)
+ [

# AWS WAF Fraud Control account creation fraud prevention (ACFP) examples
](waf-acfp-control-examples.md)

# AWS WAF ACFP components
ACFP components

The primary components of AWS WAF Fraud Control account creation fraud prevention (ACFP) are the following: 
+ **`AWSManagedRulesACFPRuleSet`** – The rules in this AWS Managed Rules rule group detect, label, and handle various types of fraudulent account creation activity. The rule group inspects HTTP `GET` text/html requests that clients send to the specified account registration endpoint and `POST` web requests that clients send to the specified account sign-up endpoint. For protected CloudFront distributions, the rule group also inspects the responses that the distribution sends back to account creation requests. For a list of this rule group's rules, see [AWS WAF Fraud Control account creation fraud prevention (ACFP) rule group](aws-managed-rule-groups-acfp.md). You include this rule group in your protection pack (web ACL) using a managed rule group reference statement. For information about using this rule group, see [Adding the ACFP managed rule group to your web ACL](waf-acfp-rg-using.md). 
**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).
+ **Details about your application's account registration and creation pages** – You must provide information about your account registration and creation pages when you add the `AWSManagedRulesACFPRuleSet` rule group to your protection pack (web ACL). This lets the rule group narrow the scope of the requests it inspects and properly validate account creation web requests. The registration page must accept `GET` text/html requests. The account creation path must accept `POST` requests. The ACFP rule group works with usernames that are in email format. For more information, see [Adding the ACFP managed rule group to your web ACL](waf-acfp-rg-using.md). 
+ **For protected CloudFront distributions, details about how your application responds to account creation attempts** – You provide details about your application's responses to account creation attempts, and the ACFP rule group tracks and manages bulk account creation attempts from a single IP address or single client session. For information about configuring this option, see [Adding the ACFP managed rule group to your web ACL](waf-acfp-rg-using.md). 
+ **JavaScript and mobile application integration SDKs** – Implement the AWS WAF JavaScript and mobile SDKs with your ACFP implementation to enable the full set of capabilities that the rule group offers. Many of the ACFP rules use the information provided by the SDKs for session level client verification and behavior aggregation, required to separate legitimate client traffic from bot traffic. For more information about the SDKs, see [Client application integrations in AWS WAF](waf-application-integration.md).

You can combine your ACFP implementation with the following to help you monitor, tune, and customize your protections. 
+ **Logging and metrics** – You can monitor your traffic, and understand how the ACFP managed rule group affects it, by configuring and enabling logs, Amazon Security Lake data collection, and Amazon CloudWatch metrics for your protection pack (web ACL). The labels that `AWSManagedRulesACFPRuleSet` adds to your web requests are included in the data. For information about the options, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md), [Monitoring with Amazon CloudWatch](monitoring-cloudwatch.md), and [What is Amazon Security Lake?](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html).

  Depending on your needs and the traffic that you see, you might want to customize your `AWSManagedRulesACFPRuleSet` implementation. For example, you might want to exclude some traffic from ACFP evaluation, or you might want to alter how it handles some of the account creation fraud attempts that it identifies, using AWS WAF features like scope-down statements or label matching rules. 
+ **Labels and label matching rules** – For any of the rules in `AWSManagedRulesACFPRuleSet`, you can switch the blocking behavior to count, and then match against the labels that are added by the rules. Use this approach to customize how you handle web requests that are identified by the ACFP managed rule group. For more information about labeling and using label match statements, see [Label match rule statement](waf-rule-statement-type-label-match.md) and [Web request labeling in AWS WAF](waf-labels.md). 
+ **Custom requests and responses** – You can add custom headers to the requests that you allow and you can send custom responses for requests that you block. To do this, you pair your label matching with the AWS WAF custom request and response features. For more information about customizing requests and responses, see [Customized web requests and responses in AWS WAF](waf-custom-request-response.md).

# Using application integration SDKs with ACFP
Using application integration SDKs with ACFP

We highly recommend implementing the application integration SDKs, for the most efficient use of the ACFP rule group. 
+ **Complete rule group functionality** – The ACFP rule `SignalClientHumanInteractivityAbsentLow` only works with tokens that are populated by the application integrations. This rule detects and manages abnormal human interactivity with the application page. The application integration SDKs can detect normal human interactivity through mouse movements, key presses, and other measurements. The interstitials that are sent by the rule actions CAPTCHA and Challenge can't provide this type of data. 
+ **Reduced latency** – The rule group rule `AllRequests` applies the Challenge rule action to any request that doesn't already have a challenge token. When this happens, the request is evaluated by the rule group twice: once without the token, and then a second time after the token is acquired by means of the Challenge action interstitial. You aren't charged any added fees for only using the `AllRequests` rule, but this approach adds overhead to your web traffic and adds latency to your end user experience. If you acquire the token client-side using the application integrations, before sending the account creation request, the ACFP rule group evaluates the request once. 

For more information about the rule group capabilities see [AWS WAF Fraud Control account creation fraud prevention (ACFP) rule group](aws-managed-rule-groups-acfp.md).

For information about the SDKs, see [Client application integrations in AWS WAF](waf-application-integration.md). For information about AWS WAF tokens, see [Token use in AWS WAF intelligent threat mitigation](waf-tokens.md). For information about the rule actions, see [CAPTCHA and Challenge in AWS WAF](waf-captcha-and-challenge.md).

# Adding the ACFP managed rule group to your web ACL
Adding the ACFP managed rule group to your protection pack (web ACL)

This section explains how to add and configure the `AWSManagedRulesACFPRuleSet` rule group.

To configure the ACFP managed rule group to recognize account creation fraud activities in your web traffic, you provide information about how clients access your registration page and send account creation requests to your application. For protected Amazon CloudFront distributions, you also provide information about how your application responds to account creation requests. This configuration is in addition to the normal configuration for a managed rule group. 

For the rule group description and rules listing, see [AWS WAF Fraud Control account creation fraud prevention (ACFP) rule group](aws-managed-rule-groups-acfp.md).

**Note**  
The ACFP stolen credentials database only contains usernames in email format.

This guidance is intended for users who know generally how to create and manage AWS WAF protection packs (web ACLs), rules, and rule groups. Those topics are covered in prior sections of this guide. For basic information about how to add a managed rule group to your protection pack (web ACL), see [Adding a managed rule group to a protection pack (web ACL) through the console](waf-using-managed-rule-group.md).

**Follow best practices**  
Use the ACFP rule group in accordance with the best practices at [Best practices for intelligent threat mitigation in AWS WAF](waf-managed-protections-best-practices.md). 

**To use the `AWSManagedRulesACFPRuleSet` rule group in your protection pack (web ACL)**

1. Add the AWS managed rule group, `AWSManagedRulesACFPRuleSet` to your protection pack (web ACL), and **Edit** the rule group settings before saving. 
**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

1. In the **Rule group configuration** pane, provide the information that the ACFP rule group uses to inspect account creation requests. 

   1. For **Use regular expression in paths**, toggle this on if you want AWS WAF to perform regular expression matching for your registration and account creation page path specifications. 

      AWS WAF supports the pattern syntax used by the PCRE library `libpcre` with some exceptions. The library is documented at [PCRE - Perl Compatible Regular Expressions](http://www.pcre.org/). For information about AWS WAF support, see [Supported regular expression syntax in AWS WAF](waf-regex-pattern-support.md).

   1. For **Registration page path**, provide the path of the registration page endpoint for your application. This page must accept `GET` text/html requests. The rule group inspects only HTTP `GET` text/html requests to your specified registration page endpoint.
**Note**  
Matching for endpoints is case insensitive. Regex specifications must not contain the flag `(?-i)`, which disables case insensitive matching. String specifications must start with a forward slash `/`.

      For example, for the URL `https://example.com/web/registration`, you could provide the string path specification `/web/registration`. Registration page paths that start with the path that you provide are considered a match. For example `/web/registration` matches the registration paths `/web/registration`, `/web/registration/`, `/web/registrationPage`, and `/web/registration/thisPage`, but doesn't match the path `/home/web/registration` or `/website/registration`. 
**Note**  
Ensure that your end users load the registration page before they submit an account creation request. This helps ensure that the account creation requests from the client include valid tokens. 

   1. For **Account creation path**, provide the URI in your website that accepts completed new user details. This URI must accept `POST` requests.
**Note**  
Matching for endpoints is case insensitive. Regex specifications must not contain the flag `(?-i)`, which disables case insensitive matching. String specifications must start with a forward slash `/`.

      For example, for the URL `https://example.com/web/newaccount`, you could provide the string path specification `/web/newaccount`. Account creation paths that start with the path that you provide are considered a match. For example `/web/newaccount` matches the account creation paths `/web/newaccount`, `/web/newaccount/`, `/web/newaccountPage`, and `/web/newaccount/thisPage`, but doesn't match the path `/home/web/newaccount` or `/website/newaccount`. 

   1. For **Request inspection**, specify how your application accepts account creation attempts by providing the request payload type and the names of the fields within the request body where the username, password, and other account creation details are provided. 
**Note**  
For the primary address and phone number fields, provide the fields in the order in which they appear in the request payload.

      Your specification of the field names depends on the payload type.
      + **JSON payload type** – Specify the field names in JSON pointer syntax. For information about the JSON Pointer syntax, see the Internet Engineering Task Force (IETF) documentation [JavaScript Object Notation (JSON) Pointer](https://tools.ietf.org/html/rfc6901). 

        For example, for the following example JSON payload, the username field specification is `/signupform/username` and the primary address field specifications are `/signupform/addrp1`, `/signupform/addrp2`, and `/signupform/addrp3`.

        ```
        {
            "signupform": {
                "username": "THE_USERNAME",
                "password": "THE_PASSWORD",
                "addrp1": "PRIMARY_ADDRESS_LINE_1",
                "addrp2": "PRIMARY_ADDRESS_LINE_2",
                "addrp3": "PRIMARY_ADDRESS_LINE_3",
                "phonepcode": "PRIMARY_PHONE_CODE",
                "phonepnumber": "PRIMARY_PHONE_NUMBER"
            }
        }
        ```
      + **FORM\$1ENCODED payload type** – Use the HTML form names.

        For example, for an HTML form with user and password input elements named `username1` and `password1`, the username field specification is `username1` and the password field specification is `password1`.

   1. If you're protecting Amazon CloudFront distributions, then under **Response inspection**, specify how your application indicates success or failure in its responses to account creation attempts. 
**Note**  
ACFP response inspection is available only in protection packs (web ACLs) that protect CloudFront distributions.

      Specify a single component in the account creation response that you want ACFP to inspect. For the **Body** and **JSON** component types, AWS WAF can inspect the first 65,536 bytes (64 KB) of the component. 

      Provide your inspection criteria for the component type, as indicated by the interface. You must provide both success and failure criteria to inspect for in the component. 

      For example, say your application indicates the status of an account creation attempt in the status code of the response, and uses `200 OK` for success and `401 Unauthorized` or `403 Forbidden` for failure. You would set the response inspection **Component type** to **Status code**, then in the **Success** text box enter `200` and in the **Failure** text box, enter `401` on the first line and `403` on the second.

      The ACFP rule group only counts responses that match your success or failure inspection criteria. The rule group rules act on clients while they have too high a success rate among the responses that are counted, in order to mitigate bulk account creation attempts. For accurate behavior by the rule group rules, be sure to provide complete information for both successful and failed account creation attempts. 

      To see the rules that inspect account creation responses, look for `VolumetricIPSuccessfulResponse` and `VolumetricSessionSuccessfulResponse` in the rules listing at [AWS WAF Fraud Control account creation fraud prevention (ACFP) rule group](aws-managed-rule-groups-acfp.md). 

1. Provide any additional configuration that you want for the rule group. 

   You can further limit the scope of requests that the rule group inspects by adding a scope-down statement to the managed rule group statement. For example, you can inspect only requests with a specific query argument or cookie. The rule group will only inspect requests that match the criteria in your scope-down statement and that are sent to the account registration and account creation paths that you specified in the rule group configuration. For information about scope-down statements, see [Using scope-down statements in AWS WAF](waf-rule-scope-down-statements.md).

1. Save your changes to the protection pack (web ACL). 

Before you deploy your ACFP implementation for production traffic, test and tune it in a staging or testing environment until you are comfortable with the potential impact to your traffic. Then test and tune the rules in count mode with your production traffic before enabling them. See the section that follows for guidance. 

# Testing and deploying ACFP
Testing and deploying ACFP

This section provides general guidance for configuring and testing an AWS WAF Fraud Control account creation fraud prevention (ACFP) implementation for your site. The specific steps that you choose to follow will depend on your needs, resources, and web requests that you receive. 

This information is in addition to the general information about testing and tuning provided at [Testing and tuning your AWS WAF protections](web-acl-testing.md).

**Note**  
AWS Managed Rules are designed to protect you from common web threats. When used in accordance with the documentation, AWS Managed Rules rule groups add another layer of security for your applications. However, AWS Managed Rules rule groups aren't intended as a replacement for your security responsibilities, which are determined by the AWS resources that you select. Refer to the [Shared Responsibility Model](https://aws.amazon.com/compliance/shared-responsibility-model/) to ensure that your resources in AWS are properly protected. 

**Production traffic risk**  
Before you deploy your ACFP implementation for production traffic, test and tune it in a staging or testing environment until you are comfortable with the potential impact to your traffic. Then test and tune the rules in count mode with your production traffic before enabling them. 

AWS WAF provides test credentials that you can use to verify your ACFP configuration. In the following procedure, you'll configure a test protection pack (web ACL) to use the ACFP managed rule group, configure a rule to capture the label added by the rule group, and then run an account creation attempt using these test credentials. You'll verify that your protection pack (web ACL) has properly managed the attempt by checking the Amazon CloudWatch metrics for the account creation attempt. 

This guidance is intended for users who know generally how to create and manage AWS WAF protection packs (web ACLs), rules, and rule groups. Those topics are covered in prior sections of this guide. 

**To configure and test an AWS WAF Fraud Control account creation fraud prevention (ACFP) implementation**

Perform these steps first in a test environment, then in production.

1. 

**Add the AWS WAF Fraud Control account creation fraud prevention (ACFP) managed rule group in count mode**
**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

   Add the AWS Managed Rules rule group `AWSManagedRulesACFPRuleSet` to a new or existing protection pack (web ACL) and configure it so that it doesn't alter the current protection pack (web ACL) behavior. For details about the rules and labels for this rule group, see [AWS WAF Fraud Control account creation fraud prevention (ACFP) rule group](aws-managed-rule-groups-acfp.md).
   + When you add the managed rule group, edit it and do the following: 
     + In the **Rule group configuration** pane, provide the details of your application's account registration and creation pages. The ACFP rule group uses this information to monitor sign-in activities. For more information, see [Adding the ACFP managed rule group to your web ACL](waf-acfp-rg-using.md).
     + In the **Rules** pane, open the **Override all rule actions** dropdown and choose **Count**. With this configuration, AWS WAF evaluates requests against all of the rules in the rule group and only counts the matches that result, while still adding labels to requests. For more information, see [Overriding rule actions in a rule group](web-acl-rule-group-settings.md#web-acl-rule-group-rule-action-override).

       With this override, you can monitor the potential impact of the ACFP managed rules to determine whether you want to add exceptions, such as exceptions for internal use cases. 
   + Position the rule group so that it's evaluated after your existing rules in the protection pack (web ACL), with a priority setting that's numerically higher than any rules or rule groups that you're already using. For more information, see [Setting rule priority](web-acl-processing-order.md). 

     This way, your current handling of traffic isn't disrupted. For example, if you have rules that detect malicious traffic such as SQL injection or cross-site scripting, they'll continue to detect and log that. Alternately, if you have rules that allow known non-malicious traffic, they can continue to allow that traffic, without having it blocked by the ACFP managed rule group. You might decide to adjust the processing order during your testing and tuning activities.

1. 

**Implement the application integration SDKs**

   Integrate the AWS WAF JavaScript SDK into your browser's account registration and account creation paths. AWS WAF also provides mobile SDKs to integrate iOS and Android devices. For more information about the integration SDKs, see [Client application integrations in AWS WAF](waf-application-integration.md). For information about this recommendation, see [Using application integration SDKs with ACFP](waf-acfp-with-tokens.md).
**Note**  
If you are unable to use the application integration SDKs, it's possible to test the ACFP rule group by editing it in your protection pack (web ACL) and removing the override that you placed on the `AllRequests` rule. This enables the rule's Challenge action setting, to ensure that requests include a valid challenge token.   
*Do this first in a test environment and then with great care in your production environment.* This approach has the potential to block users. For example, if your registration page path doesn't accept `GET` text/html requests, then this rule configuration can effectively block all requests at the registration page. 

1. 

**Enable logging and metrics for the protection pack (web ACL)**

   As needed, configure logging, Amazon Security Lake data collection, request sampling, and Amazon CloudWatch metrics for the protection pack (web ACL). You can use these visibility tools to monitor the interaction of the ACFP managed rule group with your traffic. 
   + For information about logging, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md). 
   + For information about Amazon Security Lake, see [What is Amazon Security Lake?](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html) and [Collecting data from AWS services](https://docs.aws.amazon.com/security-lake/latest/userguide/internal-sources.html) in the *Amazon Security Lake user guide*. 
   + For information about Amazon CloudWatch metrics, see [Monitoring with Amazon CloudWatch](monitoring-cloudwatch.md). 
   + For information about web request sampling, see [Viewing a sample of web requests](web-acl-testing-view-sample.md). 

1. 

**Associate the protection pack (web ACL) with a resource**

   If the protection pack (web ACL) isn't already associated with a test resource, associate it. For information, see [Associating or disassociating protection with an AWS resource](web-acl-associating-aws-resource.md).

1. 

**Monitor traffic and ACFP rule matches**

   Make sure that your normal traffic is flowing and that the ACFP managed rule group rules are adding labels to matching web requests. You can see the labels in the logs and see the ACFP and label metrics in the Amazon CloudWatch metrics. In the logs, the rules that you've overridden to count in the rule group show up in the `ruleGroupList` with `action` set to count, and with `overriddenAction` indicating the configured rule action that you overrode. 

1. 

**Test the rule group's credential checking capabilities**

   Perform an account creation attempt with test compromised credentials and check that the rule group matches against them as expected. 

   1. Access your protected resource's account registration page and try to add a new account. Use the following AWS WAF test credential pair and enter any test 
      + User: `WAF_TEST_CREDENTIAL@wafexample.com`
      + Password: `WAF_TEST_CREDENTIAL_PASSWORD`

      These test credentials are categorized as compromised credentials, and the ACFP managed rule group will add the `awswaf:managed:aws:acfp:signal:credential_compromised` label to the account creation request, which you can see in the logs. 

   1. In your protection pack (web ACL) logs, look for the `awswaf:managed:aws:acfp:signal:credential_compromised` label in the `labels` field on the log entries for your test account creation request. For information about logging, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md). 

   After you've verified that the rule group captures compromised credentials as expected, you can take steps to configure its implementation as you need for your protected resource.

1. 

**For CloudFront distributions, test the rule group's management of bulk account creation attempts**

   Run this test for each success response criteria that you configured for the ACFP rule group. Wait at least 30 minutes between tests.

   1. For each of your success criteria, identify an account creation attempt that will succeed with that success criteria in the response. Then, from a single client session, perform at least 5 successful account creation attempts in under 30 minutes. A user would normally only create a single account on your site. 

      After the first successful account creation, the `VolumetricSessionSuccessfulResponse` rule should start matching against the rest of your account creation responses, labeling them and counting them, based on your rule action override. The rule might miss the first one or two due to latency. 

   1. In your protection pack (web ACL) logs, look for the `awswaf:managed:aws:acfp:aggregate:volumetric:session:successful_creation_response:high` label in the `labels` field on the log entries for your test account creation web requests. For information about logging, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md). 

   These tests verify that your success criteria match your responses by checking that the successful counts aggregated by the rule surpass the rule's threshold. After you've reached the threshold, if you continue to send account creation requests from the same session, the rule will continue to match until the success rate drops below the threshold. While the threshold is exceeded, the rule matches both successful or failed account creation attempts from the session address. 

1. 

**Customize ACFP web request handling**

   As needed, add your own rules that explicitly allow or block requests, to change how ACFP rules would otherwise handle them. 

   For example, you can use ACFP labels to allow or block requests or to customize request handling. You can add a label match rule after the ACFP managed rule group to filter labeled requests for the handling that you want to apply. After testing, keep the related ACFP rules in count mode, and maintain the request handling decisions in your custom rule. For an example, see [ACFP example: Custom response for compromised credentials](waf-acfp-control-example-compromised-credentials.md). 

1. 

**Remove your test rules and enable the ACFP managed rule group settings**

   Depending on your situation, you might have decided that you want to leave some ACFP rules in count mode. For the rules that you want to run as configured inside the rule group, disable count mode in the protection pack (web ACL) rule group configuration. When you're finished testing, you can also remove your test label match rules.

1. 

**Monitor and tune**

   To be sure that web requests are being handled as you want, closely monitor your traffic after you enable the ACFP functionality that you intend to use. Adjust the behavior as needed with the rules count override on the rule group and with your own rules. 

After you finish testing your ACFP rule group implementation, if you haven't already integrated the AWS WAF JavaScript SDK into your browser's account registration and account creation pages, we strongly recommend that you do so. AWS WAF also provides mobile SDKs to integrate iOS and Android devices. For more information about the integration SDKs, see [Client application integrations in AWS WAF](waf-application-integration.md). For information about this recommendation, see [Using application integration SDKs with ACFP](waf-acfp-with-tokens.md).

# AWS WAF Fraud Control account creation fraud prevention (ACFP) examples
ACFP examplesUpdated ACFP examples

Added example depicting response inspection configuration.

This section shows example configurations that satisfy common use cases for the AWS WAF Fraud Control account creation fraud prevention (ACFP) implementations. 

Each example provides a description of the use case and then shows the solution in JSON listings for the custom configured rules. 

**Note**  
You can retrieve JSON listings like the ones shown in these examples through the console protection pack (web ACL) JSON download or rule JSON editor, or through the `getWebACL` operation in the APIs and the command line interface. 

**Topics**
+ [

# ACFP example: Simple configuration
](waf-acfp-control-example-basic.md)
+ [

# ACFP example: Custom response for compromised credentials
](waf-acfp-control-example-compromised-credentials.md)
+ [

# ACFP example: Response inspection configuration
](waf-acfp-control-example-response-inspection.md)

# ACFP example: Simple configuration
Simple configuration

The following JSON listing shows an example protection pack (web ACL) with an AWS WAF Fraud Control account creation fraud prevention (ACFP) managed rule group. Note the additional `CreationPath` and `RegistrationPagePath` configurations, along with the payload type and the information needed to locate new account information in the payload, in order to verify it. The rule group uses this information to monitor and manage your account creation requests. This JSON includes the protection pack (web ACL)'s automatically generated settings, like the label namespace and the protection pack (web ACL)'s application integration URL.

```
{
  "Name": "simpleACFP",
  "Id": "... ",
  "ARN": "arn:aws:wafv2:us-east-1:111122223333:regional/webacl/simpleACFP/... ",
  "DefaultAction": {
    "Allow": {}
  },
  "Description": "",
  "Rules": [
    {
      "Name": "AWS-AWSManagedRulesACFPRuleSet",
      "Priority": 0,
      "Statement": {
        "ManagedRuleGroupStatement": {
          "VendorName": "AWS",
          "Name": "AWSManagedRulesACFPRuleSet",
          "ManagedRuleGroupConfigs": [
            {
              "AWSManagedRulesACFPRuleSet": {
                "CreationPath": "/web/signup/submit-registration",
                "RegistrationPagePath": "/web/signup/registration",
                "RequestInspection": {
                  "PayloadType": "JSON",
                  "UsernameField": {
                    "Identifier": "/form/username"
                  },
                  "PasswordField": {
                    "Identifier": "/form/password"
                  },
                  "EmailField": {
                    "Identifier": "/form/email"
                  },
                  "PhoneNumberFields": [
                    {
                      "Identifier": "/form/country-code"
                    },
                    {
                      "Identifier": "/form/region-code"
                    },
                    {
                      "Identifier": "/form/phonenumber"
                    }
                  ],
                  "AddressFields": [
                    {
                      "Identifier": "/form/name"
                    },
                    {
                      "Identifier": "/form/street-address"
                    },
                    {
                      "Identifier": "/form/city"
                    },
                    {
                      "Identifier": "/form/state"
                    },
                    {
                      "Identifier": "/form/zipcode"
                    }
                  ]
                },
                "EnableRegexInPath": false
              }
            }
          ]
        }
      },
      "OverrideAction": {
        "None": {}
      },
      "VisibilityConfig": {
        "SampledRequestsEnabled": true,
        "CloudWatchMetricsEnabled": true,
        "MetricName": "AWS-AWSManagedRulesACFPRuleSet"
      }
    }
  ],
  "VisibilityConfig": {
    "SampledRequestsEnabled": true,
    "CloudWatchMetricsEnabled": true,
    "MetricName": "simpleACFP"
  },
  "Capacity": 50,
  "ManagedByFirewallManager": false,
  "RetrofittedByFirewallManager": false,
  "LabelNamespace": "awswaf:111122223333:webacl:simpleACFP:"
}
```

# ACFP example: Custom response for compromised credentials
Custom response for compromised credentials

By default, the credentials check that's performed by the rule group `AWSManagedRulesACFPRuleSet` handles compromised credentials by labeling the request and blocking it. For details about the rule group and rule behavior, see [AWS WAF Fraud Control account creation fraud prevention (ACFP) rule group](aws-managed-rule-groups-acfp.md).

To inform the user that the account credentials they've provided have been compromised, you can do the following: 
+ **Override the `SignalCredentialCompromised` rule to Count** – This causes the rule to only count and label matching requests.
+ **Add a label match rule with custom handling** – Configure this rule to match against the ACFP label and to perform your custom handling. 

The following protection pack (web ACL) listings shows the ACFP managed rule group from the prior example, with the `SignalCredentialCompromised` rule action overridden to count. With this configuration, when this rule group evaluates any web request that uses compromised credentials, it will label the request, but not block it. 

In addition, the protection pack (web ACL) now has a custom response named `aws-waf-credential-compromised` and a new rule named `AccountSignupCompromisedCredentialsHandling`. The rule priority is a higher numeric setting than the rule group, so it runs after the rule group in the protection pack (web ACL) evaluation. The new rule matches any request with the rule group's compromised credentials label. When the rule finds a match, it applies the Block action to the request with the custom response body. The custom response body provides information to the end user that their credentials have been compromised and proposes an action to take. 

```
{
  "Name": "compromisedCreds",
  "Id": "... ",
  "ARN": "arn:aws:wafv2:us-east-1:111122223333:regional/webacl/compromisedCreds/...",
  "DefaultAction": {
    "Allow": {}
  },
  "Description": "",
  "Rules": [
    {
      "Name": "AWS-AWSManagedRulesACFPRuleSet",
      "Priority": 0,
      "Statement": {
        "ManagedRuleGroupStatement": {
          "VendorName": "AWS",
          "Name": "AWSManagedRulesACFPRuleSet",
          "ManagedRuleGroupConfigs": [
            {
              "AWSManagedRulesACFPRuleSet": {
                "CreationPath": "/web/signup/submit-registration",
                "RegistrationPagePath": "/web/signup/registration",
                "RequestInspection": {
                  "PayloadType": "JSON",
                  "UsernameField": {
                    "Identifier": "/form/username"
                  },
                  "PasswordField": {
                    "Identifier": "/form/password"
                  },
                  "EmailField": {
                    "Identifier": "/form/email"
                  },
                  "PhoneNumberFields": [
                    {
                      "Identifier": "/form/country-code"
                    },
                    {
                      "Identifier": "/form/region-code"
                    },
                    {
                      "Identifier": "/form/phonenumber"
                    }
                  ],
                  "AddressFields": [
                    {
                      "Identifier": "/form/name"
                    },
                    {
                      "Identifier": "/form/street-address"
                    },
                    {
                      "Identifier": "/form/city"
                    },
                    {
                      "Identifier": "/form/state"
                    },
                    {
                      "Identifier": "/form/zipcode"
                    }
                  ]
                },
                "EnableRegexInPath": false
              }
            }
          ],
          "RuleActionOverrides": [
            {
              "Name": "SignalCredentialCompromised",
              "ActionToUse": {
                "Count": {}
              }
            }
          ]
        }
      },
      "OverrideAction": {
        "None": {}
      },
      "VisibilityConfig": {
        "SampledRequestsEnabled": true,
        "CloudWatchMetricsEnabled": true,
        "MetricName": "AWS-AWSManagedRulesACFPRuleSet"
      }
    },
    {
      "Name": "AccountSignupCompromisedCredentialsHandling",
      "Priority": 1,
      "Statement": {
        "LabelMatchStatement": {
          "Scope": "LABEL",
          "Key": "awswaf:managed:aws:acfp:signal:credential_compromised"
        }
      },
      "Action": {
        "Block": {
          "CustomResponse": {
            "ResponseCode": 406,
            "CustomResponseBodyKey": "aws-waf-credential-compromised",
            "ResponseHeaders": [
              {
                "Name": "aws-waf-credential-compromised",
                "Value": "true"
              }
            ]
          }
        }
      },
      "VisibilityConfig": {
        "SampledRequestsEnabled": true,
        "CloudWatchMetricsEnabled": true,
        "MetricName": "AccountSignupCompromisedCredentialsHandling"
      }
    }
  ],
  "VisibilityConfig": {
    "SampledRequestsEnabled": true,
    "CloudWatchMetricsEnabled": true,
    "MetricName": "compromisedCreds"
  },
  "Capacity": 51,
  "ManagedByFirewallManager": false,
  "RetrofittedByFirewallManager": false,
  "LabelNamespace": "awswaf:111122223333:webacl:compromisedCreds:",
  "CustomResponseBodies": {
    "aws-waf-credential-compromised": {
      "ContentType": "APPLICATION_JSON",
      "Content": "{\n  \"credentials-compromised\": \"The credentials you provided have been found in a compromised credentials database.\\n\\nTry again with a different username, password pair.\"\n}"
    }
  }
}
```

# ACFP example: Response inspection configuration
Response inspection configuration

The following JSON listing shows an example protection pack (web ACL) with an AWS WAF Fraud Control account creation fraud prevention (ACFP) managed rule group that is configured to inspect origin responses. Note the response inspection configuration, which specifies success and response status codes. You can also configure success and response settings based on header, body, and body JSON matches. This JSON includes the protection pack (web ACL)'s automatically generated settings, like the label namespace and the protection pack (web ACL)'s application integration URL.

**Note**  
ATP response inspection is available only in protection packs (web ACLs) that protect CloudFront distributions.

```
{
  "Name": "simpleACFP",
  "Id": "... ",
  "ARN": "arn:aws:wafv2:us-east-1:111122223333:regional/webacl/simpleACFP/... ",
  "DefaultAction": {
    "Allow": {}
  },
  "Description": "",
  "Rules": [
    {
      "Name": "AWS-AWSManagedRulesACFPRuleSet",
      "Priority": 0,
      "Statement": {
        "ManagedRuleGroupStatement": {
          "VendorName": "AWS",
          "Name": "AWSManagedRulesACFPRuleSet",
          "ManagedRuleGroupConfigs": [
            {
              "AWSManagedRulesACFPRuleSet": {
                "CreationPath": "/web/signup/submit-registration",
                "RegistrationPagePath": "/web/signup/registration",
                "RequestInspection": {
                  "PayloadType": "JSON",
                  "UsernameField": {
                    "Identifier": "/form/username"
                  },
                  "PasswordField": {
                    "Identifier": "/form/password"
                  },
                  "EmailField": {
                    "Identifier": "/form/email"
                  },
                  "PhoneNumberFields": [
                    {
                      "Identifier": "/form/country-code"
                    },
                    {
                      "Identifier": "/form/region-code"
                    },
                    {
                      "Identifier": "/form/phonenumber"
                    }
                  ],
                  "AddressFields": [
                    {
                      "Identifier": "/form/name"
                    },
                    {
                      "Identifier": "/form/street-address"
                    },
                    {
                      "Identifier": "/form/city"
                    },
                    {
                      "Identifier": "/form/state"
                    },
                    {
                      "Identifier": "/form/zipcode"
                    }
                  ]
                },
                "ResponseInspection": {
                  "StatusCode": {
                    "SuccessCodes": [
                      200
                    ],
                    "FailureCodes": [
                      401
                    ]
                  }
                },
                "EnableRegexInPath": false
              }
            }
          ]
        }
      },
      "OverrideAction": {
        "None": {}
      },
      "VisibilityConfig": {
        "SampledRequestsEnabled": true,
        "CloudWatchMetricsEnabled": true,
        "MetricName": "AWS-AWSManagedRulesACFPRuleSet"
      }
    }
  ],
  "VisibilityConfig": {
    "SampledRequestsEnabled": true,
    "CloudWatchMetricsEnabled": true,
    "MetricName": "simpleACFP"
  },
  "Capacity": 50,
  "ManagedByFirewallManager": false,
  "RetrofittedByFirewallManager": false,
  "LabelNamespace": "awswaf:111122223333:webacl:simpleACFP:"
  }
```

# AWS WAF Fraud Control account takeover prevention (ATP)
AWS WAF Fraud Control account takeover prevention (ATP)AWS WAF Fraud Control account takeover prevention (ATP) login response inspection

For protected CloudFront distributions, you can now use ATP to block new login attempts from clients that have recently submitted too many failed login attempts. AWS WAF Fraud Control account takeover prevention (ATP)

You can detect and block account takeover attempts with the new AWS WAF Fraud Control account takeover prevention (ATP) managed rule group `AWSManagedRulesATPRuleSet`.AWS WAF Fraud Control account takeover prevention (ATP)

You can now use the AWS WAF Fraud Control account takeover prevention (ATP) functionality with Amazon CloudFront distributions. 

This section explains what AWS WAF Fraud Control account takeover prevention (ATP) does.

Account takeover is an online illegal activity in which an attacker gains unauthorized access to a person's account. The attacker might do this in a number of ways, such as using stolen credentials or guessing the victim's password through a series of attempts. When the attacker gains access, they might steal money, information, or services from the victim. The attacker might pose as the victim to gain access to other accounts that the victim owns, or to gain access to the accounts of other people or organizations. Additionally, they might attempt to change the user's password in order to block the victim from their own accounts. 

You can monitor and control account takeover attempts by implementing the ATP feature. AWS WAF offers this feature in the AWS Managed Rules rule group `AWSManagedRulesATPRuleSet` and companion application integration SDKs. 

The ATP managed rule group labels and manages requests that might be part of malicious account takeover attempts. The rule group does this by inspecting login attempts that clients send to your application's login endpoint. 
+ **Request inspection** – ATP gives you visibility and control over anomalous login attempts and login attempts that use stolen credentials, to prevent account takeovers that might lead to fraudulent activity. ATP checks email and password combinations against its stolen credential database, which is updated regularly as new leaked credentials are found on the dark web. ATP aggregates data by IP address and client session, to detect and block clients that send too many requests of a suspicious nature. 
+ **Response inspection** – For CloudFront distributions, in addition to inspecting incoming login requests, the ATP rule group inspects your application's responses to login attempts, to track success and failure rates. Using this information, ATP can temporarily block client sessions or IP addresses that have too many login failures. AWS WAF performs response inspection asynchronously, so this doesn't increase latency in your web traffic. 

**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

**Note**  
The ATP feature is not available for Amazon Cognito user pools.

**Topics**
+ [

# AWS WAF ATP components
](waf-atp-components.md)
+ [

# Using application integration SDKs with ATP
](waf-atp-with-tokens.md)
+ [

# Adding the ATP managed rule group to your protection pack (web ACL)
](waf-atp-rg-using.md)
+ [

# Testing and deploying ATP
](waf-atp-deploying.md)
+ [

# AWS WAF Fraud Control account takeover prevention (ATP) examples
](waf-atp-control-examples.md)

# AWS WAF ATP components
ATP components

The primary components of AWS WAF Fraud Control account takeover prevention (ATP) are the following: 
+ **`AWSManagedRulesATPRuleSet`** – The rules in this AWS Managed Rules rule group detect, label, and handle various types of account takeover activity. The rule group inspects HTTP `POST` web requests that clients send to the specified login endpoint. For protected CloudFront distributions, the rule group also inspects the responses that the distribution sends back to these requests. For a list of the rule group's rules, see [AWS WAF Fraud Control account takeover prevention (ATP) rule group](aws-managed-rule-groups-atp.md). You include this rule group in your protection pack (web ACL) using a managed rule group reference statement. For information about using this rule group, see [Adding the ATP managed rule group to your protection pack (web ACL)](waf-atp-rg-using.md). 
**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).
+ **Details about your application's login page** – You must provide information about your login page when you add the `AWSManagedRulesATPRuleSet` rule group to your protection pack (web ACL). This lets the rule group narrow the scope of the requests it inspects and properly validate credentials usage in web requests. The ATP rule group works with usernames that are in email format. For more information, see [Adding the ATP managed rule group to your protection pack (web ACL)](waf-atp-rg-using.md). 
+ **For protected CloudFront distributions, details about how your application responds to login attempts** – You provide details about your application's responses to login attempts, and the rule group tracks and manages clients that are sending too many failed login attempts. For information about configuring this option, see [Adding the ATP managed rule group to your protection pack (web ACL)](waf-atp-rg-using.md). 
+ **JavaScript and mobile application integration SDKs** – Implement the AWS WAF JavaScript and mobile SDKs with your ATP implementation to enable the full set of capabilities that the rule group offers. Many of the ATP rules use the information provided by the SDKs for session level client verification and behavior aggregation, required to separate legitimate client traffic from bot traffic. For more information about the SDKs, see [Client application integrations in AWS WAF](waf-application-integration.md).

You can combine your ATP implementation with the following to help you monitor, tune, and customize your protections. 
+ **Logging and metrics** – You can monitor your traffic, and understand how the ACFP managed rule group affects it, by configuring and enabling logs, Amazon Security Lake data collection, and Amazon CloudWatch metrics for your protection pack (web ACL). The labels that `AWSManagedRulesATPRuleSet` adds to your web requests are included in the data. For information about the options, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md), [Monitoring with Amazon CloudWatch](monitoring-cloudwatch.md), and [What is Amazon Security Lake?](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html).

  Depending on your needs and the traffic that you see, you might want to customize your `AWSManagedRulesATPRuleSet` implementation. For example, you might want to exclude some traffic from ATP evaluation, or you might want to alter how it handles some of the account takeover attempts that it identifies, using AWS WAF features like scope-down statements or label matching rules. 
+ **Labels and label matching rules** – For any of the rules in `AWSManagedRulesATPRuleSet`, you can switch the blocking behavior to count, and then match against the labels that are added by the rules. Use this approach to customize how you handle web requests that are identified by the ATP managed rule group. For more information about labeling and using label match statements, see [Label match rule statement](waf-rule-statement-type-label-match.md) and [Web request labeling in AWS WAF](waf-labels.md). 
+ **Custom requests and responses** – You can add custom headers to the requests that you allow and you can send custom responses for requests that you block. To do this, you pair your label matching with the AWS WAF custom request and response features. For more information about customizing requests and responses, see [Customized web requests and responses in AWS WAF](waf-custom-request-response.md).

# Using application integration SDKs with ATP
Using application integration SDKs with ATP

This section explains how to use application integration SDKs with ATP.

The ATP managed rule group requires the challenge tokens that the application integration SDKs generate. The tokens enable the full set of protections that the rule group offers. 

We highly recommend implementing the application integration SDKs, for the most effective use of the ATP rule group. The challenge script must run before the ATP rule group in order for the rule group to benefit from the tokens that the script acquires. This happens automatically with the application integration SDKs. If you are unable to use the SDKs, you can alternately configure your protection pack (web ACL) so that it runs the Challenge or CAPTCHA rule action against all requests that will be inspected by the ATP rule group. Using the Challenge or CAPTCHA rule action can incur additional fees. For pricing details, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/). 

**Capabilities of the ATP rule group that don't require a token**  
When web requests don't have a token, the ATP managed rule group is capable of blocking the following types of traffic:
+ Single IP addresses that make a lot of login requests. 
+ Single IP addresses that make a lot of failed login requests in a short amount of time. 
+ Login attempts with password traversal, using the same username but changing passwords. 

**Capabilities of the ATP rule group that require a token**  
The information provided in the challenge token expands the capabilities of the rule group and of your overall client application security. 

The token provides client information with each web request that enables the ATP rule group to separate legitimate client sessions from ill-behaved client sessions, even when both originate from a single IP address. The rule group uses information in the tokens to aggregate client session request behavior for fine-tuned detection and mitigation. 

When the token is available in web requests, the ATP rule group can detect and block the following additional categories of clients at the session level: 
+ Client sessions that fail the silent challenge that the SDKs manage. 
+ Client sessions that traverse usernames or passwords. This is also known as credential stuffing.
+ Client sessions that repeatedly use stolen credentials to log in.
+ Client sessions that spend a long time trying to log in. 
+ Clients sessions that make a lot of login requests. The ATP rule group provides better client isolation than the AWS WAF rate-based rule, which can block clients by IP address. The ATP rule group also uses a lower threshold. 
+ Clients sessions that make a lot of failed login requests in a short amount of time. This functionality is available for protected Amazon CloudFront distributions.

For more information about the rule group capabilities see [AWS WAF Fraud Control account takeover prevention (ATP) rule group](aws-managed-rule-groups-atp.md).

For information about the SDKs, see [Client application integrations in AWS WAF](waf-application-integration.md). For information about AWS WAF tokens, see [Token use in AWS WAF intelligent threat mitigation](waf-tokens.md). For information about the rule actions, see [CAPTCHA and Challenge in AWS WAF](waf-captcha-and-challenge.md).

# Adding the ATP managed rule group to your protection pack (web ACL)
Adding the ATP managed rule group to your web ACLUpdate to AWS WAF Fraud Control account takeover prevention (ATP)

You can now specify the login endpoint for the ATP managed rule group using a regular expression. 

This section explains how to add and configure the `AWSManagedRulesATPRuleSet` rule group.

To configure the ATP managed rule group to recognize account takeover activities in your web traffic, you provide information about how clients send login requests to your application. For protected Amazon CloudFront distributions, you also provide information about how your application responds to login requests. This configuration is in addition to the normal configuration for a managed rule group. 

For the rule group description and rules listing, see [AWS WAF Fraud Control account takeover prevention (ATP) rule group](aws-managed-rule-groups-atp.md).

**Note**  
The ATP stolen credentials database only contains usernames in email format.

This guidance is intended for users who know generally how to create and manage AWS WAF protection packs (web ACLs), rules, and rule groups. Those topics are covered in prior sections of this guide. For basic information about how to add a managed rule group to your protection pack (web ACL), see [Adding a managed rule group to a protection pack (web ACL) through the console](waf-using-managed-rule-group.md).

**Follow best practices**  
Use the ATP rule group in accordance with the best practices at [Best practices for intelligent threat mitigation in AWS WAF](waf-managed-protections-best-practices.md). 

**To use the `AWSManagedRulesATPRuleSet` rule group in your protection pack (web ACL)**

1. Add the AWS managed rule group, `AWSManagedRulesATPRuleSet` to your protection pack (web ACL), and **Edit** the rule group settings before saving. 
**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

1. In the **Rule group configuration** pane, provide the information that the ATP rule group uses to inspect login requests. 

   1. For **Use regular expression in paths**, toggle this on if you want AWS WAF to perform regular expression matching for your login page path specifications. 

      AWS WAF supports the pattern syntax used by the PCRE library `libpcre` with some exceptions. The library is documented at [PCRE - Perl Compatible Regular Expressions](http://www.pcre.org/). For information about AWS WAF support, see [Supported regular expression syntax in AWS WAF](waf-regex-pattern-support.md).

   1. For **Login path**, provide the path of the login endpoint for your application. The rule group inspects only HTTP `POST` requests to your specified login endpoint.
**Note**  
Matching for endpoints is case insensitive. Regex specifications must not contain the flag `(?-i)`, which disables case insensitive matching. String specifications must start with a forward slash `/`.

      For example, for the URL `https://example.com/web/login`, you could provide the string path specification `/web/login`. Login paths that start with the path that you provide are considered a match. For example `/web/login` matches the login paths `/web/login`, `/web/login/`, `/web/loginPage`, and `/web/login/thisPage`, but doesn't match the login path `/home/web/login` or `/website/login`. 

   1. For **Request inspection**, specify how your application accepts login attempts by providing the request payload type and the names of the fields within the request body where the username and password are provided. Your specification of the field names depends on the payload type.
      + **JSON payload type** – Specify the field names in JSON pointer syntax. For information about the JSON Pointer syntax, see the Internet Engineering Task Force (IETF) documentation [JavaScript Object Notation (JSON) Pointer](https://tools.ietf.org/html/rfc6901). 

        For example, for the following example JSON payload, the username field specification is `/login/username` and the password field specification is `/login/password`.

        ```
        {
            "login": {
                "username": "THE_USERNAME",
                "password": "THE_PASSWORD"
            }
        }
        ```
      + **FORM\$1ENCODED payload type** – Use the HTML form names.

        For example, for an HTML form with input elements named `username1` and `password1`, the username field specification is `username1` and the password field specification is `password1`.

   1. If you're protecting Amazon CloudFront distributions, then under **Response inspection**, specify how your application indicates success or failure in its responses to login attempts. 
**Note**  
ATP response inspection is available only in protection packs (web ACLs) that protect CloudFront distributions.

      Specify a single component in the login response that you want ATP to inspect. For the **Body** and **JSON** component types, AWS WAF can inspect the first 65,536 bytes (64 KB) of the component. 

      Provide your inspection criteria for the component type, as indicated by the interface. You must provide both success and failure criteria to inspect for in the component. 

      For example, say your application indicates the status of a login attempt in the status code of the response, and uses `200 OK` for success and `401 Unauthorized` or `403 Forbidden` for failure. You would set the response inspection **Component type** to **Status code**, then in the **Success** text box enter `200` and in the **Failure** text box, enter `401` on the first line and `403` on the second.

      The ATP rule group only counts responses that match your success or failure inspection criteria. The rule group rules act on clients while they have too high a failure rate among the responses that are counted. For accurate behavior by the rule group rules, be sure to provide complete information for both successful and failed login attempts. 

      To see the rules that inspect login responses, look for `VolumetricIpFailedLoginResponseHigh` and `VolumetricSessionFailedLoginResponseHigh` in the rules listing at [AWS WAF Fraud Control account takeover prevention (ATP) rule group](aws-managed-rule-groups-atp.md). 

1. Provide any additional configuration that you want for the rule group. 

   You can further limit the scope of requests that the rule group inspects by adding a scope-down statement to the managed rule group statement. For example, you can inspect only requests with a specific query argument or cookie. The rule group will inspect only HTTP `POST` requests to your specified login endpoint that match the criteria in your scope-down statement. For information about scope-down statements, see [Using scope-down statements in AWS WAF](waf-rule-scope-down-statements.md).

1. Save your changes to the protection pack (web ACL). 

Before you deploy your ATP implementation for production traffic, test and tune it in a staging or testing environment until you are comfortable with the potential impact to your traffic. Then test and tune the rules in count mode with your production traffic before enabling them. See the section that follows for guidance. 

# Testing and deploying ATP
Testing and deploying ATP

This section provides general guidance for configuring and testing an AWS WAF Fraud Control account takeover prevention (ATP) implementation for your site. The specific steps that you choose to follow will depend on your needs, resources, and web requests that you receive. 

This information is in addition to the general information about testing and tuning provided at [Testing and tuning your AWS WAF protections](web-acl-testing.md).

**Note**  
AWS Managed Rules are designed to protect you from common web threats. When used in accordance with the documentation, AWS Managed Rules rule groups add another layer of security for your applications. However, AWS Managed Rules rule groups aren't intended as a replacement for your security responsibilities, which are determined by the AWS resources that you select. Refer to the [Shared Responsibility Model](https://aws.amazon.com/compliance/shared-responsibility-model/) to ensure that your resources in AWS are properly protected. 

**Production traffic risk**  
Before you deploy your ATP implementation for production traffic, test and tune it in a staging or testing environment until you are comfortable with the potential impact to your traffic. Then test and tune the rules in count mode with your production traffic before enabling them. 

AWS WAF provides test credentials that you can use to verify your ATP configuration. In the following procedure, you'll configure a test protection pack (web ACL) to use the ATP managed rule group, configure a rule to capture the label added by the rule group, and then run a login attempt using these test credentials. You'll verify that your web ACL has properly managed the attempt by checking the Amazon CloudWatch metrics for the login attempt. 

This guidance is intended for users who know generally how to create and manage AWS WAF protection packs (web ACLs), rules, and rule groups. Those topics are covered in prior sections of this guide. 

**To configure and test an AWS WAF Fraud Control account takeover prevention (ATP) implementation**

Perform these steps first in a test environment, then in production.

1. 

**Add the AWS WAF Fraud Control account takeover prevention (ATP) managed rule group in count mode**
**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

   Add the AWS Managed Rules rule group `AWSManagedRulesATPRuleSet` to a new or existing protection pack (web ACL) and configure it so that it doesn't alter the current protection pack (web ACL) behavior. For details about the rules and labels for this rule group, see [AWS WAF Fraud Control account takeover prevention (ATP) rule group](aws-managed-rule-groups-atp.md).
   + When you add the managed rule group, edit it and do the following: 
     + In the **Rule group configuration** pane, provide the details of your application's login page. The ATP rule group uses this information to monitor sign-in activities. For more information, see [Adding the ATP managed rule group to your protection pack (web ACL)](waf-atp-rg-using.md).
     + In the **Rules** pane, open the **Override all rule actions** dropdown and choose **Count**. With this configuration, AWS WAF evaluates requests against all of the rules in the rule group and only counts the matches that result, while still adding labels to requests. For more information, see [Overriding rule actions in a rule group](web-acl-rule-group-settings.md#web-acl-rule-group-rule-action-override).

       With this override, you can monitor the potential impact of the ATP managed rules to determine whether you want to add exceptions, such as exceptions for internal use cases. 
   + Position the rule group so that it's evaluated after your existing rules in the protection pack (web ACL), with a priority setting that's numerically higher than any rules or rule groups that you're already using. For more information, see [Setting rule priority](web-acl-processing-order.md). 

     This way, your current handling of traffic isn't disrupted. For example, if you have rules that detect malicious traffic such as SQL injection or cross-site scripting, they'll continue to detect and log that. Alternately, if you have rules that allow known non-malicious traffic, they can continue to allow that traffic, without having it blocked by the ATP managed rule group. You might decide to adjust the processing order during your testing and tuning activities.

1. 

**Enable logging and metrics for the protection pack (web ACL)**

   As needed, configure logging, Amazon Security Lake data collection, request sampling, and Amazon CloudWatch metrics for the protection pack (web ACL). You can use these visibility tools to monitor the interaction of the ATP managed rule group with your traffic. 
   + For information about configuring and using logging, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md). 
   + For information about Amazon Security Lake, see [What is Amazon Security Lake?](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html) and [Collecting data from AWS services](https://docs.aws.amazon.com/security-lake/latest/userguide/internal-sources.html) in the *Amazon Security Lake user guide*. 
   + For information about Amazon CloudWatch metrics, see [Monitoring with Amazon CloudWatch](monitoring-cloudwatch.md). 
   + For information about web request sampling, see [Viewing a sample of web requests](web-acl-testing-view-sample.md). 

1. 

**Associate the protection pack (web ACL) with a resource**

   If the protection pack (web ACL) isn't already associated with a test resource, associate it. For information, see [Associating or disassociating protection with an AWS resource](web-acl-associating-aws-resource.md).

1. 

**Monitor traffic and ATP rule matches**

   Make sure that your normal traffic is flowing and that the ATP managed rule group rules are adding labels to matching web requests. You can see the labels in the logs and see the ATP and label metrics in the Amazon CloudWatch metrics. In the logs, the rules that you've overridden to count in the rule group show up in the `ruleGroupList` with `action` set to count, and with `overriddenAction` indicating the configured rule action that you overrode. 

1. 

**Test the rule group's credential checking capabilities**

   Perform a login attempt with test compromised credentials and check that the rule group matches against them as expected. 

   1. Log in to your protected resource's login page using the following AWS WAF test credential pair: 
      + User: `WAF_TEST_CREDENTIAL@wafexample.com`
      + Password: `WAF_TEST_CREDENTIAL_PASSWORD`

      These test credentials are categorized as compromised credentials, and the ATP managed rule group will add the `awswaf:managed:aws:atp:signal:credential_compromised` label to the login request, which you can see in the logs. 

   1. In your protection pack (web ACL) logs, look for the `awswaf:managed:aws:atp:signal:credential_compromised` label in the `labels` field on the log entries for your test login web requests. For information about logging, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md). 

   After you've verified that the rule group captures compromised credentials as expected, you can take steps to configure its implementation as you need for your protected resource.

1. 

**For CloudFront distributions, test the rule group's login failure management**

   

   1. Run a test for each failure response criteria that you configured for the ATP rule group. Wait at least 10 minutes between tests.

      To test a single failure criteria, identify a login attempt that will fail with that criteria in the response. Then, from a single client IP address, perform at least 10 failed login attempts in under 10 minutes.

      After the first 6 failures, the volumetric failed login rule should start matching against the rest of your attempts, labeling and counting them. The rule might miss the first one or two due to latency. 

   1. In your protection pack (web ACL) logs, look for the `awswaf:managed:aws:atp:aggregate:volumetric:ip:failed_login_response:high` label in the `labels` field on the log entries for your test login web requests. For information about logging, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md). 

   These tests verify that your failure criteria match your responses by checking that the failed login counts surpass the thresholds for the rule `VolumetricIpFailedLoginResponseHigh`. After you've reached the thresholds, if you continue to send login requests from the same IP address, the rule will continue to match until the failure rate drops below the threshold. While the thresholds are exceeded, the rule matches both successful or failed logins from the IP address. 

1. 

**Customize ATP web request handling**

   As needed, add your own rules that explicitly allow or block requests, to change how ATP rules would otherwise handle them. 

   For example, you can use ATP labels to allow or block requests or to customize request handling. You can add a label match rule after the ATP managed rule group to filter labeled requests for the handling that you want to apply. After testing, keep the related ATP rules in count mode, and maintain the request handling decisions in your custom rule. For an example, see [ATP example: Custom handling for missing and compromised credentials](waf-atp-control-example-user-agent-exception.md). 

1. 

**Remove your test rules and enable the ATP managed rule group settings**

   Depending on your situation, you might have decided that you want to leave some ATP rules in count mode. For the rules that you want to run as configured inside the rule group, disable count mode in the protection pack (web ACL) rule group configuration. When you're finished testing, you can also remove your test label match rules.

1. 

**Monitor and tune**

   To be sure that web requests are being handled as you want, closely monitor your traffic after you enable the ATP functionality that you intend to use. Adjust the behavior as needed with the rules count override on the rule group and with your own rules. 

After you finish testing your ATP rule group implementation, if you haven't already done so, we strongly recommend that you integrate the AWS WAF JavaScript SDK into your browser login page, for enhanced detection capabilities. AWS WAF also provides mobile SDKs to integrate iOS and Android devices. For more information about the integration SDKs, see [Client application integrations in AWS WAF](waf-application-integration.md). For information about this recommendation, see [Using application integration SDKs with ATP](waf-atp-with-tokens.md).

# AWS WAF Fraud Control account takeover prevention (ATP) examples
ATP examplesUpdated ATP examples

Added example depicting response inspection configuration and updated existing examples to reflect best practices.

This section shows example configurations that satisfy common use cases for the AWS WAF Fraud Control account takeover prevention (ATP) implementations. 

Each example provides a description of the use case and then shows the solution in JSON listings for the custom configured rules. 

**Note**  
You can retrieve JSON listings like the ones shown in these examples through the console protection pack (web ACL) JSON download or rule JSON editor, or through the `getWebACL` operation in the APIs and the command line interface. 

**Topics**
+ [

# ATP example: Simple configuration
](waf-atp-control-example-basic.md)
+ [

# ATP example: Custom handling for missing and compromised credentials
](waf-atp-control-example-user-agent-exception.md)
+ [

# ATP example: Response inspection configuration
](waf-atp-control-example-response-inspection.md)

# ATP example: Simple configuration
Simple configuration

The following JSON listing shows an example protection pack (web ACL) with an AWS WAF Fraud Control account takeover prevention (ATP) managed rule group. Note the additional sign-in page configuration, which gives the rule group the information it needs to monitor and manage your login requests. This JSON includes the protection pack (web ACL)'s automatically generated settings, like the label namespace and the protection pack (web ACL)'s application integration URL.

```
{
    "WebACL": {
        "LabelNamespace": "awswaf:111122223333:webacl:ATPModuleACL:",
        "Capacity": 50,
        "Description": "This is a test protection pack (web ACL) for ATP.",
        "Rules": [
            {
                "Priority": 1,
                "OverrideAction": {
                    "None": {}
                },
                "VisibilityConfig": {
                    "SampledRequestsEnabled": true,
                    "CloudWatchMetricsEnabled": true,
                    "MetricName": "AccountTakeOverValidationRule"
                },
                "Name": "DetectCompromisedUserCredentials",
                "Statement": {
                    "ManagedRuleGroupStatement": {
                        "VendorName": "AWS",
                        "Name": "AWSManagedRulesATPRuleSet",
                        "ManagedRuleGroupConfigs": [
                          {
                            "AWSManagedRulesATPRuleSet": {
                              "LoginPath": "/web/login",
                              "RequestInspection": {
                                "PayloadType": "JSON",
                                "UsernameField": {
                                  "Identifier": "/form/username"
                                },
                                "PasswordField": {
                                  "Identifier": "/form/password"
                                }
                              },
                              "EnableRegexInPath": false
                            }
                          }
                        ]
                    }
                }
            }
        ],
        "VisibilityConfig": {
            "SampledRequestsEnabled": true,
            "CloudWatchMetricsEnabled": true,
            "MetricName": "ATPValidationAcl"
        },
        "DefaultAction": {
            "Allow": {}
        },
        "ManagedByFirewallManager": false,
        "RetrofittedByFirewallManager": false,
        "Id": "32q10987-65rs-4tuv-3210-98765wxyz432",
        "ARN": "arn:aws:wafv2:us-east-1:111122223333:regional/webacl/ATPModuleACL/32q10987-65rs-4tuv-3210-98765wxyz432",
        "Name": "ATPModuleACL"
    },
    "ApplicationIntegrationURL": "https://9z87abce34ea.us-east-1.sdk.awswaf.com/9z87abce34ea/1234567a1b10/",
    "LockToken": "6d0e6966-95c9-48b6-b51d-8e82e523b847"
}
```

# ATP example: Custom handling for missing and compromised credentials
Custom handling for missing or compromised credentials

By default, the credentials checks that are performed by the rule group `AWSManagedRulesATPRuleSet` handle web requests as follows: 
+ **Missing credentials** – Label and block request.
+ **Compromised credentials** – Label request but don't block or count it.

For details about the rule group and rule behavior, see [AWS WAF Fraud Control account takeover prevention (ATP) rule group](aws-managed-rule-groups-atp.md).

You can add custom handling for web requests that have missing or compromised credentials by doing the following: 
+ **Override the `MissingCredential` rule to Count** – This rule action override causes the rule to only count and label matching requests.
+ **Add a label match rule with custom handling** – Configure this rule to match against both of the ATP labels and to perform your custom handling. For example, you might redirect the customer to your sign-up page.

The following rule shows the ATP managed rule group from the prior example, with the `MissingCredential` rule action overridden to count. This causes the rule to apply its label to matching requests, and then only count the requests, instead of blocking them. 

```
"Rules": [
    {
        "Priority": 1,
        "OverrideAction": {
            "None": {}
        },
        "VisibilityConfig": {
            "SampledRequestsEnabled": true,
            "CloudWatchMetricsEnabled": true,
            "MetricName": "AccountTakeOverValidationRule"
        },
        "Name": "DetectCompromisedUserCredentials",
        "Statement": {
            "ManagedRuleGroupStatement": {
                "ManagedRuleGroupConfigs": [
                  {
                    "AWSManagedRulesATPRuleSet": {
                      "LoginPath": "/web/login",
                      "RequestInspection": {
                        "PayloadType": "JSON",
                        "UsernameField": {
                          "Identifier": "/form/username"
                        },
                        "PasswordField": {
                          "Identifier": "/form/password"
                        }
                      },
                      "EnableRegexInPath": false
                    }
                  }
                ]
                "VendorName": "AWS",
                "Name": "AWSManagedRulesATPRuleSet",
                "RuleActionOverrides": [
                  {
                    "ActionToUse": {
                      "Count": {}
                    },
                    "Name": "MissingCredential"
                  }
                ],
                "ExcludedRules": []
            }
        }
    }
],
```

With this configuration, when this rule group evaluates any web request that has missing or compromised credentials, it will label the request, but not block it. 

The following rule has a priority setting that is higher numerically than the preceding rule group. AWS WAF evaluates rules in numeric order, starting from the lowest, so this rule will be evaluated after the rule group evaluation. The rule is configured to match either of the credentials labels and to send a custom response for matching requests. 

```
"Name": "redirectToSignup",
      "Priority": 10,
      "Statement": {
        "OrStatement": {
          "Statements": [
            {
              "LabelMatchStatement": {
                "Scope": "LABEL",
                "Key": "awswaf:managed:aws:atp:signal:missing_credential"
              }
            },
            {
              "LabelMatchStatement": {
                "Scope": "LABEL",
                "Key": "awswaf:managed:aws:atp:signal:credential_compromised"
              }
            }
          ]
        }
      },
      "Action": {
        "Block": {
          "CustomResponse": {
             your custom response settings 
          }
        }
      },
      "VisibilityConfig": {
        "SampledRequestsEnabled": true,
        "CloudWatchMetricsEnabled": true,
        "MetricName": "redirectToSignup"
      }
```

# ATP example: Response inspection configuration
Response inspection configuration

The following JSON listing shows an example protection pack (web ACL) with an AWS WAF Fraud Control account takeover prevention (ATP) managed rule group that is configured to inspect origin responses. Note the response inspection configuration, which specifies success and response status codes. You can also configure success and response settings based on header, body, and body JSON matches. This JSON includes the protection pack (web ACL)'s automatically generated settings, like the label namespace and the protection pack (web ACL)'s application integration URL.

**Note**  
ATP response inspection is available only in protection packs (web ACLs) that protect CloudFront distributions.

```
{
    "WebACL": {
        "LabelNamespace": "awswaf:111122223333:webacl:ATPModuleACL:",
        "Capacity": 50,
        "Description": "This is a test protection pack (web ACL) for ATP.",
        "Rules": [
            {
                "Priority": 1,
                "OverrideAction": {
                    "None": {}
                },
                "VisibilityConfig": {
                    "SampledRequestsEnabled": true,
                    "CloudWatchMetricsEnabled": true,
                    "MetricName": "AccountTakeOverValidationRule"
                },
                "Name": "DetectCompromisedUserCredentials",
                "Statement": {
                    "ManagedRuleGroupStatement": {
                        "VendorName": "AWS",
                        "Name": "AWSManagedRulesATPRuleSet",
                        "ManagedRuleGroupConfigs": [
                          {
                            "AWSManagedRulesATPRuleSet": {
                              "LoginPath": "/web/login",
                              "RequestInspection": {
                                "PayloadType": "JSON",
                                "UsernameField": {
                                  "Identifier": "/form/username"
                                },
                                "PasswordField": {
                                  "Identifier": "/form/password"
                                }
                              },
                              "ResponseInspection": {
                                "StatusCode": {
                                  "SuccessCodes": [
                                    200
                                  ],
                                  "FailureCodes": [
                                    401
                                  ]
                                }
                              },
                              "EnableRegexInPath": false
                            }
                          }
                        ]
                    }
                }
            }
        ],
        "VisibilityConfig": {
            "SampledRequestsEnabled": true,
            "CloudWatchMetricsEnabled": true,
            "MetricName": "ATPValidationAcl"
        },
        "DefaultAction": {
            "Allow": {}
        },
        "ManagedByFirewallManager": false,
        "RetrofittedByFirewallManager": false,
        "Id": "32q10987-65rs-4tuv-3210-98765wxyz432",
        "ARN": "arn:aws:wafv2:us-east-1:111122223333:regional/webacl/ATPModuleACL/32q10987-65rs-4tuv-3210-98765wxyz432",
        "Name": "ATPModuleACL"
    },
    "ApplicationIntegrationURL": "https://9z87abce34ea.us-east-1.sdk.awswaf.com/9z87abce34ea/1234567a1b10/",
    "LockToken": "6d0e6966-95c9-48b6-b51d-8e82e523b847"
}
```

# AWS WAF Bot Control
AWS WAF Bot ControlAWS WAF Bot Control

You can monitor and control bot traffic with the new AWS WAF Bot Control feature, which combines the Bot Control managed rule group with web request labeling, scope-down statements, and log filtering.

This section explains what Bot Control does.

With Bot Control, you can easily monitor, block, or rate limit bots such as scrapers, scanners, crawlers, status monitors, and search engines. If you use the targeted inspection level of the rule group, you can also challenge bots that don't self identify, making it harder and more expensive for malicious bots to operate against your website. You can protect your applications using the Bot Control managed rule group alone, or in combination with other AWS Managed Rules rule groups and your own custom AWS WAF rules. 

Bot Control includes a console dashboard that shows how much of your current traffic is coming from bots, based on request sampling. With the Bot Control managed rule group added to your protection pack (web ACL), you can take action against bot traffic and receive detailed, real-time information about common bot traffic coming to your applications. 

**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

The Bot Control managed rule group provides a basic, common protection level that adds labels to self-identifying bots, verifies generally desirable bots, and detects high confidence bot signatures. This gives you the ability to monitor and control common categories of bot traffic. 

The Bot Control rule group also provides a targeted protection level that adds detection for sophisticated bots that don't self identify. Targeted protections use detection techniques such as browser interrogation, fingerprinting, and behavior heuristics to identify bad bot traffic. Additionally, targeted protections provide optional automated, machine-learning analysis of website traffic statistics to detect bot-related activity. When you enable machine learning, AWS WAF uses statistics about website traffic, such as timestamps, browser characteristics, and previous URL visited, to improve the Bot Control machine learning model. 

When AWS WAF evaluates a web request against the Bot Control managed rule group, the rule group adds labels to requests that it detects as bot related, for example the category of bot and the bot name. You can match against these labels in your own AWS WAF rules to customize handling. The labels that are generated by the Bot Control managed rule group are included in Amazon CloudWatch metrics and your protection pack (web ACL) logs. 

You can also use AWS Firewall Manager AWS WAF policies to deploy the Bot Control managed rule group across your applications in multiple accounts that are part of your organization in AWS Organizations.

For more information about the Bot Control managed rule group, see [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md). 

## Web bot authentication for AI agents


AWS WAF Bot Control now supports Web Bot Authentication (WBA) as a cryptographic verification method for bots and AI agents accessing your CloudFront distributions. This feature enables legitimate AI crawlers and agents to prove their identity without requiring traditional challenge-response mechanisms.

Version requirement: `AWSManagedRulesBotControlRuleSet` Version\$14.0 or later. (The static version must be explicitly selected.) For detailed label taxonomy and rule behavior, see: 
+ [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md)
+ [Web request labeling in AWS WAF](waf-labels.md)
+ [AWS Managed Rules changelog](aws-managed-rule-groups-changelog.md)

# AWS WAF Bot Control components
Bot Control componentsAWS WAF Bot Control

The targeted protection level of the Bot Control managed rule group now inspects for token reuse between IP addresses. It also now provides optional, machine-learning analysis of traffic statistics to detect some bot-related activity. 

The main components of a Bot Control implementation are the following:
+ **`AWSManagedRulesBotControlRuleSet`** – The Bot Control managed rule group whose rules detect and handle various categories of bots. This rule group add labels to web requests that it detects as bot traffic. 
**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

The Bot Control managed rule group provides two levels of protection that you can choose from: 
  + **Common** – Detects a variety of self-identifying bots, such as web scraping frameworks, search engines, and automated browsers. Bot Control protections at this level identify common bots using traditional bot detection techniques, such as static request data analysis. The rules label traffic from these bots and block the ones that they cannot verify. 
  + **Targeted** – Includes the common-level protections and adds targeted detection for sophisticated bots that do not self identify. Targeted protections mitigate bot activity using a combination of rate limiting and CAPTCHA and background browser challenges. 
    + **`TGT_`** – Rules that provide targeted protection have names that begin with `TGT_`. All targeted protections use detection techniques such as browser interrogation, fingerprinting, and behavior heuristics to identify bad bot traffic. 
    + **`TGT_ML_`** – Targeted protection rules that use machine learning have names that begin with `TGT_ML_`. These rules use automated, machine-learning analysis of website traffic statistics to detect anomalous behavior indicative of distributed, coordinated bot activity. AWS WAF analyzes statistics about your website traffic such as timestamps, browser characteristics, and previous URL visited, to improve the Bot Control machine learning model. Machine learning capabilities are enabled by default, but you can disable them in your rule group configuration. When machine learning is disabled, AWS WAF does not evaluate these rules. 

  For details including information about the rule group's rules, see [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md). 

  You include this rule group in your protection pack (web ACL) using a managed rule group reference statement and indicating the inspection level that you want to use. For the targeted level, you also indicate whether to enable machine learning. For more information about adding this managed rule group to your protection pack (web ACL), see [Adding the AWS WAF Bot Control managed rule group to your web ACL](waf-bot-control-rg-using.md). 
+ **Bot Control dashboard** – The bot monitoring dashboard for your protection pack (web ACL), available through the protection pack (web ACL) Bot Control tab. Use this dashboard to monitor your traffic and understand how much of it comes from various types of bots. This can be a starting point for customizing your bot management, as described in this topic. You can also use it to verify your changes and monitor activity for various bots and bot categories. 
+ **AI Traffic Analysis dashboard** – Specialized dashboard for detailed AI bot and agent activity analysis, available through the protection pack (web ACL) AI Traffic Analysis tab. Provides enhanced visibility into AI-specific traffic patterns, bot intent, and access behaviors beyond standard Bot Control metrics.
+ **JavaScript and mobile application integration SDKs** – You should implement the AWS WAF JavaScript and mobile SDKs if you use the targeted protection level of the Bot Control rule group. The targeted rules use information provided by the SDKs in the client tokens for enhanced detection against malicious bots. For more information about the SDKs, see [Client application integrations in AWS WAF](waf-application-integration.md).
+ **Logging and metrics** – You can monitor your bot traffic and understand how the Bot Control managed rule group evaluates and handles your traffic by studying the data that's collected for your protection pack (web ACL) by AWS WAF logs, Amazon Security Lake, and Amazon CloudWatch. The labels that Bot Control adds to your web requests are included in the data. For information about these options, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md), [Monitoring with Amazon CloudWatch](monitoring-cloudwatch.md), and [What is Amazon Security Lake?](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html). 

  Depending on your needs and the traffic that you see, you might want to customize your Bot Control implementation. The following are some of the most commonly used options.
+ **Scope-down statements** – You can exclude some traffic from the web requests that the Bot Control managed rule group evaluates by adding a scope-down statement inside the Bot Control managed rule group reference statement. A scope-down statement can be any nestable rule statement. When a request doesn't match the scope-down statement, AWS WAF evaluates it as not matching the rule group reference statement without evaluating it against the rule group. For more information about scope-down statements, see [Using scope-down statements in AWS WAF](waf-rule-scope-down-statements.md).

  Your costs for using the Bot Control managed rule group increase with the number of web requests that AWS WAF evaluates with it. You can help reduce these costs by using a scope-down statement to limit the requests that the rule group evaluates. For example, you might want to allow your homepage to load for everyone, including bots, and then apply the rule group rules to requests that are going to your application APIs or that contain a particular type of content. 
+ **Labels and label matching rules** – You can customize how the Bot Control rule group handles some of the bot traffic that it identifies using the AWS WAF label match rule statement. The Bot Control rule group adds labels to your web requests. You can add label matching rules after the Bot Control rule group that match on Bot Control labels and apply the handling that you need. For more information about labeling and using label match statements, see [Label match rule statement](waf-rule-statement-type-label-match.md) and [Web request labeling in AWS WAF](waf-labels.md). 
+ **Custom requests and responses** – You can add custom headers to requests that you allow and you can send custom responses for requests that you block by pairing label matching with the AWS WAF custom request and response features. For more information about customizing requests and responses, see [Customized web requests and responses in AWS WAF](waf-custom-request-response.md).

# Using application integration SDKs with Bot Control
Using application integration SDKs with Bot Control

This section explains how to use application integration SDKs with Bot Control.

Most of the targeted protections of the Bot Control managed rule group require the challenge tokens that the application integration SDKs generate. The rules that don't require a challenge token on the request are the Bot Control common level protections and the targeted level machine learning rules. For descriptions of the protection levels and rules in the rule group, see [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md). 

We highly recommend implementing the application integration SDKs, for the most effective use of the Bot Control rule group. The challenge script must run before the Bot Control rule group in order for the rule group to benefit from the tokens that the script acquires. 
+ With the application integration SDKs, the script runs automatically.
+ If you're unable to use the SDKs, you can configure your protection pack (web ACL) so that it runs the Challenge or CAPTCHA rule action against all requests that will be inspected by the Bot Control rule group. Using the Challenge or CAPTCHA rule action can incur additional fees. For pricing details, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/). 

When you implement the application integration SDKs in your clients or use one of the rule actions that runs the challenge script, you expand the capabilities of the rule group and of your overall client application security. 

Tokens provide client information with each web request. This additional information enables the Bot Control rule group to separate legitimate client sessions from ill-behaved client sessions, even when both originate from a single IP address. The rule group uses information in the tokens to aggregate client session request behavior for the fine-tuned detection and mitigation that the targeted protections level provide. 

For information about the SDKs, see [Client application integrations in AWS WAF](waf-application-integration.md). For information about AWS WAF tokens, see [Token use in AWS WAF intelligent threat mitigation](waf-tokens.md). For information about the rule actions, see [CAPTCHA and Challenge in AWS WAF](waf-captcha-and-challenge.md).

# Adding the AWS WAF Bot Control managed rule group to your web ACL
Adding the Bot Control managed rule group to your protection pack (web ACL)

This section explains how to add and configure the `AWSManagedRulesBotControlRuleSet` rule group.

The Bot Control managed rule group `AWSManagedRulesBotControlRuleSet` requires additional configuration to identify the protection level that you want to implement. 

For the rule group description and rules listing, see [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md).

This guidance is intended for users who know generally how to create and manage AWS WAF protection packs (web ACLs), rules, and rule groups. Those topics are covered in prior sections of this guide. For basic information about how to add a managed rule group to your protection pack (web ACL), see [Adding a managed rule group to a protection pack (web ACL) through the console](waf-using-managed-rule-group.md).

**Follow best practices**  
Use the Bot Control rule group in accordance with the best practices at [Best practices for intelligent threat mitigation in AWS WAF](waf-managed-protections-best-practices.md). 

**To use the `AWSManagedRulesBotControlRuleSet` rule group in your protection pack (web ACL)**

1. Add the AWS managed rule group, `AWSManagedRulesBotControlRuleSet` to your protection pack (web ACL). For the full rule group description, see [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md). 
**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

   When you add the rule group, edit it to open the configuration page for the rule group. 

1. On the rule group's configuration page, in the **Inspection level** pane, select the inspection level that you want to use. 
   + **Common** – Detects a variety of self-identifying bots, such as web scraping frameworks, search engines, and automated browsers. Bot Control protections at this level identify common bots using traditional bot detection techniques, such as static request data analysis. The rules label traffic from these bots and block the ones that they cannot verify. 
   + **Targeted** – Includes the common-level protections and adds targeted detection for sophisticated bots that do not self identify. Targeted protections mitigate bot activity using a combination of rate limiting and CAPTCHA and background browser challenges. 
     + **`TGT_`** – Rules that provide targeted protection have names that begin with `TGT_`. All targeted protections use detection techniques such as browser interrogation, fingerprinting, and behavior heuristics to identify bad bot traffic. 
     + **`TGT_ML_`** – Targeted protection rules that use machine learning have names that begin with `TGT_ML_`. These rules use automated, machine-learning analysis of website traffic statistics to detect anomalous behavior indicative of distributed, coordinated bot activity. AWS WAF analyzes statistics about your website traffic such as timestamps, browser characteristics, and previous URL visited, to improve the Bot Control machine learning model. Machine learning capabilities are enabled by default, but you can disable them in your rule group configuration. When machine learning is disabled, AWS WAF does not evaluate these rules. 

1. If you're using the targeted protection level and you don't want AWS WAF to use machine learning (ML) to analyze web traffic for distributed, coordinated bot activity, disable the machine learning option. Machine learning is required for the Bot Control rules whose names start with `TGT_ML_`. For details about these rules, see [Bot Control rules listing](aws-managed-rule-groups-bot.md#aws-managed-rule-groups-bot-rules).

1. Add a scope-down statement for the rule group, to contain the costs of using it. A scope-down statement narrows the set of requests that the rule group inspects. For example use cases, start with [Bot Control example: Using Bot Control only for the login page](waf-bot-control-example-scope-down-login.md) and [Bot Control example: Using Bot Control only for dynamic content](waf-bot-control-example-scope-down-dynamic-content.md). 

1. Provide any additional configuration that you need for the rule group. 

1. Save your changes to the protection pack (web ACL). 

Before you deploy your Bot Control implementation for production traffic, test and tune it in a staging or testing environment until you are comfortable with the potential impact to your traffic. Then test and tune the rules in count mode with your production traffic before enabling them. See the sections that follow for guidance. 

# Example scenarios of false positives with AWS WAF Bot Control
False positives with Bot Control

 This section provides example situations where you might encounter false positives with AWS WAF Bot Control.

We have carefully selected the rules in the AWS WAF Bot Control managed rule group to minimize false positives. We test the rules against global traffic and monitor their impact on test protection packs (web ACLs). However, it's still possible to get false positives due to changes in traffic patterns. Additionally, some use cases are known to cause false positives and will require customization specific to your web traffic. 

Situations where you might encounter false positives include the following: 
+ Mobile apps typically have non-browser user agents, which the `SignalNonBrowserUserAgent` rule blocks by default. If you expect traffic from mobile apps, or any other legitimate traffic with non-browser user agents, you'll need to add an exception to allow it. 
+ You might rely on some specific bot traffic for things like uptime monitoring, integration testing, or marketing tools. If Bot Control identifies and blocks the bot traffic that you want to allow, you need to alter the handling by adding your own rules. While this isn't a false positive scenario for all customers, if it is for you, you will need to handle it the same as for a false positive. 
+ The Bot Control managed rule group verifies bots using the IP addresses from AWS WAF. If you use Bot Control and you have verified bots that route through a proxy or load balancer, you might need to explicitly allow them using a custom rule. For information about how to create a custom rule of this type, see [Using forwarded IP addresses in AWS WAF](waf-rule-statement-forwarded-ip-address.md). 
+ A Bot Control rule with a low global false positive rate might heavily impact specific devices or applications. For example, in testing and validation, we might not have observed requests from applications with low traffic volumes or from less common browsers or devices. 
+ A Bot Control rule that has a historically low false positive rate might have increased false positives for valid traffic. This might be due to new traffic patterns or request attributes that emerge with valid traffic, causing it to match the rule where it didn't before. These changes might be due to situations like the following:
  + Traffic details that are altered as traffic flows through network appliances, such as load balancers or content distribution networks (CDN).
  + Emerging changes in traffic data, for example new browsers or new versions for existing browsers.

For information about how to handle false positives that you might get from the AWS WAF Bot Control managed rule group, see the guidance in the section that follows, [Testing and deploying AWS WAF Bot Control](waf-bot-control-deploying.md).

# Testing and deploying AWS WAF Bot Control
Testing and deploying Bot Control

This section provides general guidance for configuring and testing an AWS WAF Bot Control implementation for your site. The specific steps that you choose to follow will depend on your needs, resources, and the web requests that you receive. 

This information is in addition to the general information about testing and tuning provided at [Testing and tuning your AWS WAF protections](web-acl-testing.md).

**Note**  
AWS Managed Rules are designed to protect you from common web threats. When used in accordance with the documentation, AWS Managed Rules rule groups add another layer of security for your applications. However, AWS Managed Rules rule groups aren't intended as a replacement for your security responsibilities, which are determined by the AWS resources that you select. Refer to the [Shared Responsibility Model](https://aws.amazon.com/compliance/shared-responsibility-model/) to ensure that your resources in AWS are properly protected. 

**Production traffic risk**  
Before you deploy your Bot Control implementation for production traffic, test and tune it in a staging or testing environment until you are comfortable with the potential impact to your traffic. Then test and tune the rules in count mode with your production traffic before enabling them. 

This guidance is intended for users who know generally how to create and manage AWS WAF protection packs (web ACLs), rules, and rule groups. Those topics are covered in prior sections of this guide. 

**To configure and test a Bot Control implementation**

Perform these steps first in a test environment, then in production.

1. 

**Add the Bot Control managed rule group**
**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

   Add the managed AWS rule group `AWSManagedRulesBotControlRuleSet` to a new or existing protection pack (web ACL) and configure it so that it doesn't alter current protection pack (web ACL) behavior. 
   + When you add the managed rule group, edit it and do the following: 
     + In the **Inspection level** pane, select the inspection level that you want to use. 
       + **Common** – Detects a variety of self-identifying bots, such as web scraping frameworks, search engines, and automated browsers. Bot Control protections at this level identify common bots using traditional bot detection techniques, such as static request data analysis. The rules label traffic from these bots and block the ones that they cannot verify. 
       + **Targeted** – Includes the common-level protections and adds targeted detection for sophisticated bots that do not self identify. Targeted protections mitigate bot activity using a combination of rate limiting and CAPTCHA and background browser challenges. 
         + **`TGT_`** – Rules that provide targeted protection have names that begin with `TGT_`. All targeted protections use detection techniques such as browser interrogation, fingerprinting, and behavior heuristics to identify bad bot traffic. 
         + **`TGT_ML_`** – Targeted protection rules that use machine learning have names that begin with `TGT_ML_`. These rules use automated, machine-learning analysis of website traffic statistics to detect anomalous behavior indicative of distributed, coordinated bot activity. AWS WAF analyzes statistics about your website traffic such as timestamps, browser characteristics, and previous URL visited, to improve the Bot Control machine learning model. Machine learning capabilities are enabled by default, but you can disable them in your rule group configuration. When machine learning is disabled, AWS WAF does not evaluate these rules. 

       For more information about this choice, see [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md). 
     + In the **Rules** pane, open the **Override all rule actions** dropdown and choose **Count**. With this configuration, AWS WAF evaluates requests against all of the rules in the rule group and only counts the matches that result, while still adding labels to requests. For more information, see [Overriding rule actions in a rule group](web-acl-rule-group-settings.md#web-acl-rule-group-rule-action-override).

       With this override, you can monitor the potential impact of the Bot Control rules on your traffic, to determine whether you want to add exceptions for things like internal use cases or desired bots. 
   + Position the rule group so that it's evaluated last in the protection pack (web ACL), with a priority setting that's numerically higher than any other rules or rule groups that you're already using. For more information, see [Setting rule priority](web-acl-processing-order.md). 

     This way, your current handling of traffic isn't disrupted. For example, if you have rules that detect malicious traffic such as SQL injection or cross-site scripting, they'll continue to detect and log those requests. Alternately, if you have rules that allow known non-malicious traffic, they can continue to allow that traffic, without having it blocked by the Bot Control managed rule group. You might decide to adjust the processing order during your testing and tuning activities, but this is a good way to start.

1. 

**Enable logging and metrics for the protection pack (web ACL)**

   As needed, configure logging, Amazon Security Lake data collection, request sampling, and Amazon CloudWatch metrics for the protection pack (web ACL). You can use these visibility tools to monitor the interaction of the Bot Control managed rule group with your traffic. 
   + For information about logging, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md). 
   + For information about Amazon Security Lake, see [What is Amazon Security Lake?](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html) and [Collecting data from AWS services](https://docs.aws.amazon.com/security-lake/latest/userguide/internal-sources.html) in the *Amazon Security Lake user guide*. 
   + For information about Amazon CloudWatch metrics, see [Monitoring with Amazon CloudWatch](monitoring-cloudwatch.md). 
   + For information about web request sampling, see [Viewing a sample of web requests](web-acl-testing-view-sample.md). 

1. 

**Associate the protection pack (web ACL) with a resource**

   If the protection pack (web ACL) isn't already associated with a resource, associate it. For information, see [Associating or disassociating protection with an AWS resource](web-acl-associating-aws-resource.md).

1. 

**Monitor traffic and Bot Control rule matches**

   Make sure that traffic is flowing and that the Bot Control managed rule group rules are adding labels to matching web requests. You can see the labels in the logs and see bot and label metrics in the Amazon CloudWatch metrics. In the logs, the rules that you've overridden to count in the rule group show up in the `ruleGroupList` with `action` set to count, and with `overriddenAction` indicating the configured rule action that you overrode.
**Note**  
The Bot Control managed rule group verifies bots using the IP addresses from AWS WAF. If you use Bot Control and you have verified bots that route through a proxy or load balancer, you might need to explicitly allow them using a custom rule. For information about how to create a custom rule, see [Using forwarded IP addresses in AWS WAF](waf-rule-statement-forwarded-ip-address.md). For information about how you can use the rule to customize Bot Control web request handling, see the next step. 

   Carefully review the web request handling for any false positives that you might need to mitigate with custom handling. For examples of false positives, see [Example scenarios of false positives with AWS WAF Bot Control](waf-bot-control-false-positives.md).

1. 

**Customize Bot Control web request handling**

   As needed, add your own rules that explicitly allow or block requests, to change how Bot Control rules would otherwise handle them. 

   How you do this depends on your use case, but the following are common solutions:
   + Explicitly allow requests with a rule that you add before the Bot Control managed rule group. With this, the allowed requests never reach the rule group for evaluation. This can help contain the cost of using the Bot Control managed rule group. 
   + Exclude requests from Bot Control evaluation by adding a scope-down statement inside the Bot Control managed rule group statement. This functions the same as the preceding option. It can help contain the cost of using the Bot Control managed rule group because the requests that don't match the scope-down statement never reach rule group evaluation. For information about scope-down statements, see [Using scope-down statements in AWS WAF](waf-rule-scope-down-statements.md). 

     For examples, see the following: 
     + [Excluding IP range from bot management](waf-bot-control-example-scope-down-ip.md)
     + [Allowing traffic from a bot that you control](waf-bot-control-example-scope-down-your-bot.md)
   + Use Bot Control labels in request handling to allow or block requests. Add a label match rule after the Bot Control managed rule group to filter out labeled requests that you want to allow from those that you want to block. 

     After testing, keep the related Bot Control rules in count mode, and maintain the request handling decisions in your custom rule. For information about label match statements, see [Label match rule statement](waf-rule-statement-type-label-match.md). 

     For examples of this type of customization, see the following: 
     + [Creating an exception for a blocked user agent](waf-bot-control-example-user-agent-exception.md)
     + [Allowing a specific blocked bot](waf-bot-control-example-allow-blocked-bot.md)
     + [Blocking verified bots](waf-bot-control-example-block-verified-bots.md)

   For additional examples, see [AWS WAF Bot Control examples](waf-bot-control-examples.md).

1. 

**As needed, enable the Bot Control managed rule group settings**

   Depending on your situation, you might have decided that you want to leave some Bot Control rules in count mode or with a different action override. For the rules that you want to have run as they are configured inside the rule group, enable the regular rule configuration. To do this, edit the rule group statement in your protection pack (web ACL) and make your changes in the **Rules** pane. 

# AWS WAF Bot Control examples
Bot Control examplesUpdated Bot Control examples

Added examples depicting the targeted inspection level and updated existing examples to reflect best practices.

This section shows example configurations that satisfy a variety of common use cases for AWS WAF Bot Control implementations. 

Each example provides a description of the use case and then shows the solution in JSON listings for the custom configured rules. 

**Note**  
The JSON listings shown in these examples were created in the console by configuring the rule and then editing it using the **Rule JSON editor**. 

**Topics**
+ [

# Bot Control example: Simple configuration
](waf-bot-control-example-basic.md)
+ [

# Bot Control example: Explicitly allowing verified bots
](waf-bot-control-example-allow-verified-bots.md)
+ [

# Bot Control example: Blocking verified bots
](waf-bot-control-example-block-verified-bots.md)
+ [

# Bot Control example: Allowing a specific blocked bot
](waf-bot-control-example-allow-blocked-bot.md)
+ [

# Bot Control example: Creating an exception for a blocked user agent
](waf-bot-control-example-user-agent-exception.md)
+ [

# Bot Control example: Using Bot Control only for the login page
](waf-bot-control-example-scope-down-login.md)
+ [

# Bot Control example: Using Bot Control only for dynamic content
](waf-bot-control-example-scope-down-dynamic-content.md)
+ [

# Bot Control example: Excluding IP range from bot management
](waf-bot-control-example-scope-down-ip.md)
+ [

# Bot Control example: Allowing traffic from a bot that you control
](waf-bot-control-example-scope-down-your-bot.md)
+ [

# Bot Control example: Enabling targeted inspection level
](waf-bot-control-example-targeted-inspection-level.md)
+ [

# Bot Control example: Using two statements to limit the use of the targeted inspection level
](waf-bot-control-example-common-and-targeted-inspection-level.md)

# Bot Control example: Simple configuration
Simple configuration

The following JSON listing shows an example protection pack (web ACL) with an AWS WAF Bot Control managed rule group. Note the visibility configuration, which causes AWS WAF to store request samples and metrics for monitoring purposes. 

```
{
  "Name": "Bot-WebACL",
  "Id": "...",
  "ARN": "...",
  "DefaultAction": {
    "Allow": {}
  },
  "Description": "Bot-WebACL",
  "Rules": [
      {
        ...
      },
      {
         "Name": "AWS-AWSBotControl-Example",
         "Priority": 5,
         "Statement": {
            "ManagedRuleGroupStatement": {
               "VendorName": "AWS",
               "Name": "AWSManagedRulesBotControlRuleSet",
               "ManagedRuleGroupConfigs": [
                 {
                   "AWSManagedRulesBotControlRuleSet": {
                     "InspectionLevel": "COMMON"
                   }
                 }
               ],
               "RuleActionOverrides": [],
               "ExcludedRules": []
            },
            "VisibilityConfig": {
               "SampledRequestsEnabled": true,
               "CloudWatchMetricsEnabled": true,
               "MetricName": "AWS-AWSBotControl-Example"
             }
          }
      }
    ],
    "VisibilityConfig": {
      ...
    },
    "Capacity": 1496,
    "ManagedByFirewallManager": false,
    "RetrofittedByFirewallManager": false
}
```

# Bot Control example: Explicitly allowing verified bots
Explicitly allowing verified bots

AWS WAF Bot Control doesn't block bots that are known by AWS to be common and verifiable bots. When Bot Control identifies a web request as coming from a verified bot, it adds a label that names the bot and a label that indicates that it's a verified bot. Bot Control doesn't add any other labels, such as signals labels, in order to prevent known good bots from being blocked.

You might have other AWS WAF rules that block verified bots. If you want to ensure that verified bots are allowed, add a custom rule to allow them based on the Bot Control labels. Your new rule must run after the Bot Control managed rule group, so that the labels are available to match against. 

The following rule explicitly allows verified bots.

```
{
    "Name": "match_rule",
    "Statement": {
      "LabelMatchStatement": {
        "Scope": "LABEL",
        "Key": "awswaf:managed:aws:bot-control:bot:verified"
      }
    },
    "RuleLabels": [],
    "Action": {
      "Allow": {}
    }
}
```

# Bot Control example: Blocking verified bots
Blocking verified bots

In order to block verified bots, you must add a rule to block them that runs after the AWS WAF Bot Control managed rule group. To do this, identify the bot names that you want to block and use a label match statement to identify and block them. If you want to just block all verified bots, you can omit the match against the `bot:name:` label. 

The following rule blocks only the `bingbot` verified bot. This rule must run after the Bot Control managed rule group.

```
{
    "Name": "match_rule",
    "Statement": {
      "AndStatement": {
        "Statements": [
          {
            "LabelMatchStatement": {
              "Scope": "LABEL",
              "Key": "awswaf:managed:aws:bot-control:bot:name:bingbot"
            }
          },
          {
            "LabelMatchStatement": {
              "Scope": "LABEL",
              "Key": "awswaf:managed:aws:bot-control:bot:verified"
            }
          }
        ]
      }
    },
    "RuleLabels": [],
    "Action": {
      "Block": {}
    }
  }
```

The following rule blocks all verified bots.

```
{
    "Name": "match_rule",
    "Statement": {
      "LabelMatchStatement": {
        "Scope": "LABEL",
        "Key": "awswaf:managed:aws:bot-control:bot:verified"
      }
    },
    "RuleLabels": [],
    "Action": {
      "Block": {}
    }
}
```

# Bot Control example: Allowing a specific blocked bot
Allowing a specific blocked bot

It's possible for a bot to be blocked by more than one of the Bot Control rules. Run through the following procedure for each blocking rule. 

If an AWS WAF Bot Control rule is blocking a bot that you do not want to block, do the following:

1. Identify the Bot Control rule that's blocking the bot by checking the logs. The blocking rule will be specified in the logs in the fields whose names start with `terminatingRule`. For information about the protection pack (web ACL) logs, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md). Note the label that the rule is adds to the requests. 

1. In your protection pack (web ACL), override the action of the blocking rule to count. To do this in the console, edit the rule group rule in the protection pack (web ACL) and choose a rule action override of Count for the rule. This ensures that the bot is not blocked by the rule, but the rule will still apply its label to matching requests. 

1. Add a label matching rule to your protection pack (web ACL), after the Bot Control managed rule group. Configure the rule to match against the overridden rule's label and to block all matching requests except for the bot that you don't want to block. 

   Your protection pack (web ACL) is now configured so that the bot you want to allow is no longer blocked by the blocking rule that you identified through the logs. 

Check traffic and your logs again, to be sure that the bot is being allowed through. If not, run through the above procedure again.

For example, suppose you want to block all monitoring bots except for `pingdom`. In this case, you override the `CategoryMonitoring` rule to count and then write a rule to block all monitoring bots except for those with the bot name label `pingdom`. 

The following rule uses the Bot Control managed rule group but overrides the rule action for `CategoryMonitoring` to count. The category monitoring rule applies its labels as usual to matching requests, but only counts them instead of performing its usual action of block. 

```
{
  "Name": "AWS-AWSBotControl-Example",
  "Priority": 5,
  "Statement": {
    "ManagedRuleGroupStatement": {
      "VendorName": "AWS",
      "Name": "AWSManagedRulesBotControlRuleSet",
      "ManagedRuleGroupConfigs": [
        {
          "AWSManagedRulesBotControlRuleSet": {
            "InspectionLevel": "COMMON"
          }
        }
      ],
	  "RuleActionOverrides": [
        {
          "ActionToUse": {
            "Count": {}
          },
          "Name": "CategoryMonitoring"
        }
      ],
      "ExcludedRules": []
    }
  },
  "VisibilityConfig": {
    "SampledRequestsEnabled": true,
    "CloudWatchMetricsEnabled": true,
    "MetricName": "AWS-AWSBotControl-Example"
  }
}
```

The following rule matches against the category monitoring label that the preceding `CategoryMonitoring` rule adds to matching web requests. Among the category monitoring requests, this rule blocks all but those that have a label for the bot name `pingdom`. 

The following rule must run after the preceding Bot Control managed rule group in the protection pack (web ACL) processing order. 

```
{
      "Name": "match_rule",
      "Priority": 10,
      "Statement": {
        "AndStatement": {
          "Statements": [
            {
              "LabelMatchStatement": {
                "Scope": "LABEL",
                "Key": "awswaf:managed:aws:bot-control:bot:category:monitoring"
              }
            },
            {
              "NotStatement": {
                "Statement": {
                  "LabelMatchStatement": {
                    "Scope": "LABEL",
                    "Key": "awswaf:managed:aws:bot-control:bot:name:pingdom"
                  }
                }
              }
            }
          ]
        }
      },
      "Action": {
        "Block": {}
      },
      "VisibilityConfig": {
        "SampledRequestsEnabled": true,
        "CloudWatchMetricsEnabled": true,
        "MetricName": "match_rule"
      }
}
```

# Bot Control example: Creating an exception for a blocked user agent
Creating an exception for a blocked user agent

If traffic from some non-browser user agents is being erroneously blocked, you can create an exception by setting the offending AWS WAF Bot Control rule `SignalNonBrowserUserAgent` to Count and then combining the rule's labeling with your exception criteria. 

**Note**  
Mobile apps typically have non-browser user agents, which the `SignalNonBrowserUserAgent` rule blocks by default. 

The following rule uses the Bot Control managed rule group but overrides the rule action for `SignalNonBrowserUserAgent` to Count. The signal rule applies its labels as usual to matching requests, but only counts them instead of performing its usual action of block. 

```
{
  "Name": "AWS-AWSBotControl-Example",
  "Priority": 5,
  "Statement": {
    "ManagedRuleGroupStatement": {
      "VendorName": "AWS",
      "Name": "AWSManagedRulesBotControlRuleSet",
      "ManagedRuleGroupConfigs": [
        {
          "AWSManagedRulesBotControlRuleSet": {
            "InspectionLevel": "COMMON"
          }
        }
      ],
	  "RuleActionOverrides": [
        {
          "ActionToUse": {
            "Count": {}
          },
          "Name": "SignalNonBrowserUserAgent"
        }
      ],
      "ExcludedRules": []
    }
  },
  "VisibilityConfig": {
    "SampledRequestsEnabled": true,
    "CloudWatchMetricsEnabled": true,
    "MetricName": "AWS-AWSBotControl-Example"
  }
}
```

The following rule matches against the signal label that the Bot Control `SignalNonBrowserUserAgent` rule adds to its matching web requests. Among the signal requests, this rule blocks all but those that have the user agent that we want to allow. 

The following rule must run after the preceding Bot Control managed rule group in the protection pack (web ACL) processing order. 

```
{
    "Name": "match_rule",
    "Statement": {
      "AndStatement": {
        "Statements": [
          {
            "LabelMatchStatement": {
              "Scope": "LABEL",
              "Key": "awswaf:managed:aws:bot-control:signal:non_browser_user_agent"
            }
          },
          {
            "NotStatement": {
              "Statement": {
                "ByteMatchStatement": {
                  "FieldToMatch": {
                    "SingleHeader": {
                      "Name": "user-agent"
                    }
                  },
                  "PositionalConstraint": "EXACTLY",
                  "SearchString": "PostmanRuntime/7.29.2",
                  "TextTransformations": [
                    {
                      "Priority": 0,
                      "Type": "NONE"
                    }
                  ]
                }
              }
            }
          }
        ]
      }
    },
    "RuleLabels": [],
    "Action": {
      "Block": {}
    },
    "VisibilityConfig": {
      "SampledRequestsEnabled": true,
      "CloudWatchMetricsEnabled": true,
      "MetricName": "match_rule"
    }
}
```

# Bot Control example: Using Bot Control only for the login page
Using Bot Control only for the login page

The following example uses a scope-down statement to apply AWS WAF Bot Control only for traffic that's coming to a website's login page, which is identified by the URI path `login`. The URI path to your login page might be different from the example, depending on your application and environment.

```
{
  "Name": "AWS-AWSBotControl-Example",
  "Priority": 5,
  "Statement": {
    "ManagedRuleGroupStatement": {
      "VendorName": "AWS",
      "Name": "AWSManagedRulesBotControlRuleSet",
	  "ManagedRuleGroupConfigs": [
        {
          "AWSManagedRulesBotControlRuleSet": {
            "InspectionLevel": "COMMON"
          }
        }
      ],
      "RuleActionOverrides": [],
      "ExcludedRules": []
    },
    "VisibilityConfig": {
      "SampledRequestsEnabled": true,
      "CloudWatchMetricsEnabled": true,
      "MetricName": "AWS-AWSBotControl-Example"
    },
    "ScopeDownStatement": {
      "ByteMatchStatement": {
        "SearchString": "login",
        "FieldToMatch": {
          "UriPath": {}
        },
        "TextTransformations": [
          {
            "Priority": 0,
            "Type": "NONE"
          }
        ],
        "PositionalConstraint": "CONTAINS"
      }
    }
  }
}
```

# Bot Control example: Using Bot Control only for dynamic content
Using Bot Control only for dynamic content

This example uses a scope-down statement to apply AWS WAF Bot Control only to dynamic content. 

The scope-down statement excludes static content by negating the match results for a regex pattern set: 
+ The regex pattern set is configured to match extensions of *static content*. For example, the regex pattern set specification might be `(?i)\.(jpe?g|gif|png|svg|ico|css|js|woff2?)$`. For information about regex pattern sets and statements, see [Regex pattern set match rule statement](waf-rule-statement-type-regex-pattern-set-match.md). 
+ In the scope-down statement, we exclude the matching static content by nesting the regex pattern set statement inside a `NOT` statement. For information about the `NOT` statement, see [NOT rule statement](waf-rule-statement-type-not.md).

```
{
  "Name": "AWS-AWSBotControl-Example",
  "Priority": 5,
  "Statement": {
    "ManagedRuleGroupStatement": {
      "VendorName": "AWS",
      "Name": "AWSManagedRulesBotControlRuleSet",
	  "ManagedRuleGroupConfigs": [
        {
          "AWSManagedRulesBotControlRuleSet": {
            "InspectionLevel": "COMMON"
          }
        }
      ],
      "RuleActionOverrides": [],
      "ExcludedRules": []
    },
    "VisibilityConfig": {
      "SampledRequestsEnabled": true,
      "CloudWatchMetricsEnabled": true,
      "MetricName": "AWS-AWSBotControl-Example"
    },
    "ScopeDownStatement": {
      "NotStatement": {
        "Statement": {
          "RegexPatternSetReferenceStatement": {
            "ARN": "arn:aws:wafv2:us-east-1:123456789:regional/regexpatternset/excludeset/00000000-0000-0000-0000-000000000000",
            "FieldToMatch": {
              "UriPath": {}
            },
            "TextTransformations": [
              {
                "Priority": 0,
                "Type": "NONE"
              }
            ]
          }
        }
      }
    }
  }
}
```

# Bot Control example: Excluding IP range from bot management
Excluding IP range from bot management

If you want to exclude a subset of web traffic from AWS WAF Bot Control management, and you can identify that subset using a rule statement, then exclude it by adding a scope-down statement to your Bot Control managed rule group statement. 

The following rule performs normal Bot Control bot management on all web traffic except for web requests coming from a specific IP address range.

```
{
  "Name": "AWS-AWSBotControl-Example",
  "Priority": 5,
  "Statement": {
    "ManagedRuleGroupStatement": {
      "VendorName": "AWS",
      "Name": "AWSManagedRulesBotControlRuleSet",
      "ManagedRuleGroupConfigs": [
        {
          "AWSManagedRulesBotControlRuleSet": {
            "InspectionLevel": "COMMON"
          }
        }
      ],
      "RuleActionOverrides": [],
      "ExcludedRules": []
    },
    "VisibilityConfig": {
      "SampledRequestsEnabled": true,
      "CloudWatchMetricsEnabled": true,
      "MetricName": "AWS-AWSBotControl-Example"
    },
    "ScopeDownStatement": {
      "NotStatement": {
        "Statement": {
          "IPSetReferenceStatement": {
            "ARN": "arn:aws:wafv2:us-east-1:123456789:regional/ipset/friendlyips/00000000-0000-0000-0000-000000000000"
          }
        }
      }
    }
  }
}
```

# Bot Control example: Allowing traffic from a bot that you control
Allowing traffic from a bot that you control

You can configure some site monitoring bots and custom bots to send custom headers. If you want to allow traffic from these types of bots, you can configure them to add a shared secret in a header. You then can exclude messages that have the header by adding a scope-down statement to the AWS WAF Bot Control managed rule group statement. 

The following example rule excludes traffic with a secret header from Bot Control inspection.

```
{
  "Name": "AWS-AWSBotControl-Example",
  "Priority": 5,
  "Statement": {
    "ManagedRuleGroupStatement": {
      "VendorName": "AWS",
      "Name": "AWSManagedRulesBotControlRuleSet",
      "ManagedRuleGroupConfigs": [
        {
          "AWSManagedRulesBotControlRuleSet": {
            "InspectionLevel": "COMMON"
          }
        }
      ],
      "RuleActionOverrides": [],
      "ExcludedRules": []
    },
    "VisibilityConfig": {
      "SampledRequestsEnabled": true,
      "CloudWatchMetricsEnabled": true,
      "MetricName": "AWS-AWSBotControl-Example"
    },
    "ScopeDownStatement": {
      "NotStatement": {
        "Statement": {
          "ByteMatchStatement": {
            "SearchString": "YSBzZWNyZXQ=",
            "FieldToMatch": {
              "SingleHeader": {
                "Name": "x-bypass-secret"
              }
            },
            "TextTransformations": [
              {
                "Priority": 0,
                "Type": "NONE"
              }
            ],
            "PositionalConstraint": "EXACTLY"
          }
        }
      }
    }
  }
}
```

# Bot Control example: Enabling targeted inspection level
Enabling targeted inspection level

For an enhanced level of protection, you can enable the targeted inspection level in your AWS WAF Bot Control managed rule group.

In the following example, machine learning features are enabled. You can opt out of this behavior by setting `EnableMachineLearning` to `false`.

```
{
  "Name": "AWS-AWSBotControl-Example",
  "Priority": 5,
  "Statement": {
    "ManagedRuleGroupStatement": {
      "VendorName": "AWS",
      "Name": "AWSManagedRulesBotControlRuleSet",
      "ManagedRuleGroupConfigs": [
        {
          "AWSManagedRulesBotControlRuleSet": {
            "InspectionLevel": "TARGETED",
            "EnableMachineLearning": true
          }
        }
      ],
      "RuleActionOverrides": [],
      "ExcludedRules": []
    },
    "VisibilityConfig": {
      "SampledRequestsEnabled": true,
      "CloudWatchMetricsEnabled": true,
      "MetricName": "AWS-AWSBotControl-Example"
    }
  }
}
```

# Bot Control example: Using two statements to limit the use of the targeted inspection level
Using two statements to limit the use of targeted inspection level

As a cost optimization, you can use two AWS WAF Bot Control managed rule group statements in your protection pack (web ACL), with separate inspection levels and scoping. For instance, you could scope the targeted inspection level statement only to more sensitive application endpoints.

The two statements in the following example have mutually exclusive scoping. Without this configuration, a request could result in two billed Bot Control evaluations.

**Note**  
Multiple statements referencing `AWSManagedRulesBotControlRuleSet` are not supported in the visual editor in the console. Instead, use the JSON editor.

```
{
  "Name": "Bot-WebACL",
  "Id": "...",
  "ARN": "...",
  "DefaultAction": {
    "Allow": {}
  },
  "Description": "Bot-WebACL",
  "Rules": [
      {
        ...
      },
      {
       "Name": "AWS-AWSBotControl-Common",
       "Priority": 5,
       "Statement": {
          "ManagedRuleGroupStatement": {
             "VendorName": "AWS",
             "Name": "AWSManagedRulesBotControlRuleSet",
             "ManagedRuleGroupConfigs": [
               {
                 "AWSManagedRulesBotControlRuleSet": {
                   "InspectionLevel": "COMMON"
                 }
               }
             ],
             "RuleActionOverrides": [],
             "ExcludedRules": []
          },
          "VisibilityConfig": {
             "SampledRequestsEnabled": true,
             "CloudWatchMetricsEnabled": true,
             "MetricName": "AWS-AWSBotControl-Common"
           },
           "ScopeDownStatement": {
              "NotStatement": {
                "Statement": {
                  "ByteMatchStatement": {
                    "FieldToMatch": {
                      "UriPath": {}
                    },
                    "PositionalConstraint": "STARTS_WITH",
                    "SearchString": "/sensitive-endpoint",
                    "TextTransformations": [
                      {
                        "Type": "NONE",
                        "Priority": 0
                      }
                    ]
                  }
                }
              }
            }
        }
      },
      {
       "Name": "AWS-AWSBotControl-Targeted",
       "Priority": 6,
       "Statement": {
          "ManagedRuleGroupStatement": {
             "VendorName": "AWS",
             "Name": "AWSManagedRulesBotControlRuleSet",
             "ManagedRuleGroupConfigs": [
               {
                 "AWSManagedRulesBotControlRuleSet": {
                   "InspectionLevel": "TARGETED",
                   "EnableMachineLearning": true
                 }
               }
             ],
             "RuleActionOverrides": [],
             "ExcludedRules": []
          },
          "VisibilityConfig": {
             "SampledRequestsEnabled": true,
             "CloudWatchMetricsEnabled": true,
             "MetricName": "AWS-AWSBotControl-Targeted"
           },
           "ScopeDownStatement": {
              "Statement": {
                "ByteMatchStatement": {
                  "FieldToMatch": {
                    "UriPath": {}
                  },
                  "PositionalConstraint": "STARTS_WITH",
                  "SearchString": "/sensitive-endpoint",
                  "TextTransformations": [
                    {
                      "Type": "NONE",
                      "Priority": 0
                    }
                  ]
                }
              }
            }
        }
      }
    ],
    "VisibilityConfig": {
      ...
    },
    "Capacity": 1496,
    "ManagedByFirewallManager": false,
    "RetrofittedByFirewallManager": false
}
```

# AWS WAF Distributed Denial of Service (DDoS) prevention
Distributed Denial of Service (DDoS) preventionAWS WAF adds resource-level DDoS protection

You can now use Anti-DDoS functionality to detect and prevent DDoS attacks in Application Load Balancers.

AWS WAF offers sophisticated and customizable protection against DDoS attacks in your AWS resources. Review the options described in this section and select the level of Anti-DDoS protection that meets your security and business needs.

You can choose from two tiers of DDoS protection in AWS WAF:

Resource-level DDoS protection  
The standard tier works within Application Load Balancers to defend against known malicious sources through on-host filtering. You can configure the protective behavior to best react to potential DDoS events.  
Resource-level DDoS protection:  
+ Monitors your traffic patterns automatically.
+ Updates threat intelligence in real time.
+ Protects against known malicious sources.
**To optimize web ACL request costs for your Application Load Balancer**  
You must associate a web ACL with your Application Load Balancer to enable resource-level protection. If your Application Load Balancer is associated with a web ACL that has no configuration, you will not incur charges from AWS WAF requests, however, AWS WAF will not provide sampled requests or report on the Application Load Balancer in CloudWatch metrics. You can take the following actions to enable observability features for the Application Load Balancer:  
+ Use the `Block` action or `Allow` action with custom request headers in the `DefaultAction`. For information, see [Inserting custom request headers for non-blocking actions](customizing-the-incoming-request.md).
+ Add any rules to the web ACL. For information, see [AWS WAF rules](waf-rules.md).
+ Enable a logging destination. For information, see [Configuring logging for a protection pack (web ACL)](logging-management-configure.md).
+ Associate the web ACL with an AWS Firewall Manager policy. For information, see [Creating an AWS Firewall Manager policy for AWS WAF](create-policy.md#creating-firewall-manager-policy-for-waf).
AWS WAF will not provide sampled requests or publish CloudWatch metrics without these configurations.

AWS managed rule group DDoS protection  
The advanced tier of DDoS protections is offered through the `AWSManagedRulesAntiDDoSRuleSet`. The managed rule group complements the resource-level tier of protection, with the following notable differences:  
+ Protection extends to both Application Load Balancers and CloudFront distributions
+ Traffic baselines are created for your protected resources to improve detection of novel attack patterns.
+ Protective behavior is activated according to sensitivity levels you select.
+ Manages and labels requests to protected resources during probable DDoS events.
For a comprehensive list of the rules and functionality included, see [AWS WAF Distributed Denial of Service (DDoS) prevention rule group](aws-managed-rule-groups-anti-ddos.md).

**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

**Topics**
+ [

# Resource-level DDoS protection for Application Load Balancers
](waf-anti-ddos-alb.md)
+ [

# Advanced Anti-DDoS protection using the AWS WAF Anti-DDoS managed rule group
](waf-anti-ddos-advanced.md)

# Resource-level DDoS protection for Application Load Balancers
Resource-level DDoS protection

**Resource level DDoS protection** adds immediate defense to Application Load Balancers without incurring charges of deploying AWS WAF managed rule groups. This standard tier of Anti-DDoS protection uses AWS threat intelligence and traffic pattern analysis to protect Application Load Balancers. To identify known malicous sources, Anti-DDoS protection performs on-host filtering of both direct client IP addresses and X-Forwarded-For (XFF) headers. After a known malicious source is identified, protection is activated through one of two modes:

**Active under DDoS** is the default protective mode and is recommended for most use cases. 

This mode:
+ Activates protection automatically when detecting high load conditions or potential DDoS events
+ Rate-limits traffic from known malicious sources only during attack conditions
+ Minimizes impact on legitimate traffic during normal operations
+ Uses Application Load Balancer health metrics and AWS WAF response data to determine when to engage protection

**Always on** is an optional mode that is always active once enabled.

This mode: 
+ Maintains continuous protection against known malicious sources
+ Rate-limits traffic from known malicious sources in real time
+ Applies protection to both direct connections and requests with malicious IPs in XFF headers
+ May have higher impact on legitimate traffic but provides maximum security

Requests blocked by resource-level DDoS protection are recorded in CloudWatch logs as either `LowReputationPacketsDropped` or `LowReputationRequestsDenied` metrics. For information, see [AWS WAF core metrics and dimensions](waf-metrics.md#waf-metrics-general).

## Enable standard DDoS protection on an existing webACL


You can enable DDoS protection when you create a web ACL or update an existing web ACL associated with Application Load Balancer.

**Note**  
If you have an existing web ACL that is associated with an Application Load Balancer, Anti-DDoS protection is enabled by default with **Active under DDoS** mode.

**To enable Anti-DDoS protection in the AWS WAF console**

1. Sign in to the AWS Management Console and open the AWS WAF console at [https://console.aws.amazon.com/wafv2/homev2](https://console.aws.amazon.com/wafv2/homev2). 

1. Choose **Web ACLs** in the navigation pane, and then open any web ACL that is associated with an Application Load Balancer.

1. Choose **Associated AWS resources**.

1. Under **Resource level DDoS protection**, choose **Edit**.

1. Select one of the following protection modes:
   + **Active under DDoS** (recommended) - Protection engages only during high load conditions
   + **Always on** - Always-on protection against known malicious sources

1. Choose **Save changes**.

**Note**  
For information about creating a web ACL, see [Creating a protection pack (web ACL) in AWS WAF](web-acl-creating.md).

**To optimize web ACL request costs for your Application Load Balancer**  
You must associate a web ACL with your Application Load Balancer to enable resource-level protection. If your Application Load Balancer is associated with a web ACL that has no configuration, you will not incur charges from AWS WAF requests, however, AWS WAF will not provide sampled requests or report on the Application Load Balancer in CloudWatch metrics. You can take the following actions to enable observability features for the Application Load Balancer:  
Use the `Block` action or `Allow` action with custom request headers in the `DefaultAction`. For information, see [Inserting custom request headers for non-blocking actions](customizing-the-incoming-request.md).
Add any rules to the web ACL. For information, see [AWS WAF rules](waf-rules.md).
Enable a logging destination. For information, see [Configuring logging for a protection pack (web ACL)](logging-management-configure.md).
Associate the web ACL with an AWS Firewall Manager policy. For information, see [Creating an AWS Firewall Manager policy for AWS WAF](create-policy.md#creating-firewall-manager-policy-for-waf).
AWS WAF will not provide sampled requests or publish CloudWatch metrics without these configurations.

# Advanced Anti-DDoS protection using the AWS WAF Anti-DDoS managed rule group
Using the Anti-DDoS managed rule group

The `AWSManagedRulesAntiDDoSRuleSet` managed rule group is the most advanced tier of Anti-DDoS protections available in AWS WAF.

**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

## AWS WAF Anti-DDoS protection components
Anti-DDoS protection components

The main components for implementing advanced Anti-DDoS protection in AWS WAF include the following:

**`AWSManagedRulesAntiDDoSRuleSet`** – Detects, labels, and challenges requests that are likely participating in a DDoS attack. It also labels all requests to a protected resource during an event. For details about the rule group's rules and labels, see [AWS WAF Distributed Denial of Service (DDoS) prevention rule group](aws-managed-rule-groups-anti-ddos.md). To use this rule group, include it in your protection pack (web ACL) using a managed rule group reference statement. For information, see [Adding the Anti-DDoS managed rule group to your protection pack (web ACL)](waf-anti-ddos-rg-using.md).
+ **Web ACL traffic overview dashboards** – Provide monitoring for DDoS activity and anti-DDoS responses in the console. For more information, see [Traffic overview dashboards for protection packs (web ACLs)](web-acl-dashboards.md).
+ **Logging and metrics** – Allow you to monitor traffic and understand Anti-DDoS protection effects. Configure logs, Amazon Security Lake data collection, and Amazon CloudWatch metrics for your protection pack (web ACL). For information about these options, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md), [Monitoring with Amazon CloudWatch](monitoring-cloudwatch.md), and [What is Amazon Security Lake?](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html).
+ **Labels and label matching rules** – Allow you to customize handling of web requests identified by the Anti-DDoS managed rule group. For any rule in `AWSManagedRulesAntiDDoSRuleSet`, you can switch to count mode and match against added labels. For more information, see [Label match rule statement](waf-rule-statement-type-label-match.md) and [Web request labeling in AWS WAF](waf-labels.md).
+ **Custom requests and responses** – Allow you to add custom headers to allowed requests and send custom responses for blocked requests. Pair label matching with AWS WAF custom request and response features. For more information, see [Customized web requests and responses in AWS WAF](waf-custom-request-response.md).

# Adding the Anti-DDoS managed rule group to your protection pack (web ACL)
Adding the Anti-DDoS managed rule group to your protection pack (web ACL)

This section explains how to add and configure the `AWSManagedRulesAntiDDoSRuleSet` rule group.

To configure the Anti-DDoS managed rule group, you provide settings that include how sensitive the rule group is to DDoS attacks and the actions that it takes on requests that are or might be participating in the attacks. This configuration is in addition to the normal configuration for a managed rule group. 

For the rule group description and rules and labels listing, see [AWS WAF Distributed Denial of Service (DDoS) prevention rule group](aws-managed-rule-groups-anti-ddos.md).

This guidance is intended for users who know generally how to create and manage AWS WAF protection packs (web ACLs), rules, and rule groups. Those topics are covered in prior sections of this guide. For basic information about how to add a managed rule group to your protection pack (web ACL), see [Adding a managed rule group to a protection pack (web ACL) through the console](waf-using-managed-rule-group.md).

**Follow best practices**  
Use the Anti-DDoS rule group in accordance with the best practices at [Best practices for intelligent threat mitigation in AWS WAF](waf-managed-protections-best-practices.md). 

**To use the `AWSManagedRulesAntiDDoSRuleSet` rule group in your protection pack (web ACL)**

1. Add the AWS managed rule group, `AWSManagedRulesAntiDDoSRuleSet` to your protection pack (web ACL), and **Edit** the rule group settings before saving. 
**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

1. In the **Rule group configuration** pane, provide any custom configuration for the `AWSManagedRulesAntiDDoSRuleSet` rule group. 

   1. For **Block sensitivity level**, specify how sensitive you want the rule `DDoSRequests` to be when matching on the rule group's DDoS suspicion labeling. The higher the sensitivity, the lower the levels of labeling that the rule matches: 
      + Low sensitivity is less sensitive, causing the rule to match only on the most obvious participants in an attack, which have the high suspicion label `awswaf:managed:aws:anti-ddos:high-suspicion-ddos-request`.
      + Medium sensitivity causes the rule to match on the medium and high suspicion labels.
      + High sensitivity causes the rule to match on all of the suspicion labels: low, medium, and high.

      This rule provides the most severe handling of web requests that are suspected of participating in DDoS attacks. 

   1. For **Enable challenge**, choose whether to enable the rules `ChallengeDDoSRequests` and `ChallengeAllDuringEvent`, which by default apply the Challenge action to matching requests. 

      These rules provide request handling that's intended to permit legitimate users to proceed with their requests while blocking participants in the DDoS attack. You can override their action settings to Allow or Count or you can disable their use entirely.

      If you enable these rules, then provide any additional configuration that you want: 
      + For **Challenge sensitivity level**, specify how sensitive you want the rule `ChallengeDDoSRequests` to be. 

        The higher the sensitivity, the lower the levels of labeling that the rule matches: 
        + Low sensitivity is less sensitive, causing the rule to match only on the most obvious participants in an attack, which have the high suspicion label `awswaf:managed:aws:anti-ddos:high-suspicion-ddos-request`.
        + Medium sensitivity causes the rule to match on the medium and high suspicion labels.
        + High sensitivity causes the rule to match on all of the suspicion labels: low, medium, and high.
      + For **Exempt URI regular expressions**, provide a regular expression that matches against URIs for web requests that can't handle a silent browser challenge. The Challenge action will effectively block requests from URIs that are missing the challenge token unless they can handle the silent browser challenge. 

        The Challenge action can only be handled properly by a client that's expecting HTML content. For more information about how the action works, see [CAPTCHA and Challenge action behavior](waf-captcha-and-challenge-actions.md). 

        Review the default regular expression and update it as needed. The rules use the specified regular expression to identify request URIs that can't handle the Challenge action and prevent the rules from sending a challenge back. Requests that you exclude in this way can only be blocked by the rule group with the rule `DDoSRequests`. 

        The default expression that's provided in the console covers most use cases, but you should review and adapt it for your application. 

        AWS WAF supports the pattern syntax used by the PCRE library `libpcre` with some exceptions. The library is documented at [PCRE - Perl Compatible Regular Expressions](http://www.pcre.org/). For information about AWS WAF support, see [Supported regular expression syntax in AWS WAF](waf-regex-pattern-support.md).

1. Provide any additional configuration that you want for the rule group and save the rule. 
**Note**  
AWS recommends against using a scope-down statement with this managed rule group. The scope-down statement limits the requests that the rule group observes, and so can result in an inaccurate traffic baseline and diminished DDoS event detection. The scope-down statement option is available for all of the managed rule group statements, but should not be used for this one. For information about scope-down statements, see [Using scope-down statements in AWS WAF](waf-rule-scope-down-statements.md).

1. In the **Set rule priority** page, move the new anti-DDoS managed rule group rule up so that it runs only after any Allow action rules that you have and before any other rules. This gives the rule group the ability to track the most traffic for Anti-DDoS protection. 

1. Save your changes to the protection pack (web ACL). 

Before you deploy your anti-DDoS implementation for production traffic, test and tune it in a staging or testing environment until you are comfortable with the potential impact to your traffic. Then test and tune the rules in count mode with your production traffic before enabling them. See the section that follows for guidance. 

# Testing and deploying Anti-DDoS
Testing and deploying Anti-DDoS

You will want to configure and test AWS WAF Distributed Denial of Service (DDoS) prevention before deploying the feature. This section provides general guidance for configuring and testing, however the specific steps that you choose to follow will depend on your needs, resources, and web requests that you receive. 

This information is in addition to the general information about testing and tuning provided at [Testing and tuning your AWS WAF protections](web-acl-testing.md).

**Note**  
AWS Managed Rules are designed to protect you from common web threats. When used in accordance with the documentation, AWS Managed Rules rule groups add another layer of security for your applications. However, AWS Managed Rules rule groups aren't intended as a replacement for your security responsibilities, which are determined by the AWS resources that you select. Refer to the [Shared Responsibility Model](https://aws.amazon.com/compliance/shared-responsibility-model/) to ensure that your resources in AWS are properly protected. 

**Production traffic risk**  
Test and tune your anti-DDoS implementation in a staging or testing environment until you are comfortable with the potential impact to your traffic. Then test and tune the rules in count mode with your production traffic before enabling them. 

This guidance is intended for users who know generally how to create and manage AWS WAF protection packs (web ACLs), rules, and rule groups. Those topics are covered in prior sections of this guide. 

**To configure and test an AWS WAF Distributed Denial of Service (DDoS) prevention implementation**

Perform these steps first in a test environment, then in production.

1. 

**Add the AWS WAF Distributed Denial of Service (DDoS) prevention managed rule group in count mode**
**Note**  
You are charged additional fees when you use this managed rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

   Add the AWS Managed Rules rule group `AWSManagedRulesAntiDDoSRuleSet` to a new or existing protection pack (web ACL) and configure it so that it doesn't alter the current protection pack (web ACL) behavior. For details about the rules and labels for this rule group, see [AWS WAF Distributed Denial of Service (DDoS) prevention rule group](aws-managed-rule-groups-anti-ddos.md).
   + When you add the managed rule group, edit it and do the following: 
     + In the **Rule group configuration** pane, provide the details needed to perform anti-DDoS activities for your web traffic. For more information, see [Adding the Anti-DDoS managed rule group to your protection pack (web ACL)](waf-anti-ddos-rg-using.md).
     + In the **Rules** pane, open the **Override all rule actions** dropdown and choose **Count**. With this configuration, AWS WAF evaluates requests against all of the rules in the rule group and only counts the matches that result, while still adding labels to requests. For more information, see [Overriding rule actions in a rule group](web-acl-rule-group-settings.md#web-acl-rule-group-rule-action-override).

       With this override, you can monitor the potential impact of the Anti-DDoS managed rules to determine whether you want to make modifications, such as expanding the regex for the URIs that can't handle a silent browser challenge. 
   + Position the rule group so that it's evaluated as early as possible, immediately after any rules that allow traffic. Rules are evaluated in ascending numeric priority order. The console sets the order for you, starting at the top of your rule list. For more information, see [Setting rule priority](web-acl-processing-order.md). 

1. 

**Enable logging and metrics for the protection pack (web ACL)**

   As needed, configure logging, Amazon Security Lake data collection, request sampling, and Amazon CloudWatch metrics for the protection pack (web ACL). You can use these visibility tools to monitor the interaction of the Anti-DDoS managed rule group with your traffic. 
   + For information about configuring and using logging, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md). 
   + For information about Amazon Security Lake, see [What is Amazon Security Lake?](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html) and [Collecting data from AWS services](https://docs.aws.amazon.com/security-lake/latest/userguide/internal-sources.html) in the *Amazon Security Lake user guide*. 
   + For information about Amazon CloudWatch metrics, see [Monitoring with Amazon CloudWatch](monitoring-cloudwatch.md). 
   + For information about web request sampling, see [Viewing a sample of web requests](web-acl-testing-view-sample.md). 

1. 

**Associate the protection pack (web ACL) with a resource**

   If the protection pack (web ACL) isn't already associated with a test resource, associate it. For information, see [Associating or disassociating protection with an AWS resource](web-acl-associating-aws-resource.md).

1. 

**Monitor traffic and Anti-DDoS rule matches**

   Make sure that your normal traffic is flowing and that the Anti-DDoS managed rule group rules are adding labels to matching web requests. You can see the labels in the logs and see the Anti-DDoS and label metrics in the Amazon CloudWatch metrics. In the logs, the rules that you've overridden to count in the rule group show up in the `ruleGroupList` with `action` set to count, and with `overriddenAction` indicating the configured rule action that you overrode. 

1. 

**Customize Anti-DDoS web request handling**

   As needed, add your own rules that explicitly allow or block requests, to change how Anti-DDoS rules would otherwise handle them. 

   For example, you can use Anti-DDoS labels to allow or block requests or to customize request handling. You can add a label match rule after the Anti-DDoS managed rule group to filter labeled requests for the handling that you want to apply. After testing, keep the related Anti-DDoS rules in count mode, and maintain the request handling decisions in your custom rule. 

1. 

**Remove test rules and configure Anti-DDoS settings**

   Review your testing results to determine which Anti-DDoS rules you want to keep in count mode for monitoring only. For any rules you want to run with active protection, disable count mode in the protection pack (web ACL) rule group configuration to allow them to perform their configured actions. Once you've finalized these settings, remove any temporary test label match rules while retaining any custom rules you created for production use. For additional Anti-DDoS configuration considerations, see [Best practices for intelligent threat mitigation in AWS WAF](waf-managed-protections-best-practices.md).

1. 

**Monitor and tune**

   To be sure that web requests are being handled as you want, closely monitor your traffic after you enable the Anti-DDoS functionality that you intend to use. Adjust the behavior as needed with the rules count override on the rule group and with your own rules. 

# Best Practices for Anti-DDoS

+ **Enable protection during normal traffic periods** – This allows the protection to establish baseline traffic patterns before responding to attacks. Add protection when you are not experiencing an attack and allow time for baseline establishment.
+ **Monitor metrics regularly** – Review CloudWatch metrics to understand traffic patterns and protection effectiveness.
+ **Consider proactive mode for critical applications** – While reactive mode is recommended for most use cases, consider using proactive mode for applications that require continuous protection against known threats.
+ **Test in staging environments** – Before enabling protection in production, test and tune settings in a staging environment to understand the impact on legitimate traffic.

# Client application integrations in AWS WAF
Client application integrationsApplication integration renamed to intelligent threat integration

We renamed the existing functionality for client application integrations to intelligent threat integrations, to help distinguish between that and the new CAPTCHA application integration for JavaScript. AWS WAF client application integrations

Use the AWS WAF JavaScript and mobile client APIs to integrate your client applications with the intelligent threat mitigation AWS Managed Rules rule groups for enhanced detection. 

This section explains how to use the intelligent threat integration APIs and JavaScript CAPTCHA integration API with your AWS WAF features. 

Use AWS WAF client application integration APIs to couple client-side protections with your AWS server-side protection pack (web ACL) protections, to help verify that the client applications that send web requests to your protected resources are the intended clients and that your end users are human beings. 

Use the client integrations to manage silent browser challenges and CAPTCHA puzzles, obtain tokens with proof of successful browser and end user responses, and to include these tokens in requests to your protected endpoints. For general information about AWS WAF tokens, see [Token use in AWS WAF intelligent threat mitigation](waf-tokens.md). 

Combine your client integrations with protection pack (web ACL) protections that require valid tokens for access to your resources. You can use rule groups that check and monitor challenge tokens, like the ones listed in the next section, at [Intelligent threat integration and AWS Managed Rules](waf-application-integration-with-AMRs.md), and you can use the CAPTCHA and Challenge rule actions to check, as described in [CAPTCHA and Challenge in AWS WAF](waf-captcha-and-challenge.md). 

AWS WAF provides two levels of integration for JavaScript applications, and one for mobile applications: 
+ **Intelligent threat integration** – Verify the client application and provide AWS token acquisition and management. This is similar to the functionality provided by the AWS WAF Challenge rule action. This functionality fully integrates your client application with the `AWSManagedRulesACFPRuleSet` managed rule group, the `AWSManagedRulesATPRuleSet` managed rule group, and the targeted protection level of the `AWSManagedRulesBotControlRuleSet` managed rule group. 

  The intelligent threat integration APIs use the AWS WAF silent browser challenge to help ensure that login attempts and other calls to your protected resource are only allowed after the client has acquired a valid token. The APIs manage token authorization for your client application sessions and gather information about the client to help determine whether it's being operated by a bot or by a human being. 
**Note**  
This is available for JavaScript and for Android and iOS mobile applications. 
+ **CAPTCHA integration** – Verify end users with customized CAPTCHA puzzle that you manage in your application. This is similar to the functionality provided by the AWS WAF CAPTCHA rule action, but with added control over the puzzle placement and behavior. 

  This integration leverages the JavaScript intelligent threat integration to run silent challenges and provide AWS WAF tokens to the customer's page. 
**Note**  
This is available for JavaScript applications. 

**Topics**
+ [

# Intelligent threat integration and AWS Managed Rules
](waf-application-integration-with-AMRs.md)
+ [

# Accessing the AWS WAF client application integration APIs
](waf-application-integration-location-in-console.md)
+ [

# AWS WAF JavaScript integrations
](waf-javascript-api.md)
+ [

# AWS WAF mobile application integration
](waf-mobile-sdk.md)

# Intelligent threat integration and AWS Managed Rules
Intelligent threat integration and AWS Managed Rules

This section explains how the intelligent threat integration APIs work with the AWS Managed Rules rule groups.

The intelligent threat integration APIs work with protection packs (web ACLs) that use the intelligent threat rule groups to enable the full functionality of these advanced managed rule groups. 
+ AWS WAF Fraud Control account creation fraud prevention (ACFP) managed rule group `AWSManagedRulesACFPRuleSet`. 

  Account creation fraud is an online illegal activity in which an attacker creates invalid accounts in your application for purposes such as receiving sign-up bonuses or impersonating someone. The ACFP managed rule group provides rules to block, label, and manage requests that might be part of fraudulent account creation attempts. The APIs enable fine-tuned client browser verification and human interactivity information that the ACFP rules use to separate valid client traffic from malicious traffic.

  For more information, see [AWS WAF Fraud Control account creation fraud prevention (ACFP) rule group](aws-managed-rule-groups-acfp.md) and [AWS WAF Fraud Control account creation fraud prevention (ACFP)](waf-acfp.md).
+ AWS WAF Fraud Control account takeover prevention (ATP) managed rule group `AWSManagedRulesATPRuleSet`. 

  Account takeover is an online illegal activity in which an attacker gains unauthorized access to a person's account. The ATP managed rule group provides rules to block, label, and manage requests that might be part of malicious account takeover attempts. The APIs enable fine-tuned client verification and behavior aggregation that the ATP rules use to separate valid client traffic from malicious traffic.

  For more information, see [AWS WAF Fraud Control account takeover prevention (ATP) rule group](aws-managed-rule-groups-atp.md) and [AWS WAF Fraud Control account takeover prevention (ATP)](waf-atp.md).
+ Targeted protection level of the AWS WAF Bot Control managed rule group `AWSManagedRulesBotControlRuleSet`. 

  Bots run from self-identifying and useful ones, such as most search engines and crawlers, to malicious bots that operate against your website and don't self-identify. The Bot Control managed rule group provides rules to monitor, label, and manage the bot activity in your web traffic. When you use the targeted protection level of this rule group, the targeted rules use the client session information that the APIs provide to better detect malicious bots. 

  For more information, see [AWS WAF Bot Control rule group](aws-managed-rule-groups-bot.md) and [AWS WAF Bot Control](waf-bot-control.md).

To add one of these managed rule groups to your protection pack (web ACL), see the procedures [Adding the ACFP managed rule group to your web ACL](waf-acfp-rg-using.md), [Adding the ATP managed rule group to your protection pack (web ACL)](waf-atp-rg-using.md), and [Adding the AWS WAF Bot Control managed rule group to your web ACL](waf-bot-control-rg-using.md).

**Note**  
The managed rule groups currently don't block requests that are missing tokens. In order to block requests that are missing tokens, after you implement your application integration APIs, follow the guidance at [Blocking requests that don't have a valid AWS WAF token](waf-tokens-block-missing-tokens.md). 

# Accessing the AWS WAF client application integration APIs
Accessing the integration APIs

This section explains where to find the application integration APIs in the AWS WAF console.

The JavaScript integration APIs are generally available, and you can use them for your browsers and other devices that execute JavaScript. 

AWS WAF offers custom intelligent threat integration SDKs for Android and iOS mobile apps. 
+ For Android mobile and TV apps, the SDKs work for Android API version 23 (Android version 6) and later. For information about Android versions, see [SDK Platform release notes](https://developer.android.com/tools/releases/platforms).
+ For iOS mobile apps, the SDKs work for iOS version 13 and later. For information about iOS versions, see [iOS & iPadOS Release Notes](https://developer.apple.com/documentation/ios-ipados-release-notes).
+ For Apple TV apps, the SDKs work for tvOS version 14 or later. For information about tvOS versions, see [tvOS Release Notes](https://developer.apple.com/documentation/tvos-release-notes).

**To access the integration APIs through the console**

1. Sign in to the AWS Management Console and open the AWS WAF console at [https://console.aws.amazon.com/wafv2/homev2](https://console.aws.amazon.com/wafv2/homev2). 

1. Choose **Application integration** in the navigation pane, and then choose the tab you're interested in.
   + **Intelligent threat integration** is available for JavaScript and mobile applications. 

     The tab contains the following:
     + A list of the protection packs (web ACLs) that are enabled for intelligent threat application integration. The list includes each protection pack (web ACL) that uses the `AWSManagedRulesACFPRuleSet` managed rule group, the `AWSManagedRulesATPRuleSet` managed rule group, or the targeted protection level of the `AWSManagedRulesBotControlRuleSet` managed rule group. When you implement the intelligent threat APIs, you use the integration URL for the protection pack (web ACL) that you want to integrate with.
     + The APIs that you have access to. The JavaScript APIs are always available. For access to the mobile SDKs, contact support at [Contact AWS](https://aws.amazon.com/contact-us).
   + **CAPTCHA integration** is available for JavaScript applications. 

     The tab contains the following: 
     + The integration URL for use in your integration. 
     + The API keys that you've created for your client application domains. Your use of the CAPTCHA API requires an encrypted API key that gives clients the right to access AWS WAF CAPTCHA from their domains. For each client that you integrate with, use an API key that contains the client's domain. For more information these requirements and about managing these keys, see [Managing API keys for the JS CAPTCHA API](waf-js-captcha-api-key.md).

# AWS WAF JavaScript integrations
JavaScript integrations

This section explains how to use the AWS WAF JavaScript integrations.

You can use the JavaScript integration APIs to implement AWS WAF application integrations in your browsers and other devices that execute JavaScript. 

CAPTCHA puzzles and silent challenges can only run when browsers are accessing HTTPS endpoints. Browser clients must be running in secure contexts in order to acquire tokens. 
+ The intelligent threat APIs let you manage token authorization through a silent client-side browser challenge, and to include the tokens in the requests that you send to your protected resources. 
+ The CAPTCHA integration API adds to the intelligent threat APIs, and lets you customize the placement and characteristics of the CAPTCHA puzzle in your client applications. This API leverages the intelligent threat APIs to acquire AWS WAF tokens for use in the page after the end user successfully completes the CAPTCHA puzzle. 

By using these integrations, you ensure that the remote procedure calls by your client contain a valid token. When these integration APIs are in place on your application's pages, you can implement mitigating rules in your protection pack (web ACL), such as blocking requests that don't contain a valid token. You can also implement rules that enforce the use of the tokens that your client applications obtain, by using the Challenge or CAPTCHA actions in your rules. 

**Example implementation of intelligent threat APIs**  
The following listing shows basic components of a typical implementation of the intelligent threat APIs in a web application page. 

```
<head>
<script type="text/javascript" src="protection pack (web ACL) integration URL/challenge.js" defer></script>
</head>
<script>
const login_response = await AwsWafIntegration.fetch(login_url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: login_body
  });
</script>
```

**Example implementation of CAPTCHA JavaScript API**  
The CAPTCHA integration API lets you customize your end users' CAPTCHA puzzle experience. The CAPTCHA integration leverages the JavaScript intelligent threat integration, for browser verification and token management, and adds a function for configuring and rendering the CAPTCHA puzzle. 

The following listing shows basic components of a typical implementation of the CAPTCHA JavaScript API in a web application page. 

```
<head>
    <script type="text/javascript" src="<Integration URL>/jsapi.js" defer></script>
</head>

<script type="text/javascript">
    function showMyCaptcha() {
        var container = document.querySelector("#my-captcha-container");
        
        AwsWafCaptcha.renderCaptcha(container, {
            apiKey: "...API key goes here...",
            onSuccess: captchaExampleSuccessFunction,
            onError: captchaExampleErrorFunction,
            ...other configuration parameters as needed...
        });
    }
    
    function captchaExampleSuccessFunction(wafToken) {
        // Use WAF token to access protected resources
        AwsWafIntegration.fetch("...WAF-protected URL...", {
            method: "POST",
            ...
        });
    }
    
    function captchaExampleErrorFunction(error) {
        /* Do something with the error */
    }
</script>

<div id="my-captcha-container">
    <!-- The contents of this container will be replaced by the captcha widget -->
</div>
```

**Topics**
+ [

# Providing domains for use in the tokens
](waf-js-challenge-api-set-token-domain.md)
+ [

# Using the JavaScript API with content security policies
](waf-javascript-api-csp.md)
+ [

# Using the intelligent threat JavaScript API
](waf-js-challenge-api.md)
+ [

# Using the CAPTCHA JavaScript API
](waf-js-captcha-api.md)

# Providing domains for use in the tokens
Providing domains for use in the tokens

This section explains how to provide additional domains for tokens.

By default, when AWS WAF creates a token, it uses the host domain of the resource that’s associated with the protection pack (web ACL). You can provide additional domains for the tokens that AWS WAF creates for the JavaScript APIs. To do this, configure the global variable `window.awsWafCookieDomainList`, with one or more token domains. 

When AWS WAF creates a token, it uses the most appropriate, shortest domain from among the combination of the domains in `window.awsWafCookieDomainList` and the host domain of the resource that’s associated with the protection pack (web ACL). 

Example settings: 

```
window.awsWafCookieDomainList = ['.aws.amazon.com']
```

```
window.awsWafCookieDomainList = ['.aws.amazon.com', 'abc.aws.amazon.com']
```

You can't use public suffixes in this list. For example, you can't use `gov.au` or `co.uk` as token domains in the list.

The domains that you specify in this list must be compatible with your other domains and domain configurations: 
+ The domains must be ones that AWS WAF will accept, based on the protected host domain and the token domain list that's configured for the protection pack (web ACL). For more information, see [AWS WAF protection pack (web ACL) token domain list configuration](waf-tokens-domains.md#waf-tokens-domain-lists). 
+ If you use the JavaScript CAPTCHA API, at least one domain in your CAPTCHA API key must be an exact match for one of the token domains in `window.awsWafCookieDomainList` or it must be the apex domain of one of those token domains. 

  For example, for the token domain `mySubdomain.myApex.com`, the API key `mySubdomain.myApex.com` is an exact match and the API key `myApex.com` is the apex domain. Either key matches the token domain. 

  For more information about the API keys, see [Managing API keys for the JS CAPTCHA API](waf-js-captcha-api-key.md). 

If you use the `AWSManagedRulesACFPRuleSet` managed rule group, you might configure a domain that matches the one in the account creation path that you provided to the rule group configuration. For more information about this configuration, see [Adding the ACFP managed rule group to your web ACL](waf-acfp-rg-using.md).

If you use the `AWSManagedRulesATPRuleSet` managed rule group, you might configure a domain that matches the one in the login path that you provided to the rule group configuration. For more information about this configuration, see [Adding the ATP managed rule group to your protection pack (web ACL)](waf-atp-rg-using.md).

# Using the JavaScript API with content security policies
Content security policies

This section provides an example configuration to allowlist the AWS WAF apex domain.

If you apply content security policies (CSP) to your resources, for your JavaScript implementation to work, you need to allowlist the AWS WAF apex domain `awswaf.com`. The JavaScript SDKs make calls to different AWS WAF endpoints, so allowlisting this domain provides the permissions that the SDKs need to operate.

The following shows an example configuration to allowlist the AWS WAF apex domain: 

```
connect-src 'self' https://*.awswaf.com;
script-src 'self' https://*.awswaf.com;
script-src-elem 'self' https://*.awswaf.com;
```

If you try to use the JavaScript SDKs with resources that use CSP, and you haven't allowlisted the AWS WAF domain, you'll receive errors like the following: 

```
Refused to load the script ...awswaf.com/<> because it violates the following Content Security Policy directive: “script-src ‘self’
```

# Using the intelligent threat JavaScript API
Using the intelligent threat API

This section provides instructions for using the intelligent threat JavaScript API in your client application.

The intelligent threat APIs provide operations for running silent challenges against the user's browser, and for handling the AWS WAF tokens that provide proof of successful challenge and CAPTCHA responses. 

Implement the JavaScript integration first in a test environment, then in production. For additional coding guidance, see the sections that follow. 

 

**To use the intelligent threat APIs**

1. **Install the APIs** 

   If you use the CAPTCHA API, you can skip this step. When you install the CAPTCHA API, the script automatically installs the intelligent threat APIs.

   1. Sign in to the AWS Management Console and open the AWS WAF console at [https://console.aws.amazon.com/wafv2/homev2](https://console.aws.amazon.com/wafv2/homev2). 

   1. In the navigation pane, choose **Application integration**. On the **Application integration** page, you can see tabbed options. 

   1. Select **Intelligent threat integration**

   1. In the tab, select the protection pack (web ACL) that you want to integrate with. The protection pack (web ACL) list includes only protection packs (web ACLs) that use the `AWSManagedRulesACFPRuleSet` managed rule group, the `AWSManagedRulesATPRuleSet` managed rule group, or the targeted protection level of the `AWSManagedRulesBotControlRuleSet` managed rule group. 

   1. Open the **JavaScript SDK** pane, and copy the script tag for use in your integration. 

   1. In your application page code, in the `<head>` section, insert the script tag that you copied for the protection pack (web ACL). This inclusion causes your client application to automatically retrieve a token in the background on page load. 

      ```
      <head>
          <script type="text/javascript" src="protection pack (web ACL) integration URL/challenge.js” defer></script>
      <head>
      ```

      This `<script>` listing is configured with the `defer` attribute, but you can change the setting to `async` if you want a different behavior for your page. 

1. **(Optional) Add domain configuration for the client's tokens** – By default, when AWS WAF creates a token, it uses the host domain of the resource that’s associated with the protection pack (web ACL). To provide additional domains for the JavaScript APIs, follow the guidance at [Providing domains for use in the tokens](waf-js-challenge-api-set-token-domain.md). 

1. **Code your intelligent threat integration** – Write your code to ensure that token retrieval completes before the client sends its requests to your protected endpoints. If you are already using the `fetch` API to make your call, you can substitute the AWS WAF integration `fetch` wrapper. If you don't use the `fetch` API, you can use the AWS WAF integration `getToken` operation instead. For coding guidance, see the following sections. 

1. **Add token verification in your protection pack (web ACL)** – Add at least one rule to your protection pack (web ACL) that checks for a valid challenge token in the web requests that your client sends. You can use rule groups that check and monitor challenge tokens, like the targeted level of the Bot Control managed rule group, and you can use the Challenge rule action to check, as described in [CAPTCHA and Challenge in AWS WAF](waf-captcha-and-challenge.md). 

   The protection pack (web ACL) additions verify that requests to your protected endpoints include the token that you've acquired in your client integration. Requests that include a valid, unexpired token pass the Challenge inspection and do not send another silent challenge to your client. 

1. **(Optional) Block requests that are missing tokens** – If you use the APIs with the ACFP managed rule group, the ATP managed rule group, or the targeted rules of the Bot Control rule group, these rules don't block requests that are missing tokens. To block requests that are missing tokens, follow the guidance at [Blocking requests that don't have a valid AWS WAF token](waf-tokens-block-missing-tokens.md). 

**Topics**
+ [

# Intelligent threat API specification
](waf-js-challenge-api-specification.md)
+ [

# How to use the integration `fetch` wrapper
](waf-js-challenge-api-fetch-wrapper.md)
+ [

# How to use the integration `getToken`
](waf-js-challenge-api-get-token.md)

# Intelligent threat API specification
Intelligent threat API specification

This section lists the specification for the methods and properties of the intelligent threat mitigation JavaScript APIs. Use these APIs for intelligent threat and CAPTCHA integrations.

**`AwsWafIntegration.fetch()`**  
Sends the HTTP `fetch` request to the server using the AWS WAF integration implementation. 

**`AwsWafIntegration.getToken()`**  
Retrieves the stored AWS WAF token and stores it in a cookie on the current page with name `aws-waf-token`, and the value set to the token value. 

**`AwsWafIntegration.hasToken()`**  
Returns a boolean indicating whether the `aws-waf-token` cookie currently holds an unexpired token. 

If you're also using the CAPTCHA integration, see the specification for that at [CAPTCHA JavaScript API specification](waf-js-captcha-api-specification.md).

# How to use the integration `fetch` wrapper
How to use the `fetch` wrapper

This section provides instructions for using the integration `fetch` wrapper.

You can use the AWS WAF `fetch` wrapper by changing your normal `fetch` calls to the `fetch` API under the `AwsWafIntegration` namespace. The AWS WAF wrapper supports all of the same options as the standard JavaScript `fetch` API call and adds the token handling for the integration. This approach is generally the simplest way to integrate your application. 

**Before the wrapper implementation**  
The following example listing shows standard code before implementing the `AwsWafIntegration` `fetch` wrapper.

```
const login_response = await fetch(login_url, {
	    method: 'POST',
	    headers: {
	      'Content-Type': 'application/json'
	    },
	    body: login_body
	  });
```

**After the wrapper implementation**  
The following listing shows the same code with the `AwsWafIntegration` `fetch` wrapper implementation.

```
const login_response = await AwsWafIntegration.fetch(login_url, {
	    method: 'POST',
	    headers: {
	      'Content-Type': 'application/json'
	    },
	    body: login_body
	  });
```

# How to use the integration `getToken`
How to use `getToken`

This section explains how to use the `getToken` operation.

AWS WAF requires your requests to protected endpoints to include the cookie named `aws-waf-token` with the value of your current token. 

The `getToken` operation is an asynchronous API call that retrieves the AWS WAF token and stores it in a cookie on the current page with name `aws-waf-token`, and the value set to the token value. You can use this token cookie as needed in your page. 

When you call `getToken`, it does the following: 
+ If an unexpired token is already available, the call returns it immediately.
+ Otherwise, the call retrieves a new token from the token provider, waiting for up to 2 seconds for the token acquisition workflow to complete before timing out. If the operation times out, it throws an error, which your calling code must handle. 

The `getToken` operation has an accompanying `hasToken` operation, which indicates whether the `aws-waf-token` cookie currently holds an unexpired token. 

`AwsWafIntegration.getToken()` retrieves a valid token and stores it as a cookie. Most client calls automatically attach this cookie, but some don't. For example, calls made across host domains don't attach the cookie. In the implementation details that follow, we show how to work with both types of client calls. 

**Basic `getToken` implementation, for calls that attach the `aws-waf-token` cookie**  
The following example listing shows standard code for implementing the `getToken` operation with a login request.

```
const login_response = await AwsWafIntegration.getToken()
	    .catch(e => {
	        // Implement error handling logic for your use case
	    })
	    // The getToken call returns the token, and doesn't typically require special handling
	    .then(token => {
	        return loginToMyPage()
	    })
	
	async function loginToMyPage() {
	    // Your existing login code
	}
```

**Submit form only after token is available from `getToken`**  
The following listing shows how to register an event listener to intercept form submissions until a valid token is available for use. 

```
<body>
	  <h1>Login</h1>
	  <p></p>
	  <form id="login-form" action="/web/login" method="POST" enctype="application/x-www-form-urlencoded">
	    <label for="input_username">USERNAME</label>
	    <input type="text" name="input_username" id="input_username"><br>
	    <label for="input_password">PASSWORD</label>
	    <input type="password" name="input_password" id="input_password"><br>
	    <button type="submit">Submit<button>
	  </form>
	
	<script>
	  const form = document.querySelector("#login-form");
	
	  // Register an event listener to intercept form submissions
	  form.addEventListener("submit", (e) => {
	      // Submit the form only after a token is available 
	      if (!AwsWafIntegration.hasToken()) {
	          e.preventDefault();
	          AwsWafIntegration.getToken().then(() => {
	              e.target.submit();
	          }, (reason) => { console.log("Error:"+reason) });
	        }
	    });
	</script>
	</body>
```

**Attaching the token when your client doesn't attach the `aws-waf-token` cookie by default**  
`AwsWafIntegration.getToken()` retrieves a valid token and stores it as a cookie, but not all client calls attach this cookie by default. For example, calls made across host domains don't attach the cookie. 

The `fetch` wrapper handles these cases automatically, but if you aren't able to use the `fetch` wrapper, you can handle this by using a custom `x-aws-waf-token` header. AWS WAF reads tokens from this header, in addition to reading them from the `aws-waf-token` cookie. The following code shows an example of setting the header. 

```
const token = await AwsWafIntegration.getToken();
const result = await fetch('/url', {
    headers: {
        'x-aws-waf-token': token,
    },
});
```

By default, AWS WAF only accepts tokens that contain the same domain as the requested host domain. Any cross-domain tokens require corresponding entries in the protection pack (web ACL) token domain list. For more information, see [AWS WAF protection pack (web ACL) token domain list configuration](waf-tokens-domains.md#waf-tokens-domain-lists). 

For additional information about cross-domain token use, see [aws-samples/aws-waf-bot-control-api-protection-with-captcha](https://github.com/aws-samples/aws-waf-bot-control-api-protection-with-captcha).

# Using the CAPTCHA JavaScript API
Using the CAPTCHA JavaScript APINew JavaScript client application integration for CAPTCHA

You can now customize the placement and characteristics of the CAPTCHA puzzle in your JavaScript client applications. 

This section provides instructions for using the CAPTCHA integration API.

The CAPTCHA JavaScript API allows you to configure the CAPTCHA puzzle and place it where you want in your client application. This API leverages the features of the intelligent threat JavaScript APIs to acquire and use AWS WAF tokens after an end user successfully completes a CAPTCHA puzzle. 

Implement the JavaScript integration first in a test environment, then in production. For additional coding guidance, see the sections that follow. 

**To use the CAPTCHA integration API**

1. **Install the API**

   1. Sign in to the AWS Management Console and open the AWS WAF console at [https://console.aws.amazon.com/wafv2/homev2](https://console.aws.amazon.com/wafv2/homev2). 

   1. In the navigation pane, choose **Application integration**. On the **Application integration** page, you can see tabbed options. 

   1. Select **CAPTCHA integration**.

   1. Copy the listed JavaScript integration script tag for use in your integration.

   1. In your application page code, in the `<head>` section, insert the script tag that you copied. This inclusion makes the CAPTCHA puzzle available for configuration and use. 

      ```
      <head>
          <script type="text/javascript" src="integrationURL/jsapi.js" defer></script>
      </head>
      ```

      This `<script>` listing is configured with the `defer` attribute, but you can change the setting to `async` if you want a different behavior for your page. 

      The CAPTCHA script also automatically loads the intelligent threat integration script if it isn't already present. The intelligent threat integration script causes your client application to automatically retrieve a token in the background on page load, and provides other token management functionality that you need for your use of the CAPTCHA API. 

1. **(Optional) Add domain configuration for the client's tokens** – By default, when AWS WAF creates a token, it uses the host domain of the resource that’s associated with the protection pack (web ACL). To provide additional domains for the JavaScript APIs, follow the guidance at [Providing domains for use in the tokens](waf-js-challenge-api-set-token-domain.md). 

1. **Get the encrypted API key for the client** – The CAPTCHA API requires an encrypted API key that contains a list of valid client domains. AWS WAF uses this key to verify that the client domain you're using with the integration is approved to use AWS WAF CAPTCHA. To generate your API key, follow the guidance at [Managing API keys for the JS CAPTCHA API](waf-js-captcha-api-key.md).

1. **Code your CAPTCHA widget implementation** – Implement the `renderCaptcha()` API call in your page, at the location where you want to use it. For information about configuring and using this function, see the following sections, [CAPTCHA JavaScript API specification](waf-js-captcha-api-specification.md) and [How to render the CAPTCHA puzzle](waf-js-captcha-api-render.md). 

   The CAPTCHA implementation integrates with the intelligent threat integration APIs for token management and to run fetch calls that use the AWS WAF tokens. For guidance about using these APIs, see [Using the intelligent threat JavaScript API](waf-js-challenge-api.md).

1. **Add token verification in your protection pack (web ACL)** – Add at least one rule to your protection pack (web ACL) that checks for a valid CAPTCHA token in the web requests that your client sends. You can use the CAPTCHA rule action to check, as described in [CAPTCHA and Challenge in AWS WAF](waf-captcha-and-challenge.md). 

   The protection pack (web ACL) additions verify that requests going to your protected endpoints include the token that you've acquired in your client integration. Requests that include a valid, unexpired CAPTCHA token pass the CAPTCHA rule action inspection and do not present your end user with another CAPTCHA puzzle. 

After you've implemented the JavaScript API, you can review the CloudWatch metrics for CAPTCHA puzzle attempts and solutions. For metrics and dimension details, see [Account metrics and dimensions](waf-metrics.md#waf-metrics-account).

**Topics**
+ [

# CAPTCHA JavaScript API specification
](waf-js-captcha-api-specification.md)
+ [

# How to render the CAPTCHA puzzle
](waf-js-captcha-api-render.md)
+ [

# Handling a CAPTCHA response from AWS WAF
](waf-js-captcha-api-conditional.md)
+ [

# Managing API keys for the JS CAPTCHA API
](waf-js-captcha-api-key.md)

# CAPTCHA JavaScript API specification
CAPTCHA JavaScript API specification

This section lists the specification for the methods and properties of the CAPTCHA JavaScript APIs. Use the CAPTCHA JavaScript APIs to run custom CAPTCHA puzzles in your client applications. 

This API builds on the intelligent threat APIs, which you use to configure and manage AWS WAF token acquisition and use. See [Intelligent threat API specification](waf-js-challenge-api-specification.md). .

**`AwsWafCaptcha.renderCaptcha(container, configuration)`**  
Presents an AWS WAF CAPTCHA puzzle to the end user and, upon success, updates the client token with the CAPTCHA validation. This is available only with the CAPTCHA integration. Use this call along with the intelligent threat APIs to manage token retrieval and to provide the token in your `fetch` calls. See the intelligent threat APIs at [Intelligent threat API specification](waf-js-challenge-api-specification.md).  
Unlike the CAPTCHA interstitial that AWS WAF sends, the CAPTCHA puzzle rendered by this method displays the puzzle immediately, without an initial title screen.     
**`container`**  
The `Element` object for the target container element on the page. This is commonly retrieved by calling `document.getElementById()` or `document.querySelector()`.  
Required: Yes  
Type: `Element`  
**configuration**  
An object containing CAPTCHA configuration settings, as follows****:    
**`apiKey`**   
The encrypted API key that enables permissions for the client's domain. Use the AWS WAF console to generate your API keys for your client domains. You can use one key for up to five domains. For information, see [Managing API keys for the JS CAPTCHA API](waf-js-captcha-api-key.md).   
Required: Yes  
Type: `string`  
**`onSuccess: (wafToken: string) => void;`**   
Called with a valid AWS WAF token when the end user successfully completes a CAPTCHA puzzle. Use the token in the requests that you send to the endpoints that you protect with an AWS WAF protection pack (web ACL). The token provides proof and the timestamp of the latest successful puzzle completion.   
Required: Yes  
**`onError?: (error: CaptchaError) => void;`**   
Called with an error object when an error occurs during the CAPTCHA operation.   
Required: No  
**`CaptchaError` class definition** – The `onError` handler supplies an error type with the following class definition.   

```
CaptchaError extends Error {
    kind: "internal_error" | "network_error" | "token_error" | "client_error";
    statusCode?: number;
}
```
+ `kind` – The kind of error returned. 
+ `statusCode` – The HTTP status code, if available. This is used by `network_error` if the error is due to an HTTP error.  
**`onLoad?: () => void;`**   
Called when a new CAPTCHA puzzle loads.  
Required: No  
**`onPuzzleTimeout?: () => void;`**   
Called when a CAPTCHA puzzle isn't completed before it expires.  
Required: No  
**`onPuzzleCorrect?: () => void;`**   
Called when a correct answer is provided to a CAPTCHA puzzle.  
Required: No  
**`onPuzzleIncorrect?: () => void;`**   
Called when an incorrect answer is provided to a CAPTCHA puzzle.  
Required: No  
**`defaultLocale`**   
The default locale to use for the CAPTCHA puzzle. The written instructions for CAPTCHA puzzles are available in Arabic (ar-SA), simplified Chinese (zh-CN), Dutch (nl-NL), English (en-US), French (fr-FR), German (de-DE), Italian (it-IT), Japanese (ja-JP), Brazilian Portuguese (pt-BR), Spanish (es-ES), and Turkish (tr-TR). Audio instructions are available for all of the written languages except Chinese and Japanese, which default to English. To change the default language, provide the international language and locale code, for example, `ar-SA`.  
Default: The language currently in use in the end user's browser  
Required: No  
Type: `string`  
**`disableLanguageSelector`**   
If set to `true`, the CAPTCHA puzzle hides the language selector.   
Default: `false`  
Required: No  
Type: `boolean`  
**`dynamicWidth`**   
If set to `true`, the CAPTCHA puzzle changes width for compatibility with the browser window width.   
Default: `false`  
Required: No  
Type: `boolean`  
**`skipTitle`**   
If set to `true`, the CAPTCHA puzzle doesn't display the puzzle title heading **Solve the puzzle**.   
Default: `false`  
Required: No  
Type: `boolean`

# How to render the CAPTCHA puzzle
How to render the CAPTCHA puzzle

This section provides an example `renderCaptcha` implementation.

You can use the AWS WAF `renderCaptcha` call where you want to in your client interface. The call retrieves a CAPTCHA puzzle from AWS WAF, renders it, and sends the results to AWS WAF for verification. When you make the call, you provide the puzzle rendering configuration and the callbacks that you want to run when your end users complete the puzzle. For details about the options, see the preceding section, [CAPTCHA JavaScript API specification](waf-js-captcha-api-specification.md).

Use this call in conjunction with the token management functionality of the intelligent threat integration APIs. This call gives your client a token that verifies the successful completion of the CAPTCHA puzzle. Use the intelligent threat integration APIs to manage the token and to provide the token in your client's calls to the endpoints that are protected with AWS WAF protection packs (web ACLs). For information about the intelligent threat APIs, see [Using the intelligent threat JavaScript API](waf-js-challenge-api.md).

**Example implementation**  
The following example listing shows a standard CAPTCHA implementation, including the placement of the AWS WAF integration URL in the `<head>` section. 

This listing configures the `renderCaptcha` function with a success callback that uses the `AwsWafIntegration.fetch` wrapper of the intelligent threat integration APIs. For information about this function, see [How to use the integration `fetch` wrapper](waf-js-challenge-api-fetch-wrapper.md).

```
<head>
    <script type="text/javascript" src="<Integration URL>/jsapi.js" defer></script>
</head>

<script type="text/javascript">
    function showMyCaptcha() {
        var container = document.querySelector("#my-captcha-container");
        
        AwsWafCaptcha.renderCaptcha(container, {
            apiKey: "...API key goes here...",
            onSuccess: captchaExampleSuccessFunction,
            onError: captchaExampleErrorFunction,
            ...other configuration parameters as needed...
        });
    }
    
    function captchaExampleSuccessFunction(wafToken) {
        // Captcha completed. wafToken contains a valid WAF token. Store it for
        // use later or call AwsWafIntegration.fetch() to use it easily.
        // It will expire after a time, so calling AwsWafIntegration.getToken()
        // again is advised if the token is needed later on, outside of using the
        // fetch wrapper.
        
        // Use WAF token to access protected resources
        AwsWafIntegration.fetch("...WAF-protected URL...", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: "{ ... }" /* body content */
        });
    }
    
    function captchaExampleErrorFunction(error) {
        /* Do something with the error */
    }
</script>

<div id="my-captcha-container">
    <!-- The contents of this container will be replaced by the captcha widget -->
</div>
```

**Example configuration settings**  
The following example listing shows the `renderCaptcha` with non-default settings for the width and the title options. 

```
        AwsWafCaptcha.renderCaptcha(container, {
            apiKey: "...API key goes here...",
            onSuccess: captchaExampleSuccessFunction,
            onError: captchaExampleErrorFunction,
            dynamicWidth: true, 
            skipTitle: true
        });
```

For full information about the configuration options, see [CAPTCHA JavaScript API specification](waf-js-captcha-api-specification.md).

# Handling a CAPTCHA response from AWS WAF
Handling a CAPTCHA response from AWS WAFNew information for the CAPTCHA JavaScript API

New section describes how to serve a custom CAPTCHA puzzle when AWS WAF responds to a request with a CAPTCHA. 

This section provides an example of handling a CAPTCHA response.

An AWS WAF rule with a CAPTCHA action terminates the evaluation of a matching web request if the request doesn't have a token with a valid CAPTCHA timestamp. If the request is a `GET` text/html call, the CAPTCHA action then serves the client an interstitial with a CAPTCHA puzzle. When you don't integrate the CAPTCHA JavaScript API, the interstitial runs the puzzle and, if the end user successfully solves it, automatically resubmits the request. 

When you integrate the CAPTCHA JavaScript API and customize your CAPTCHA handling, you need to detect the terminating CAPTCHA response, serve your custom CAPTCHA, and then if the end user successfully solves the puzzle, resubmit the client's web request. 

The following code example shows how to do this. 

**Note**  
The AWS WAF CAPTCHA action response has a status code of HTTP 405, which we use to recognize the CAPTCHA response in this code. If your protected endpoint uses an HTTP 405 status code to communicate any other type of response for the same call, this example code will render a CAPTCHA puzzle for those responses as well. 

```
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="<Integration URL>/jsapi.js" defer></script>
</head>
<body>
    <div id="my-captcha-box"></div>
    <div id="my-output-box"></div>

    <script type="text/javascript">
    async function loadData() {
        // Attempt to fetch a resource that's configured to trigger a CAPTCHA
        // action if the rule matches. The CAPTCHA response has status=HTTP 405.
        const result = await AwsWafIntegration.fetch("/protected-resource");

        // If the action was CAPTCHA, render the CAPTCHA and return

        // NOTE: If the endpoint you're calling in the fetch call responds with HTTP 405
        // as an expected response status code, then this check won't be able to tell the
        // difference between that and the CAPTCHA rule action response.

        if (result.status === 405) {
            const container = document.querySelector("#my-captcha-box");
            AwsWafCaptcha.renderCaptcha(container, {
                apiKey: "...API key goes here...",
                onSuccess() {
                    // Try loading again, now that there is a valid CAPTCHA token
                    loadData();
                },
            });
            return;
        }

        const container = document.querySelector("#my-output-box");
        const response = await result.text();
        container.innerHTML = response;
    }

    window.addEventListener("load", () => {
        loadData();
    });
    </script>
</body>
</html>
```

# Managing API keys for the JS CAPTCHA API
Managing JS CAPTCHA API keysJavaScript CAPTCHA API key management

You can now delete CAPTCHA JS API keys through the AWS WAF APIs.

This section provides instructions for generating and deleting API keys.

To integrate AWS WAF CAPTCHA into a a client application with the JavaScript API, you need the JavaScript API integration tag and the encrypted API key for the client domain where you want to run your CAPTCHA puzzle. 

The CAPTCHA application integration for JavaScript uses the encrypted API keys to verify that the client application domain has permission to use the AWS WAF CAPTCHA API. When you call the CAPTCHA API from your JavaScript client, you provide an API key with a domain list that includes a domain for the current client. You can list up to 5 domains in a single encrypted key. 

**API key requirements**  
The API key that you use in your CAPTCHA integration must contain a domain that applies to the client where you use the key. 
+ If you specify a `window.awsWafCookieDomainList` in your client's intelligent threat integration, then at least one domain in your API key must be an exact match for one of the token domains in `window.awsWafCookieDomainList` or it must be the apex domain of one of those token domains. 

  For example, for the token domain `mySubdomain.myApex.com`, the API key `mySubdomain.myApex.com` is an exact match and the API key `myApex.com` is the apex domain. Either key matches the token domain. 

  For information about the setting the token domain list, see [Providing domains for use in the tokens](waf-js-challenge-api-set-token-domain.md).
+ Otherwise, the current domain must be contained in the API key. The current domain is the domain that you can see in the browser address bar. 

The domains that you use must be ones that AWS WAF will accept, based on the protected host domain and the token domain list that's configured for the web ACL. For more information, see [AWS WAF protection pack (web ACL) token domain list configuration](waf-tokens-domains.md#waf-tokens-domain-lists).

**How to choose the Region for your API key**  
AWS WAF can generate CAPTCHA API keys in any Region where AWS WAF is available. 

As a general rule, you should use the same Region for your CAPTCHA API key as you use for your protection pack (web ACL). If you expect a global audience for a regional protection pack (web ACL), however, you can obtain a CAPTCHA JavaScript integration tag that's scoped to CloudFront and an API key that's scoped to CloudFront, and use them with a regional protection pack (web ACL). This approach allows clients to load a CAPTCHA puzzle from the Region that's closest to them, which reduces latency. 

CAPTCHA API keys that are scoped to Regions other than CloudFront are not supported for use across multiple Regions. They can only be used in the Region they are scoped to. 

**To generate an API key for your client domains**  
To obtain the integration URL and generate and retrieve the API keys through the console. 

1. Sign in to the AWS Management Console and open the AWS WAF console at [https://console.aws.amazon.com/wafv2/homev2](https://console.aws.amazon.com/wafv2/homev2). 

1. In the navigation pane, choose **Application integration**. 

1. In the pane, **protection packs (web ACLs) that are enabled for application integration**, select the Region that you want to use for your API key. You can also select the Region in the **API keys** pane of the **CAPTCHA integration** tab.

1. Choose the tab **CAPTCHA integration**. This tab provides the CAPTCHA JavaScript integration tag, which you can use in your integration, and the API keys listing. Both are scoped to the selected Region.

1. In the **API keys** pane, choose **Generate key**. The key generation dialogue appears. 

1. Enter the client domains that you want to include in the key. You can enter up to 5. When you're finished, choose **Generate key**. The interface returns to the CAPTCHA integration tab, where your new key is listed. 

   Once created, an API key is immutable. If you need to make changes to a key, generate a new key and use that instead. 

1. (Optional) Copy the newly generated key for use in your integration. 

You can also use the REST APIs or one of the language-specific AWS SDKs for this work. The REST API calls are [CreateAPIKey](https://docs.aws.amazon.com/waf/latest/APIReference/API_CreateAPIKey.html) and [ListAPIKeys](https://docs.aws.amazon.com/waf/latest/APIReference/API_ListAPIKeys.html). 

**To delete an API key**  
To delete an API key, you must use the REST API or one of the language specific AWS SDKs. The REST API call is [DeleteAPIKey](https://docs.aws.amazon.com/waf/latest/APIReference/API_DeleteAPIKey.html). You can't use the console to delete a key. 

After you delete a key, it can take up to 24 hours for AWS WAF to disallow use of the key in all regions. 

# AWS WAF mobile application integration
Mobile application integrationApplication integration SDKs add TV apps

You can use the Android and iOS integration SDKs for TV apps as well as mobile apps. 

This section introduces the topic of using the AWS WAF mobile SDKs to implement AWS WAF intelligent threat integration SDKs for Android and iOS mobile and TV apps. For TV apps, the SDKs are compatible with major smart TV platforms, including Android TV and Apple TV.
+ For Android mobile and TV apps, the SDKs work for Android API version 23 (Android version 6) and later. For information about Android versions, see [SDK Platform release notes](https://developer.android.com/tools/releases/platforms).
+ For iOS mobile apps, the SDKs work for iOS version 13 and later. For information about iOS versions, see [iOS & iPadOS Release Notes](https://developer.apple.com/documentation/ios-ipados-release-notes).
+ For Apple TV apps, the SDKs work for tvOS version 14 or later. For information about tvOS versions, see [tvOS Release Notes](https://developer.apple.com/documentation/tvos-release-notes).

With the mobile AWS WAF SDK, you can manage token authorization, and include the tokens in the requests that you send to your protected resources. By using the SDKs, you ensure that these remote procedure calls by your client contain a valid token. Additionally, when this integration is in place on your application's pages, you can implement mitigating rules in your protection pack (web ACL), such as blocking requests that don't contain a valid token.

For access to the mobile SDKs, contact support at [Contact AWS](https://aws.amazon.com/contact-us).

**Note**  
The AWS WAF mobile SDKs aren't available for CAPTCHA customization.

The basic approach for using the SDK is to create a token provider using a configuration object, then to use the token provider to retrieve tokens from AWS WAF. By default, the token provider includes the retrieved tokens in your web requests to your protected resource. 

The following is a partial listing of an SDK implementation, which shows the main components. For more detailed examples, see [Code examples for the AWS WAF mobile SDK](waf-mobile-sdk-coding-examples.md).

------
#### [ iOS ]

```
let url: URL = URL(string: "protection pack (web ACL) integration URL")!
	let configuration = WAFConfiguration(applicationIntegrationUrl: url, domainName: "Domain name")
	let tokenProvider = WAFTokenProvider(configuration)
	let token = tokenProvider.getToken()
```

------
#### [ Android ]

```
URL applicationIntegrationURL = new URL("protection pack (web ACL) integration URL");
	String domainName = "Domain name";
	WAFConfiguration configuration = WAFConfiguration.builder().applicationIntegrationURL(applicationIntegrationURL).domainName(domainName).build();
	WAFTokenProvider tokenProvider = new WAFTokenProvider(Application context, configuration);
	WAFToken token = tokenProvider.getToken();
```

------

# Installing the AWS WAF mobile SDK
Installing the mobile SDK

This section provides instructions for installing the AWS WAF mobile SDK.

For access to the mobile SDKs, contact support at [Contact AWS](https://aws.amazon.com/contact-us).

Implement the mobile SDK first in a test environment, then in production.

**To install the AWS WAF mobile SDK**

1. Sign in to the AWS Management Console and open the AWS WAF console at [https://console.aws.amazon.com/wafv2/homev2](https://console.aws.amazon.com/wafv2/homev2). 

1. In the navigation pane, choose **Application integration**. 

1. In the **Intelligent threat integrations** tab, do the following: 

   1. In the pane **protection packs (web ACLs) that are enabled for application integration**, locate the protection pack (web ACL) that you're integrating with. Copy and save the protection pack (web ACL) integration URL for use in your implementation. You can also obtain this URL through the API call `GetWebACL`.

   1. Choose the mobile device type and version, then choose **Download**. You can choose any version you like, but we recommend using the latest version. AWS WAF downloads the `zip` file for your device to your standard download location.

1. In your app development environment, unzip the file to a work location of your choice. In the top-level directory of the zip file, locate and open the `README`. Follow the instructions in the `README` file to install the AWS WAF mobile SDK for use in your mobile app code. 

1. Program your app according to the guidance in the following sections.

# AWS WAF mobile SDK specification
Mobile SDK specificationUpdate to the AWS WAF mobile SDK specification

Added the `loadTokenIntoProvider` operation to `WAFTokenProvider`. Update to the AWS WAF mobile SDK specification

Added the `storeTokenInCookieStorage` operation to `WAFTokenProvider`. Update to the AWS WAF mobile SDK specification

Lowered the min, max, and default values for `tokenRefreshDelaySec` from min 300, max 600, and default 300 to min 88, max 300, and default 88.Update to the AWS WAF mobile SDK specification

Lowered the default value for `tokenRefreshDelaySec` from 600 (10 minutes) to 300 (5 minutes).

This section lists the SDK objects, operations, and configuration settings for the latest available version of the AWS WAF mobile SDK. For detailed information about how the token provider and operations work for the various combinations of configuration settings, see [How the AWS WAF mobile SDK works](waf-mobile-sdk-how-it-works.md). 

**`WAFToken`**  
Holds an AWS WAF token.    
**`getValue()`**  
Retrieves the `String` representation of the `WAFToken`. 

**`WAFTokenProvider`**  
Manages tokens in your mobile app. Implement this using a `WAFConfiguration` object.    
**`getToken()`**  
If background refresh is enabled, this returns the cached token. If background refresh is disabled, this makes a synchronous, blocking call to AWS WAF to retrieve a new token.   
**`loadTokenIntoProvider(WAFToken)`**  
Loads the specified token into the `WAFTokenProvider`, replacing any token that the provider was managing. The token provider takes ownership of the new token and handles refreshing it going forward. This operation also updates the token in the cookie store, if `setTokenCookie` is enabled in the `WAFConfiguration`.  
**`onTokenReady(WAFTokenResultCallback)`**  
Instructs the token provider to refresh the token and invoke the provided callback when an active token is ready. The token provider will invoke your callback in a background thread when the token is cached and ready. Call this when your app first loads and also when it comes back to an active state. For more information about returning to an active state, see [Retrieving a token following app inactivity](waf-mobile-sdk-how-it-works.md#waf-mobile-sdk-how-back-from-inactive).   
For Android or iOS apps, you can set `WAFTokenResultCallback` to the operation that you want the token provider to invoke when a requested token is ready. Your implementation of `WAFTokenResultCallback` must take the parameters `WAFToken`, `SdkError`. For iOS apps, you can alternately create an inline function.   
**`storeTokenInCookieStorage(WAFToken)`**  
Instructs the `WAFTokenProvider` to store the specified AWS WAF token into the SDK’s cookie manager. By default, the token is only added to the cookie store when it's first acquired and when it's refreshed. If the application clears the shared cookie store for any reason, the SDK doesn't automatically add the AWS WAF token back until the next refresh. 

**`WAFConfiguration`**  
Holds the configuration for the implementation of the `WAFTokenProvider`. When you implement this, you provide your protection pack (web ACL)’s integration URL, the domain name to use in the token, and any non-default settings that you want the token provider to use.   
The following list specifies the configuration settings that you can manage in the `WAFConfiguration` object.    
**`applicationIntegrationUrl`**   
The application integration URL. Get this from the AWS WAF console or through the `getWebACL` API call.  
Required: Yes  
Type: App-specific URL. For iOS, see [iOS URL](https://developer.apple.com/documentation/foundation/url). For Android, see [java.net URL](https://docs.oracle.com/javase/7/docs/api/java/net/URL.html).   
**`backgroundRefreshEnabled`**   
Indicates whether you want the token provider to refresh the token in the background. If you set this, the token provider refreshes your tokens in the background according to the configuration settings that govern automatic token refresh activities.   
Required: No  
Type: `Boolean`  
Default value: `TRUE`  
**`domainName`**   
The domain to use in the token, which is used in token acquisition and cookie storage. For example, `example.com` or `aws.amazon.com`. This is usually the host domain of your resource that’s associated with the protection pack (web ACL), where you’ll be sending web requests. For the ACFP managed rule group, `AWSManagedRulesACFPRuleSet`, this will usually be a single domain that matches the domain in the account creation path that you provided in the rule group configuration. For the ATP managed rule group, `AWSManagedRulesATPRuleSet`, this will usually be a single domain that matches the domain in the login path that you provided in the rule group configuration.   
Public suffixes aren't allowed. For example, you can't use `gov.au` or `co.uk` as the token domain.  
The domain must be one that AWS WAF will accept, based on the protected host domain and the protection pack (web ACL)'s token domain list. For more information, see [AWS WAF protection pack (web ACL) token domain list configuration](waf-tokens-domains.md#waf-tokens-domain-lists).  
Required: Yes  
Type: `String`   
**`maxErrorTokenRefreshDelayMsec`**   
The maximum time in milliseconds to wait before repeating a token refresh after a failed attempt. For each auto-retry for a failed attempt, it will add an exponential backoff up until the given input delay time. This value is used after token retrieval has failed and been retried `maxRetryCount` times.   
Required: No  
Type: `Integer`  
Default value: `5000` (5 seconds)  
Minimum value allowed: `1` (1 millisecond)  
Maximum value allowed: `30000` (30 seconds)  
**`maxRetryCount`**   
The maximum number of retries to perform with exponential backoff when a token is requested.   
Required: No  
Type: `Integer`  
Default value: `Infinity`  
Minimum value allowed: `0`  
Maximum value allowed: `100`  
**`setTokenCookie`**   
Indicates whether you want the SDK’s cookie manager to add a token cookie into requests and in other areas.   
With a `TRUE` value:   
+ The cookie manager adds a token cookie to all requests whose path is under the path specified in `tokenCookiePath`. 
+ The `WAFTokenProvider` operation `loadTokenIntoProvider()` updates the token in the cookie store, in addition to loading it into the token provider.
Required: No  
Type: `Boolean`  
Default value: `TRUE`  
**`tokenCookiePath`**   
Used when `setTokenCookie` is `TRUE`. Indicates the top-level path where you want the SDK’s cookie manager to add a token cookie. The manager adds a token cookie to all requests that you send to this path and to all child paths.   
For example, if you set this to `/web/login`, then the manager includes the token cookie for everything sent to `/web/login` and any of its child paths, like `/web/login/help`. It doesn't include the token for requests sent to other paths, like `/`, `/web`, or `/web/order`.   
Required: No  
Type: `String`  
Default value: `/`  
**`tokenRefreshDelaySec`**   
Used for background refresh. The maximum amount of time in seconds between background token refreshes.  
Required: No  
Type: `Integer`  
Default value: `88`  
Minimum value allowed: `88`  
Maximum value allowed: `300` (5 minutes)

## AWS WAF mobile SDK errors


This section lists the possible errors for the current AWS WAF mobile SDK version.

**`SdkError`**  
The error type returned when failing to retrieve a token. The Android and iOS SDK have the same error types.  
The AWS WAF mobile SDK has the following error types:    
**`invalidChallenge`**  
This error is returned when the token server returns invalid challenge data, or the response blob is mutated by an attacker.  
**`errorInvokingGetChallengeEndpoint`**  
This error is returned when the token server sends a non-success response code back to the client or when a network error occurs.  
**`invalidVerifyChallengeResponse`**  
This error is returned when there is an error retrieving the `aws-waf-token` from the AWS WAF server's verification response, or the server response was tampered with.  
**`errorInvokingVerifyEndpoint`**  
This error is returned when the client receives a bad response from the AWS WAF server or network error when verifying the solved challenge.  
**`internalError`**  
This error is returned on all other errors that might occur within the SDK itself.

**`socketTimeoutException`**  
This error is often returned when encountering network errors during token retrieval.  
This error might be caused by the following:  
+ Low network bandwidth: Confirm your network connectivity settings
+ Mutated Application Integration URL: Confirm that the integration URL is not modified from what appears on the AWS WAF console

# How the AWS WAF mobile SDK works
How the Mobile SDK works

This section explains how the AWS WAF mobile SDK classes, properties, and operations work together.

The mobile SDKs provide you with a configurable token provider that you can use for token retrieval and use. The token provider verifies that the requests that you allow are from legitimate customers. When you send requests to the AWS resources that you protect with AWS WAF, you include the token in a cookie, to validate the request. You can handle the token cookie manually or have the token provider do it for you.

This section covers the interactions between the classes, properties, and methods that are included in the mobile SDK. For the SDK specification, see [AWS WAF mobile SDK specification](waf-mobile-sdk-specification.md). 

## Token retrieval and caching
Token retrieval and caching

When you create the token provider instance in your mobile app, you configure how you want it to manage tokens and token retrieval. Your main choice is how to maintain valid, unexpired tokens for use in your app’s web requests:
+ **Background refresh enabled** – This is the default. The token provider automatically refreshes the token in the background and caches it. With background refresh enabled, when you call `getToken()`, the operation retrieves the cached token. 

  The token provider performs the token refresh at configurable intervals, so that an unexpired token is always available in the cache while the application is active. Background refresh is paused while your application is in an inactive state. For information about this, see [Retrieving a token following app inactivity](#waf-mobile-sdk-how-back-from-inactive).
+ **Background refresh disabled** – You can disable background token refresh, and then retrieve tokens only on demand. Tokens retrieved on demand aren't cached, and you can retrieve more than one if you want. Each token is independent of any others that you retrieve, and each has its own timestamp that's used to calculate expiration.

  You have the following choices for token retrieval when background refresh is disabled: 
  + **`getToken()`** – When you call `getToken()` with background refresh disabled, the call synchronously retrieves a new token from AWS WAF. This is a potentially blocking call that might affect app responsiveness if you invoke it on the main thread. 
  + **`onTokenReady(WAFTokenResultCallback)`** – This call asynchronously retrieves a new token and then invokes the provided result callback in a background thread when a token is ready. 

### How the token provider retries failed token retrievals
Failed token retrieval retries

The token provider automatically retries token retrieval when retrieval fails. Retries are initially performed using exponential backoff with a starting retry wait time of 100 ms. For information about exponential retries, see [Error retries and exponential backoff in AWS](https://docs.aws.amazon.com/general/latest/gr/api-retries.html).

When the number of retries reaches the configured `maxRetryCount`, the token provider either stops trying or switches to trying every `maxErrorTokenRefreshDelayMsec` milliseconds, depending on the type of token retrieval: 
+ **`onTokenReady()`** – The token provider switches to waiting `maxErrorTokenRefreshDelayMsec` milliseconds between attempts, and continues trying to retrieve the token. 
+ **Background refresh** – The token provider switches to waiting `maxErrorTokenRefreshDelayMsec` milliseconds between attempts, and continues trying to retrieve the token. 
+ **On-demand `getToken()` calls, when background refresh is disabled** – The token provider stops trying to retrieve a token and returns the previous token value, or a null value if there is no previous token. 

## Token retrieval retry scenarios
Token retrieval retry scenarios

When the token provider tries to retrieve a token, it might result in auto-retries depending on where token retrieval fails in the token acquisition flow. This section lists the possible places where you might see an auto-retry.
+ **Obtaining or verifying the AWS WAF Challenge through /inputs or /verify:**
  + When a request to obtain and verify a AWS WAF challenge is made and fails, it can result in an auto-retry.
  + You might observe auto-retries happening here along with a `socketTimeoutException` error. This can have multiple causes including:
    + Low network bandwidth: Confirm your network connectivity settings
    + Mutated Application Integration URL: Confirm that the integration URL is not modified from what appears on the AWS WAF console
  + The auto-retry count is configurable with the `maxRetryCount()` function
+ **Refreshing the token:**
  + When a request to refresh the token is made through the token handler, it might result in an auto-retry.
  + The auto-retry count here is configurable with the `maxRetryCount()` function.

A configuration with no auto-retries is possible by setting `maxRetryCount(0)`.

## Token immunity time and background refresh
Token immunity and refresh

The token immunity time that you configure in the Web ACL is independent of the token refresh interval you set in the AWS WAF mobile SDK. When you enable background refresh, the SDK refreshes the token at the interval you specify using `tokenRefreshDelaySec()`. This can result in multiple valid tokens existing simultaneously, depending on your configured immunity time.

To prevent multiple valid tokens, you can disable background refresh and use the `getToken()` function to manage the token lifecycle in your mobile app.

## Retrieving a token following app inactivity
Retrieving a token following app inactivity

Background refresh is only performed while your app is considered active for your app type: 
+ **iOS** – Background refresh is performed when the app is in the foreground.
+ **Android** – Background refresh is performed when the app isn't closed, whether it's in the foreground or background.

If your app remains in any state that doesn’t support background refresh for longer than your configured `tokenRefreshDelaySec` seconds, the token provider pauses background refresh. For example, for an iOS app, if `tokenRefreshDelaySec` is 300 and the app closes or goes into the background for more than 300 seconds, the token provider stops refreshing the token. When the app returns to an active state, the token provider automatically restarts background refresh. 

When your app comes back to an active state, call `onTokenReady()` so you can be notified when the token provider has retrieved and cached a new token. Don't just call `getToken()`, because the cache might not yet contain a current, valid token. 

## Application Integration URL
Application Integration URL

The AWS WAF mobile SDK application integration URL points to a Web ACL that you've enabled for application integration. This URL routes requests to the correct backend server and associates them with your customer. It doesn't serve as a hard security control, so exposing an integration URL doesn't pose a security risk.

You can technically modify the provided integration URL and still obtain a token. However, we don't recommend this because you might lose visibility into challenge solve rates or encounter token retrieval failures with `socketTimeoutException` errors.

## Dependencies
Dependencies

Each downloadable AWS WAF mobile SDK includes a README file that lists out the dependencies for its specific version of the SDK. Refer to the README for the dependencies for your version of the mobile SDK.

## Obfuscation/ProGuard (Android SDK Only)
Obfuscation/ProGuard

If you use an obfuscation or minification product like ProGuard, you might need to exclude certain namespaces to ensure the mobile SDK works correctly. Check the README for your version of the mobile SDK to find the list of namespaces and exclusion rules.

# Code examples for the AWS WAF mobile SDK
Code examples for the Mobile SDKAWS WAF mobile SDK Android Kotlin code samples

Added example code for Kotlin-based Android integrations.

This section provides code examples for using the mobile SDK. 

## Initializing the token provider and getting tokens
Initializing the token provider and getting tokens

You initiate your token provider instance using a configuration object. Then you can retrieve tokens using the available operations. The following shows the basic components of the required code.

------
#### [ iOS ]

```
let url: URL = URL(string: "protection pack (web ACL) integration URL")!
let configuration = WAFConfiguration(applicationIntegrationUrl: url, domainName: "Domain name")
let tokenProvider = WAFTokenProvider(configuration)

//onTokenReady can be add as an observer for UIApplication.willEnterForegroundNotification
self.tokenProvider.onTokenReady() { token, error in
	if let token = token {
	//token available
	}

	if let error = error {
	//error occurred after exhausting all retries
	}
}

//getToken()
let token = tokenProvider.getToken()
```

------
#### [ Android ]

Java example:

```
String applicationIntegrationURL = "protection pack (web ACL) integration URL";
//Or
URL applicationIntegrationURL = new URL("protection pack (web ACL) integration URL");

String domainName = "Domain name";

WAFConfiguration configuration = WAFConfiguration.builder().applicationIntegrationURL(applicationIntegrationURL).domainName(domainName).build();
WAFTokenProvider tokenProvider = new WAFTokenProvider(Application context, configuration);

// implement a token result callback
WAFTokenResultCallback callback = (wafToken, error) -> {
	if (wafToken != null) {
	// token available
	} else {  
	// error occurred in token refresh  
	}
};

// Add this callback to application creation or activity creation where token will be used
tokenProvider.onTokenReady(callback);

// Once you have token in token result callback
// if background refresh is enabled you can call getToken() from same tokenprovider object
// if background refresh is disabled you can directly call getToken()(blocking call) for new token
WAFToken token = tokenProvider.getToken();
```

Kotlin example:

```
import com.amazonaws.waf.mobilesdk.token.WAFConfiguration
import com.amazonaws.waf.mobilesdk.token.WAFTokenProvider

private lateinit var wafConfiguration: WAFConfiguration
private lateinit var wafTokenProvider: WAFTokenProvider

private val WAF_INTEGRATION_URL = "protection pack (web ACL) integration URL"
private val WAF_DOMAIN_NAME = "Domain name"

fun initWaf() {
	// Initialize the tokenprovider instance
	val applicationIntegrationURL = URL(WAF_INTEGRATION_URL)
	wafConfiguration =
		WAFConfiguration.builder().applicationIntegrationURL(applicationIntegrationURL)
			.domainName(WAF_DOMAIN_NAME).backgroundRefreshEnabled(true).build()
	wafTokenProvider = WAFTokenProvider(getApplication(), wafConfiguration)
	
		// getToken from tokenprovider object
		println("WAF: "+ wafTokenProvider.token.value)
	
		// implement callback for where token will be used
		wafTokenProvider.onTokenReady {
			wafToken, sdkError ->
		run {
			println("WAF Token:" + wafToken.value)
		}
	}
}
```

------

## Allowing the SDK to provide the token cookie in your HTTP requests
Allowing the SDK to provide the token cookie

If `setTokenCookie` is `TRUE`, the token provider includes the token cookie for you in your web requests to all locations under the path that's specified in `tokenCookiePath`. By default,`setTokenCookie` is `TRUE` and `tokenCookiePath` is `/`. 

You can narrow the scope of the requests that include a token cookie by specifying the token cookie path, for example, `/web/login`. If you do this, check that your AWS WAF rules don't inspect for tokens in the requests that you send to other paths. When you use the `AWSManagedRulesACFPRuleSet` rule group, you configure the account registration and creation paths, and the rule group checks for tokens in requests that are sent to those paths. For more information, see [Adding the ACFP managed rule group to your web ACL](waf-acfp-rg-using.md). Similarly, when you use the `AWSManagedRulesATPRuleSet` rule group, you configure the login path, and the rule group checks for tokens in requests that are sent to that path. For more information, see [Adding the ATP managed rule group to your protection pack (web ACL)](waf-atp-rg-using.md). 

------
#### [ iOS ]

When `setTokenCookie` is `TRUE`, the token provider stores the AWS WAF token in a `HTTPCookieStorage.shared` and automatically includes the cookie in requests to the domain that you specified in `WAFConfiguration`.

```
let request = URLRequest(url: URL(string: domainEndpointUrl)!)
//The token cookie is set automatically as cookie header
let task = URLSession.shared.dataTask(with: request) { data, urlResponse, error  in
}.resume()
```

------
#### [ Android ]

When `setTokenCookie` is `TRUE`, the token provider stores the AWS WAF token in a `CookieHandler` instance that's shared application wide. The token provider automatically includes the cookie in requests to the domain that you specified in `WAFConfiguration`.

Java example:

```
URL url = new URL("Domain name");
//The token cookie is set automatically as cookie header
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.getResponseCode();
```

Kotlin example:

```
val url = URL("Domain name")
//The token cookie is set automatically as cookie header
val connection = (url.openConnection() as HttpsURLConnection)
connection.responseCode
```

If you already have the `CookieHandler` default instance initialized, the token provider will use it to manage cookies. If not, the token provider will initialize a new `CookieManager` instance with the AWS WAF token and `CookiePolicy.ACCEPT_ORIGINAL_SERVER` and then set this new instance as the default instance in `CookieHandler`.

The following code shows how the SDK initializes the cookie manager and cookie handler when they aren't available in your app. 

Java example:

```
CookieManager cookieManager = (CookieManager) CookieHandler.getDefault();
if (cookieManager == null) {
	// Cookie manager is initialized with CookiePolicy.ACCEPT_ORIGINAL_SERVER
	cookieManager = new CookieManager();
	CookieHandler.setDefault(cookieManager);
}
```

Kotlin example:

```
var cookieManager = CookieHandler.getDefault() as? CookieManager
if (cookieManager == null) {
	// Cookie manager is initialized with CookiePolicy.ACCEPT_ORIGINAL_SERVER
	cookieManager = CookieManager()
	CookieHandler.setDefault(cookieManager)
}
```

------

## Manually providing the token cookie in your HTTP requests
Manually providing the token cookie

If you set `setTokenCookie` to `FALSE`, then you need to provide the token cookie manually, as a Cookie HTTP request header, in your requests to your protected endpoint. The following code shows how to do this.

------
#### [ iOS ]

```
var request = URLRequest(url: wafProtectedEndpoint)
request.setValue("aws-waf-token=token from token provider", forHTTPHeaderField: "Cookie")
request.httpShouldHandleCookies = true
URLSession.shared.dataTask(with: request) { data, response, error in }
```

------
#### [ Android ]

Java example:

```
URL url = new URL("Domain name");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
String wafTokenCookie = "aws-waf-token=token from token provider";
connection.setRequestProperty("Cookie", wafTokenCookie);
connection.getInputStream();
```

Kotlin example:

```
val url = URL("Domain name")
val connection = (url.openConnection() as HttpsURLConnection)
val wafTokenCookie = "aws-waf-token=token from token provider"
connection.setRequestProperty("Cookie", wafTokenCookie)
connection.inputStream
```

------

# CAPTCHA and Challenge in AWS WAF
CAPTCHA and ChallengeAWS WAF new Challenge rule action option

You can configure rules to use a Challenge, to verify that requests are being sent by browsers. AWS WAF new CAPTCHA rule action option

You can configure rules to run a CAPTCHA against web requests and, as needed, send a CAPTCHA problem to the client. CAPTCHA and Challenge actions

Added clarification that browser clients require HTTPS to run CAPTCHA puzzles and silent challenges. 

This section explains how CAPTCHA and Challenge work with AWS WAF.

You can configure your AWS WAF rules to run a CAPTCHA or Challenge action against web requests that match your rule's inspection criteria. You can also program your JavaScript client applications to run CAPTCHA puzzles and browser challenges locally. 

CAPTCHA puzzles and silent challenges can only run when browsers are accessing HTTPS endpoints. Browser clients must be running in secure contexts in order to acquire tokens. 
+ **CAPTCHA** – Requires the end user to solve a CAPTCHA puzzle to prove that a human being is sending the request. CAPTCHA puzzles are intended to be fairly easy and quick for humans to complete successfully and hard for computers to either complete successfully or to randomly complete with any meaningful rate of success. 

  In protection pack (web ACL) rules, CAPTCHA is commonly used when a Block action would stop too many legitimate requests, but letting all traffic through would result in unacceptably high levels of unwanted requests, such as from bots. For information about the rule action behavior, see [How the AWS WAF CAPTCHA and Challenge rule actions work](waf-captcha-and-challenge-how-it-works.md).

  You can also program a CAPTCHA puzzle implementation in your client application integration APIs. When you do this, you can customize the behavior and placement of the puzzle in your client application. For more information, see [Client application integrations in AWS WAF](waf-application-integration.md). 
+ **Challenge** – Runs a silent challenge that requires the client session to verify that it's a browser, and not a bot. The verification runs in the background without involving the end user. This is a good option for verifying clients that you suspect of being invalid without negatively impacting the end user experience with a CAPTCHA puzzle. For information about the rule action behavior, see [How the AWS WAF CAPTCHA and Challenge rule actions work](waf-captcha-and-challenge-how-it-works.md).

  The Challenge rule action is similar to the challenge run by the client intelligent threat integration APIs, described at [Client application integrations in AWS WAF](waf-application-integration.md).

**Note**  
You are charged additional fees when you use the CAPTCHA or Challenge rule action in one of your rules or as a rule action override in a rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

For descriptions of all of the rule action options, see [Using rule actions in AWS WAF](waf-rule-action.md). 

**Topics**
+ [

# AWS WAF CAPTCHA puzzles
](waf-captcha-puzzle.md)
+ [

# How the AWS WAF CAPTCHA and Challenge rule actions work
](waf-captcha-and-challenge-how-it-works.md)
+ [

# Best practices for using the CAPTCHA and Challenge actions
](waf-captcha-and-challenge-best-practices.md)

# AWS WAF CAPTCHA puzzles
CAPTCHA puzzlesExpansion of language options for the AWS WAF CAPTCHA puzzle

The CAPTCHA puzzle now offers its written instructions in multiple languages. The instructions inside each audio puzzle are still provided in English only. 

This section explains the features and functionality of the AWS WAF CAPTCHA puzzle.

AWS WAF provides standard CAPTCHA functionality that challenges users to confirm that they are human beings. CAPTCHA stands for Completely Automated Public Turing test to tell Computers and Humans Apart. CAPTCHA puzzles are designed to verify that a human is sending requests and to prevent activity like web scraping, credential stuffing, and spam. CAPTCHA puzzles can't weed out all unwanted requests. Many puzzles have been solved using machine learning and artificial intelligence. In an effort to circumvent CAPTCHA, some organizations supplement automated techniques with human intervention. In spite of this, CAPTCHA continues to be a useful tool to prevent less sophisticated bot traffic and to increase the resources required for large-scale operations. 

AWS WAF randomly generates its CAPTCHA puzzles and rotates through them to ensure that users are presented with unique challenges. AWS WAF regularly adds new types and styles of puzzles to remain effective against automation techniques. In addition to the puzzles, the AWS WAF CAPTCHA script gathers data about the client to ensure that the task is being completed by a human and to prevent replay attacks. 

Each CAPTCHA puzzle includes a standard set of controls for the end user to request a new puzzle, switch between audio and visual puzzles, access additional instructions, and submit a puzzle solution. All puzzles include support for screen readers, keyboard controls, and contrasting colors. 

The AWS WAF CAPTCHA puzzles meet the requirements of the Web Content Accessibility Guidelines (WCAG). For information, see [Web Content Accessibility Guidelines (WCAG) Overview](https://www.w3.org/WAI/standards-guidelines/wcag/) at the World Wide Web Consortium (W3C) website.

**Topics**
+ [

# CAPTCHA puzzle language support
](waf-captcha-puzzle-language-support.md)
+ [

# CAPTCHA puzzle examples
](waf-captcha-puzzle-examples.md)

# CAPTCHA puzzle language support
Language supportAWS WAF CAPTCHA puzzles audio

The audio version of the CAPTCHA puzzle now supports multiple languages. 

This section lists what languages are supported in AWS WAF CAPTCHA puzzles.

The CAPTCHA puzzle starts with written instructions in the client browser language or, if the browser language is unsupported, in English. The puzzle provides alternate language options through a dropdown menu.

The user can switch to audio instructions by selecting the headphone icon at the bottom of the page. The audio version of the puzzle provides spoken instructions about text that the user should type into a text box, overlaid by background noise. 

The following table lists the languages that you can select for the written instructions in a CAPTCHA puzzle and the audio support for each selection. 


**AWS WAF CAPTCHA puzzle supported languages**  

| Written instructions support | Locale code | Audio instructions support | 
| --- | --- | --- | 
|  Arabic  |  ar-SA  |  Arabic  | 
|  Simplified Chinese  |  zh-CN  |  Audio in English  | 
|  Dutch  |  nl-NL  |  Dutch  | 
|  English  |  en-US  |  English  | 
|  French  |  fr-FR  |  French  | 
|  German  |  de-DE  |  German  | 
|  Italian  |  it-IT  |  Italian  | 
|  Japanese  |  ja-JP  |  Audio in English  | 
|  Brazilian Portuguese  |  pt-BR  |  Brazilian Portuguese  | 
|  Spanish  |  es-ES  |  Spanish  | 
|  Turkish  |  tr-TR  |  Turkish  | 

# CAPTCHA puzzle examples
Puzzle examples

A typical visual CAPTCHA puzzle requires interaction to show that the user can comprehend and interact with one or more images. 

The following screenshot shows an example of a picture grid puzzle. This puzzle requires you to select all of the pictures in the grid that include a specific type of object. 

![\[A screen contains the title "Let's confirm you are human" and the text "Choose all the chairs". Below the text is a 3x3 grid of images, some of which contain chairs and others that contain non-chair objects, like beds and windows. At the bottom of the screen are options to load a different puzzle, toggle the information box into and out of view, toggle to an audio puzzle, and change the language. Also at the bottom is the button "Confirm".\]](http://docs.aws.amazon.com/waf/latest/developerguide/images/CAPTCHAPuzzleGrid.png)


An audio puzzle provides background noise overlaid with spoken instructions about text that the user should type into a text box.

The following screenshot shows the display for the audio puzzle choice. 

![\[A screen contains the title "Solve the puzzle" and the text "Click play to listen to instructions". Below the text is an image that shows a Play button. Below the image is the text "Keyboard audio toggle: alt + space". Below is a title "Enter your response" with a text entry box below it. An open information box has the text "Solve by listening to the recording and typing your answer into the text box." At the bottom of the screen are options to load a different puzzle, toggle the information box into and out of view, and toggle to a visual puzzle. Also at the bottom is the button "Submit".\]](http://docs.aws.amazon.com/waf/latest/developerguide/images/CAPTCHAPuzzleAudio.png)




# How the AWS WAF CAPTCHA and Challenge rule actions work
How the rule actions work

This section explains how CAPTCHA and Challenge work.

AWS WAF CAPTCHA and Challenge are standard rule actions, so they're relatively easy to implement. To use either of them, you create the inspection criteria for your rule that identifies the requests that you want to inspect, and then specify one of the two rule actions. For general information about rule action options, see [Using rule actions in AWS WAF](waf-rule-action.md).

In addition to implementing silent challenges and CAPTCHA puzzles from the server side, you can integrate silent challenges in your JavaScript and iOS and Android client applications, and you can render CAPTCHA puzzles in your JavaScript clients. These integrations allow you to provide your end users with better performance and CAPTCHA puzzle experiences, and they can reduce costs associated with using the rule actions and the intelligent threat mitigation rule groups. For more information about these options, see [Client application integrations in AWS WAF](waf-application-integration.md). For pricing information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

**Topics**
+ [

# CAPTCHA and Challenge action behavior
](waf-captcha-and-challenge-actions.md)
+ [

# CAPTCHA and Challenge actions in the logs and metrics
](waf-captcha-and-challenge-logs-metrics.md)

# CAPTCHA and Challenge action behavior
Action behavior

This section explains what the CAPTCHA and Challenge actions do.

When a web request matches the inspection criteria of a rule with CAPTCHA or Challenge action, AWS WAF determines how to handle the request according to the state of its token and immunity time configuration. AWS WAF also considers whether the request can handle the CAPTCHA puzzle or challenge script interstitials. The scripts are designed to be handled as HTML content, and they can only be handled properly by a client that's expecting HTML content. 

**Note**  
You are charged additional fees when you use the CAPTCHA or Challenge rule action in one of your rules or as a rule action override in a rule group. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing/).

**How the action handles the web request**  
AWS WAF applies the CAPTCHA or Challenge action to a web request as follows:
+ **Valid token** – AWS WAF handles this similar to a Count action. AWS WAF applies any labels and request customizations that you've configured for the rule action, and then continues evaluating the request using the remaining rules in the protection pack (web ACL). 
+ **Missing, invalid, or expired token** – AWS WAF discontinues the protection pack (web ACL) evaluation of the request and blocks it from going to its intended destination. 

  AWS WAF generates a response that it sends back to the client, according to the rule action type: 
  + **Challenge** – AWS WAF includes the following in the response:
    + The header `x-amzn-waf-action` with a value of `challenge`.
**Note**  
For Javascript applications running in the client browser, this header is only available within the application's domain. The header isn't available for cross-domain retrieval. For details, see the section that follows.
    + The HTTP status code `202 Request Accepted`.
    + If the request contains an `Accept` header with a value of `text/html`, the response includes a JavaScript page interstitial with a challenge script.
  + **CAPTCHA** – AWS WAF includes the following in the response:
    + The header `x-amzn-waf-action` with a value of `captcha`.
**Note**  
For Javascript applications running in the client browser, this header is only available within the application's domain. The header isn't available for cross-domain retrieval. For details, see the section that follows.
    + The HTTP status code `405 Method Not Allowed`.
    + If the request contains an `Accept` header with a value of `text/html`, the response includes a JavaScript page interstitial with a CAPTCHA script. 

To configure the timing of token expiration at the protection pack (web ACL) or rule level, see [Setting timestamp expiration and token immunity times in AWS WAF](waf-tokens-immunity-times.md).

**Headers are unavailable to JavaScript applications that run in the client browser**  
When AWS WAF responds to a client request with a CAPTCHA or challenge response, it doesn't include cross-origin resource sharing (CORS) headers. CORS headers are a set of access control headers that tell the client web browser which domains, HTTP methods, and HTTP headers can be used by JavaScript applications. Without CORS headers, JavaScript applications running in a client browser are not granted access to HTTP headers and so are unable to read the `x-amzn-waf-action` header that's provided in the CAPTCHA and Challenge responses. 

**What the challenge and CAPTCHA interstitials do**  
When a challenge interstitial runs, after the client responds successfully, if it doesn't already have a token, the interstitial initializes one for it. Then it updates the token with the challenge solve timestamp.

When a CAPTCHA interstitial runs, if the client doesn't have a token yet, the CAPTCHA interstitial invokes the challenge script first to challenge the browser and initialize the token. Then the interstitial runs its CAPTCHA puzzle. When the end user successfully completes the puzzle, the interstitial updates the token with the CAPTCHA solve timestamp. 

In either case, after the client responds successfully and the script updates the token, the script resubmits the original web request using the updated token. 

You can configure how AWS WAF handles tokens. For information, see [Token use in AWS WAF intelligent threat mitigation](waf-tokens.md).

# CAPTCHA and Challenge actions in the logs and metrics
Logs and metrics

This section explains how AWS WAF handles logging and metrics for the CAPTCHA and Challenge actions.

The CAPTCHA and Challenge actions can be non-terminating, like Count, or terminating, like Block. The outcome depends on whether the request has a valid token with an unexpired timestamp for the action type. 
+ **Valid token** – When the action finds a valid token and doesn't block the request, AWS WAF captures metrics and logs as follows:
  + Increments the metrics for either `CaptchaRequests` and `RequestsWithValidCaptchaToken` or `ChallengeRequests` and `RequestsWithValidChallengeToken`. 
  + Logs the match as a `nonTerminatingMatchingRules` entry with action of CAPTCHA or Challenge. The following listing shows the section of a log for this type of match with the CAPTCHA action.

    ```
        "nonTerminatingMatchingRules": [
        {
          "ruleId": "captcha-rule",
          "action": "CAPTCHA",
          "ruleMatchDetails": [],
          "captchaResponse": {
            "responseCode": 0,
            "solveTimestamp": 1632420429
          }
        }
      ]
    ```
+ **Missing, invalid, or expired token** – When the action blocks the request due to a missing or invalid token, AWS WAF captures metrics and logs as follows:
  + Increments the metric for `CaptchaRequests` or `ChallengeRequests`. 
  + Logs the match as a `CaptchaResponse` entry with HTTP `405` status code or as a `ChallengeResponse` entry with HTTP `202` status code. The log indicates whether the request was missing the token or had an expired timestamp. The log also indicates whether AWS WAF sent a CAPTCHA interstitial page to the client or a silent challenge to the client browser. The following listing shows the sections of a log for this type of match with the CAPTCHA action.

    ```
        "terminatingRuleId": "captcha-rule",
        "terminatingRuleType": "REGULAR",
        "action": "CAPTCHA",
        "terminatingRuleMatchDetails": [],
        ...
        "responseCodeSent": 405,
        ...
        "captchaResponse": {
          "responseCode": 405,
          "solveTimestamp": 0,
          "failureReason": "TOKEN_MISSING"
        }
    ```

For information about the AWS WAF logs, see [Logging AWS WAF protection pack (web ACL) traffic](logging.md).

For information about AWS WAF metrics, see [AWS WAF metrics and dimensions](waf-metrics.md).

For general information about rule action options, see [Using rule actions in AWS WAF](waf-rule-action.md).

**Requests with no token seem to show up twice in logs and metrics**  
Based on the [CAPTCHA and Challenge action behavior](waf-captcha-and-challenge-actions.md) and the logging and metrics described in this section, a request with no token will generally be represented twice in the logs and metrics. This is because the one intended request is actually sent twice by the client.
+ The first request, with no token, receives the logging and metrics handling described above for missing, invalid, or expired token. The CAPTCHA or Challenge action terminates this first request, and then responds back to the client with either a silent challenge or CAPTCHA puzzle. 
+ The client evaluates the challenge or puzzle and, if the client browser or end user responds successfully, sends the request a second time with the newly acquired token. This second request receives the logging and metrics handling described above for a request with a valid token. 

# Best practices for using the CAPTCHA and Challenge actions
CAPTCHA and Challenge best practices

Follow the guidance in this section to plan and implement AWS WAF CAPTCHA or challenge.

**Plan your CAPTCHA and challenge implementation**  
Determine where to place CAPTCHA puzzles or silent challenges based on your website usage, the sensitivity of the data that you want to protect, and the type of requests. Select the requests where you'll apply CAPTCHA so that you present the puzzles as needed, but avoid presenting them where they wouldn't be useful and might degrade the user experience. Use the Challenge action to run silent challenges that have less impact on the end user, but still help verify that the request is coming from a JavaScript enabled browser. 

CAPTCHA puzzles and silent challenges can only run when browsers are accessing HTTPS endpoints. Browser clients must be running in secure contexts in order to acquire tokens. 

**Decide where to run CAPTCHA puzzles and silent challenges on your clients**  
Identify requests that you don't want to have impacted by CAPTCHA, for example, requests for CSS or images. Use CAPTCHA only when necessary. For example, if you plan to have a CAPTCHA check at login, and the user is always taken directly from the login to another screen, requiring a CAPTCHA check at the second screen would probably not be needed and might degrade your end user experience. 

Configure your Challenge and CAPTCHA use so that AWS WAF only sends CAPTCHA puzzles and silent challenges in response to `GET` `text/html` requests. You can't run either the puzzle or the challenge in response to `POST` requests, Cross-Origin Resource Sharing (CORS) preflight `OPTIONS` requests, or any other non-`GET` request types. Browser behavior for other request types can vary and might not be able to handle the interstitials properly. 

It's possible for a client to accept HTML but still not be able to handle the CAPTCHA or challenge interstitial. For example, a widget on a webpage with a small iFrame might accept HTML but not be able to display a CAPTCHA or process it. Avoid placing the rule actions for these types of requests, the same as for requests that don't accept HTML.

**Use CAPTCHA or Challenge to verify prior token acquisition**  
You can use the rule actions solely to verify the existence of a valid token, at locations where legitimate users should always have one. In these situations, it doesn't matter whether the request can handle the interstitials. 

For example, if you implement the JavaScript client application CAPTCHA API, and run the CAPTCHA puzzle on the client immediately before you send the first request to your protected endpoint, your first request should always include a token that's valid for both challenge and CAPTCHA. For information about JavaScript client application integration, see [AWS WAF JavaScript integrations](waf-javascript-api.md). 

For this situation, in your protection pack (web ACL), you can add a rule that matches against this first call and configure it with the Challenge or CAPTCHA rule action. When the rule matches for a legitimate end user and browser, the action will find a valid token, and therefore will not block the request or send a challenge or CAPTCHA puzzle in response. For more information about how the rule actions work, see [CAPTCHA and Challenge action behavior](waf-captcha-and-challenge-actions.md).

**Protect your sensitive non-HTML data with CAPTCHA and Challenge**  
You can use CAPTCHA and Challenge protections for sensitive non-HTML data, like APIs, with the following approach. 

1. Identify requests that take HTML responses and that are run in close proximity to the requests for your sensitive, non-HTML data. 

1. Write CAPTCHA or Challenge rules that match against the requests for HTML and that match against the requests for your sensitive data. 

1. Tune your CAPTCHA and Challenge immunity time settings so that, for normal user interactions, the tokens that clients obtain from the HTML requests are available and unexpired in their requests for your sensitive data. For tuning information, see [Setting timestamp expiration and token immunity times in AWS WAF](waf-tokens-immunity-times.md).

When a request for your sensitive data matches a CAPTCHA or Challenge rule, it won't be blocked if the client still has a valid token from the prior puzzle or challenge. If the token isn't available or the timestamp is expired, the request to access your sensitive data will fail. For more information about how the rule actions work, see [CAPTCHA and Challenge action behavior](waf-captcha-and-challenge-actions.md).

**Use CAPTCHA and Challenge to tune your existing rules**  
Review your existing rules, to see if you want to alter or add to them. The following are some common scenarios to consider. 
+ If you have a rate-based rule that blocks traffic, but you keep the rate limit relatively high to avoid blocking legitimate users, consider adding a second rate-based rule after the blocking rule. Give the second rule a lower limit than the blocking rule and set the rule action to CAPTCHA or Challenge. The blocking rule will still block requests that are coming at too high a rate, and the new rule will block most automated traffic at an even lower rate. For information about rate-based rules, see [Using rate-based rule statements in AWS WAF](waf-rule-statement-type-rate-based.md).
+ If you have a managed rule group that blocks requests, you can switch the behavior for some or all of the rules from Block to CAPTCHA or Challenge. To do this, in the managed rule group configuration, override the rule action setting. For information about overriding rule actions, see [Rule group rule action overrides](web-acl-rule-group-override-options.md#web-acl-rule-group-override-options-rules). 

**Test your CAPTCHA and challenge implementations before you deploy them**  
As for all new functionality, follow the guidance at [Testing and tuning your AWS WAF protections](web-acl-testing.md).

During testing, review your token timestamp expiration requirements and set your web ACL and rule level immunity time configurations so that you achieve a good balance between controlling access to your website and providing a good experience for your customers. For information, see [Setting timestamp expiration and token immunity times in AWS WAF](waf-tokens-immunity-times.md).