

# AWS WAF 로그에 대한 쿼리 예제
<a name="query-examples-waf-logs"></a>

이 섹션의 쿼리 예제는 대부분 이전에 생성한 파티션 프로젝션 테이블을 사용합니다. 필요에 따라 예제의 테이블 이름, 열 값 및 기타 변수를 수정합니다. 쿼리 성능을 개선하고 비용을 줄이려면 필터 조건에 파티션 열을 추가합니다.

**Topics**
+ [참조자, IP 주소 또는 일치하는 규칙 개수](query-examples-waf-logs-count.md)
+ [날짜 및 시간을 사용한 쿼리](query-examples-waf-logs-date-time.md)
+ [차단된 요청 또는 주소 쿼리](query-examples-waf-logs-blocked-requests.md)

# 참조자, IP 주소 또는 일치하는 규칙 개수
<a name="query-examples-waf-logs-count"></a>

이 섹션의 예제에서는 관심 있는 로그 항목의 개수를 쿼리합니다.
+ [Count the number of referrers that contain a specified term](#waf-example-count-referrers-with-specified-term)
+ [Count all matched IP addresses in the last 10 days that have matched excluded rules](#waf-example-count-matched-ip-addresses)
+ [Group all counted managed rules by the number of times matched](#waf-example-group-managed-rules-by-times-matched)
+ [Group all counted custom rules by number of times matched](#waf-example-group-custom-rules-by-times-matched)

**Example - 지정된 용어를 포함하는 참조자 수 계산**  
다음 쿼리는 지정된 날짜 범위에서 “amazon”이라는 용어를 포함한 참조자의 수를 셉니다.  

```
WITH test_dataset AS 
  (SELECT header FROM waf_logs
    CROSS JOIN UNNEST(httprequest.headers) AS t(header) WHERE "date" >= '2021/03/01'
    AND "date" < '2021/03/31')
SELECT COUNT(*) referer_count 
FROM test_dataset 
WHERE LOWER(header.name)='referer' AND header.value LIKE '%amazon%'
```

**Example - 지난 10일 동안 제외된 규칙과 일치하는 모든 IP 주소 계산**  
다음 쿼리는 지난 10일 동안 IP 주소가 규칙 그룹에서 제외된 규칙과 일치하는 횟수를 셉니다.  

```
WITH test_dataset AS 
  (SELECT * FROM waf_logs 
    CROSS JOIN UNNEST(rulegrouplist) AS t(allrulegroups))
SELECT 
  COUNT(*) AS count, 
  "httprequest"."clientip", 
  "allrulegroups"."excludedrules",
  "allrulegroups"."ruleGroupId"
FROM test_dataset 
WHERE allrulegroups.excludedrules IS NOT NULL AND from_unixtime(timestamp/1000) > now() - interval '10' day
GROUP BY "httprequest"."clientip", "allrulegroups"."ruleGroupId", "allrulegroups"."excludedrules"
ORDER BY count DESC
```

**Example - 일치하는 횟수를 기준으로 계산된 모든 관리형 규칙 그룹화**  
2022년 10월 27일 이전에 웹 ACL 구성에서 규칙 그룹 규칙 작업을 개수로 설정한 경우 AWS WAF에서는 재정의를 웹 ACL JSON에 `excludedRules`로 저장했습니다. 이제 규칙을 개수로 재정의하기 위한 JSON 설정은 `ruleActionOverrides` 설정에 있습니다. 자세한 내용은 *AWS WAF 개발자 안내서*의 [Action overrides in rule groups](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-rule-group-override-options.html)를 참조하세요. 새 로그 구조에서 개수 모드의 관리형 규칙을 추출하려면 다음 예제와 같이 `excludedRules` 필드 대신 `ruleGroupList` 섹션에서 `nonTerminatingMatchingRules`를 쿼리합니다.  

```
SELECT
 count(*) AS count,
 httpsourceid,
 httprequest.clientip,
 t.rulegroupid, 
 t.nonTerminatingMatchingRules
FROM "waf_logs" 
CROSS JOIN UNNEST(rulegrouplist) AS t(t) 
WHERE action <> 'BLOCK' AND cardinality(t.nonTerminatingMatchingRules) > 0 
GROUP BY t.nonTerminatingMatchingRules, action, httpsourceid, httprequest.clientip, t.rulegroupid 
ORDER BY "count" DESC 
Limit 50
```

**Example - 일치하는 횟수를 기준으로 계산된 모든 사용자 지정 규칙 그룹화**  
다음 쿼리는 일치하는 횟수를 기준으로 계산된 모든 사용자 지정 규칙을 그룹화합니다.  

```
SELECT
  count(*) AS count,
         httpsourceid,
         httprequest.clientip,
         t.ruleid,
         t.action
FROM "waf_logs" 
CROSS JOIN UNNEST(nonterminatingmatchingrules) AS t(t) 
WHERE action <> 'BLOCK' AND cardinality(nonTerminatingMatchingRules) > 0 
GROUP BY t.ruleid, t.action, httpsourceid, httprequest.clientip 
ORDER BY "count" DESC
Limit 50
```

사용자 지정 규칙 및 관리형 규칙 그룹의 로그 위치에 대한 자세한 내용은 *AWS WAF 개발자 안내서*의 [Monitoring and tuning](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-testing-activities.html)을 참조하세요.

# 날짜 및 시간을 사용한 쿼리
<a name="query-examples-waf-logs-date-time"></a>

이 섹션의 예제에는 날짜 및 시간 값을 사용하는 쿼리가 포함되어 있습니다.
+ [Return the timestamp field in human-readable ISO 8601 format](#waf-example-return-human-readable-timestamp)
+ [Return records from the last 24 hours](#waf-example-return-records-last-24-hours)
+ [Return records for a specified date range and IP address](#waf-example-return-records-date-range-and-ip)
+ [For a specified date range, count the number of IP addresses in five minute intervals](#waf-example-count-ip-addresses-in-date-range)
+ [Count the number of X-Forwarded-For IP in the last 10 days](#waf-example-count-x-forwarded-for-ip)

**Example - 사람이 읽을 수 있는 ISO 8601 형식으로 타임스탬프 필드 반환**  
다음 쿼리는 `from_unixtime` 및 `to_iso8601` 함수를 사용하여 `timestamp` 필드를 사람이 읽을 수 있는 ISO 8601 형식으로 반환합니다(예: `1576280412771`이 아닌 `2019-12-13T23:40:12.000Z`). 쿼리는 HTTP 소스 이름, 소스 ID, 요청도 반환합니다.  

```
SELECT to_iso8601(from_unixtime(timestamp / 1000)) as time_ISO_8601,
       httpsourcename,
       httpsourceid,
       httprequest
FROM waf_logs
LIMIT 10;
```

**Example - 최근 24시간의 레코드 반환**  
다음 쿼리는 `WHERE` 절에 필터를 사용해 최근 24시간의 레코드의 HTTP 소스 이름, HTTP 소스 ID, HTTP 요청 필드를 반환합니다.  

```
SELECT to_iso8601(from_unixtime(timestamp/1000)) AS time_ISO_8601, 
       httpsourcename, 
       httpsourceid, 
       httprequest 
FROM waf_logs
WHERE from_unixtime(timestamp/1000) > now() - interval '1' day
LIMIT 10;
```

**Example - 지정된 날짜 범위 및 IP 주소에 대한 레코드 반환**  
다음 쿼리는 지정된 클라이언트 IP 주소에 대해 지정된 날짜 범위의 레코드를 나열합니다.  

```
SELECT * 
FROM waf_logs 
WHERE httprequest.clientip='53.21.198.66' AND "date" >= '2021/03/01' AND "date" < '2021/03/31'
```

**Example - 지정된 날짜 범위에 대해 5분 간격으로 IP 주소 개수 계산**  
다음 쿼리는 특정 날짜 범위에 대해 5분 간격으로 IP 주소 개수를 셉니다.  

```
WITH test_dataset AS 
  (SELECT 
     format_datetime(from_unixtime((timestamp/1000) - ((minute(from_unixtime(timestamp / 1000))%5) * 60)),'yyyy-MM-dd HH:mm') AS five_minutes_ts,
     "httprequest"."clientip" 
     FROM waf_logs 
     WHERE "date" >= '2021/03/01' AND "date" < '2021/03/31')
SELECT five_minutes_ts,"clientip",count(*) ip_count 
FROM test_dataset 
GROUP BY five_minutes_ts,"clientip"
```

**Example - 지난 10일 동안 X-Forwarded-For IP 수 계산**  
다음 쿼리는 요청 헤더를 필터링하고 지난 10일 동안의 X-Forwarded-For IP 수를 계산합니다.  

```
WITH test_dataset AS
  (SELECT header
   FROM waf_logs
   CROSS JOIN UNNEST (httprequest.headers) AS t(header)
   WHERE from_unixtime("timestamp"/1000) > now() - interval '10' DAY) 
SELECT header.value AS ip,
       count(*) AS COUNT 
FROM test_dataset 
WHERE header.name='X-Forwarded-For' 
GROUP BY header.value 
ORDER BY COUNT DESC
```

날짜 및 시간 함수에 대한 자세한 내용은 Trino 설명서의 [날짜 및 시간 함수와 연산자](https://trino.io/docs/current/functions/datetime.html)를 참조하세요.

# 차단된 요청 또는 주소 쿼리
<a name="query-examples-waf-logs-blocked-requests"></a>

이 섹션의 예제는 차단된 요청 또는 주소를 쿼리합니다.
+ [Extract the top 100 IP addresses blocked by a specified rule type](#waf-example-extract-top-100-blocked-ip-by-rule)
+ [Count the number of times a request from a specified country has been blocked](#waf-example-count-request-blocks-from-country)
+ [Count the number of times a request has been blocked, grouping by specific attributes](#waf-example-count-request-blocks-by-attribute)
+ [Count the number of times a specific terminating rule ID has been matched](#waf-example-count-terminating-rule-id-matches)
+ [Retrieve the top 100 IP addresses blocked during a specified date range](#waf-example-top-100-ip-addresses-blocked-for-date-range)

**Example - 지정된 규칙 유형에 의해 차단된 상위 100개 IP 주소 추출**  
다음 쿼리는 지정된 날짜 범위 동안 `RATE_BASED` 종료 규칙에 의해 차단된 상위 100개 IP 주소를 추출하고 그 횟수를 셉니다.  

```
SELECT COUNT(httpRequest.clientIp) as count,
httpRequest.clientIp
FROM waf_logs
WHERE terminatingruletype='RATE_BASED' AND action='BLOCK' and "date" >= '2021/03/01'
AND "date" < '2021/03/31'
GROUP BY httpRequest.clientIp
ORDER BY count DESC
LIMIT 100
```

**Example - 지정된 국가의 요청이 차단된 횟수 계산**  
다음 쿼리는 아일랜드(IE)에 속하며 `RATE_BASED` 종료 규칙에 의해 차단된 IP 주소에서 요청이 도착한 횟수를 계산합니다.  

```
SELECT 
  COUNT(httpRequest.country) as count, 
  httpRequest.country 
FROM waf_logs
WHERE 
  terminatingruletype='RATE_BASED' AND 
  httpRequest.country='IE'
GROUP BY httpRequest.country
ORDER BY count
LIMIT 100;
```

**Example - 요청이 차단된 횟수 계산(특정 속성별로 그룹화)**  
다음 쿼리는 요청이 차단된 횟수를 계산하여 WebACL, RuleId, ClientIP 및 HTTP 요청 URI별로 결과를 그룹화합니다.  

```
SELECT 
  COUNT(*) AS count,
  webaclid,
  terminatingruleid,
  httprequest.clientip,
  httprequest.uri
FROM waf_logs
WHERE action='BLOCK'
GROUP BY webaclid, terminatingruleid, httprequest.clientip, httprequest.uri
ORDER BY count DESC
LIMIT 100;
```

**Example - 특정 종료 규칙 ID가 일치하는 횟수 계산**  
다음 쿼리는 특정 종료 규칙 ID(`WHERE terminatingruleid='e9dd190d-7a43-4c06-bcea-409613d9506e'`)가 일치하는 횟수를 계산합니다. 이 쿼리는 WebACL, Action, ClientIP 및 HTTP 요청 URI별로 결과를 그룹화합니다.  

```
SELECT 
  COUNT(*) AS count,
  webaclid,
  action,
  httprequest.clientip,
  httprequest.uri
FROM waf_logs
WHERE terminatingruleid='e9dd190d-7a43-4c06-bcea-409613d9506e'
GROUP BY webaclid, action, httprequest.clientip, httprequest.uri
ORDER BY count DESC
LIMIT 100;
```

**Example - 지정된 날짜 범위 동안 차단된 상위 100개 IP 주소 검색**  
다음 쿼리는 지정된 날짜 범위 동안 차단된 상위 100개 IP 주소를 추출합니다. 쿼리에는 IP 주소가 차단된 횟수도 나열됩니다.  

```
SELECT "httprequest"."clientip", "count"(*) "ipcount", "httprequest"."country"
FROM waf_logs
WHERE "action" = 'BLOCK' and "date" >= '2021/03/01'
AND "date" < '2021/03/31'
GROUP BY "httprequest"."clientip", "httprequest"."country"
ORDER BY "ipcount" DESC limit 100
```