> For the complete documentation index, see [llms.txt](https://docs.panther.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.panther.com/ko/detections/rules/python/globals.md).

# 전역 헬퍼 함수

## 개요

프로그래밍에서 흔한 패턴은 반복되는 코드를 헬퍼 함수로 추출하는 것입니다—Panther는 이 패턴을 `전역` analysis type입니다. Panther는 여러 개의 [내장 전역 헬퍼 함수](#built-in-globals), 그리고 또한 [자신만의 사용자 지정 전역을 추가할 수도 있습니다](#adding-custom-globals). 특정한 것들에 대해 더 알아보세요 [일반적인 헬퍼](#common-helpers) 아래.

{% hint style="warning" %}
전역 헬퍼는 빈번한 변경에 가장 적합하지 않습니다. 만약 당신이 *정말로* 빈번한 변경을 해야 한다면, 대신 다음을 사용하는 것을 고려하세요 [사용자 지정 조회 테이블](/ko/enrichment/custom.md), 이는 S3와의 자동 동기화를 지원하며 업데이트를 위해 Panther 내부의 코드 변경이 필요하지 않습니다.
{% endhint %}

## Panther가 관리하는 전역

기본적으로 Panther는 다음 내장 전역 헬퍼 컬렉션을 제공합니다:

* [`panther_base_helpers`](https://github.com/panther-labs/panther-analysis/blob/main/global_helpers/panther_base_helpers.py): 다양한 일반용 및 로그 소스별 헬퍼를 포함합니다. 다음에 정의된 특정 함수에 대해 더 알아보세요 `panther_base_helpers` 아래의, [공통 헬퍼](#common-helpers).
* [`panther_디택션_helpers`](/ko/detections/rules/python/caching.md#cache-helper-functions-in-panther_detection_helpers): 캐싱 함수를 제공합니다. 다음에 대해 더 알아보세요 `panther_디택션_helpers` 패키지 [Python Rules 캐싱에 대한](/ko/detections/rules/python/caching.md#cache-helper-functions-in-panther_detection_helpers).

### Panther가 관리하는 전역 사용자 지정

일부 전역은 허용 목록의 값을 제공하는 등의 구성 입력이 필요합니다. 로직 수정이나 사용자 지정 메서드 추가와 같은 더 중요한 변경이 필요하다면, 일반적으로 다음을 권장합니다 [새 전역을 만들기](#adding-custom-globals) 어떤 것에 대해서든. 이렇게 하면 디택션 소스를 업데이트할 때 복잡한 병합 충돌을 처리해야 할 가능성을 줄일 수 있습니다.

여전히 전역 헬퍼를 수정하고 싶다면, Panther Knowledge Base 문서를 참조하세요: [Panther가 관리하는 전역 헬퍼 함수를 사용자 지정하는 가장 좋은 방법은 무엇인가요?](https://help.panther.com/articles/3976369474-managing-panther-global-helpers-overwriting-vs-cloning)

## 전역 사용

### 전역 보기

{% tabs %}
{% tab title="콘솔" %}

* Console에서 Panther가 제공한 및 사용자 지정 헬퍼 파일을 보려면, Panther Console의 왼쪽 탐색 모음에서 클릭하세요 **탐지,** 그런 다음 **헬퍼** 탭.

<figure><img src="/files/7734412d40e8f3be3e4cef8ccb83c61092dc185b" alt="An arrow is drawn from &#x22;Detections&#x22; to &#x22;Helpers,&#x22; and a page titled &#x22;Helpers is shown, with a table with various entries, including &#x22;crowdstrike_event_streams_helpers&#x22; and &#x22;gcp_environment&#x22;." width="563"><figcaption></figcaption></figure>
{% endtab %}

{% tab title="CLI 워크플로" %}

* CLI 워크플로에서 Panther가 제공한 헬퍼 파일을 보려면, 다음을 참조하세요 [`global_helpers` 디렉터리를 `panther-analysis` GitHub 저장소](https://github.com/panther-labs/panther-analysis/tree/main/global_helpers).
  {% endtab %}
  {% endtabs %}

### 사용자 지정 전역 추가

새 전역은 다음에서 만들 수 있습니다 [Panther Analysis Tool](/ko/panther/detections-repo/pat.md) 또는 Panther Console에서 만들 수 있습니다.

{% hint style="warning" %}
Panther에서 디택션 내부에서 외부 API 요청을 하는 것은 매우 권장되지 않습니다. 일반적으로 디택션은 매우 대규모로 처리되므로 API 요청을 하면 수신 시스템에 과부하가 걸리고 룰이 다음을 초과할 수 있습니다 [15초 실행 시간 제한](/ko/detections/rules.md#rule-errors-and-scheduled-rule-errors).
{% endhint %}

{% tabs %}
{% tab title="Panther Console" %}
Panther Console에서 새 전역을 만들려면:

1. Panther 콘솔의 왼쪽 탐색 표시줄에서 다음을 클릭합니다: **디택션**.
2. 다음을 클릭합니다: **헬퍼** 탭.
3. 오른쪽 상단 모서리에서 다음을 클릭하세요 **새로 만들기**.\
   ![On the Helpers page in the Panther Console, there is a blue "Create New" button in the upper right.](/files/e9568c822b44eb9250b26710a471e6bed1577652)
4. Python 함수를 입력한 다음 클릭하세요 **만들기**. 이제 이 전역은 규칙 또는 정책에서 가져올 수 있습니다.

<figure><img src="/files/1cb914ed2de9021ee6809d861c7fab2ba448c90a" alt="The Helper Settings page shows fields for Helper Name and Description. Under Helper Definition, there is a code block with sample Python code written in it."><figcaption></figcaption></figure>
{% endtab %}

{% tab title="Panther Analysis Tool" %}
전역 함수는 규칙이나 정책 전반에서 공통 로직을 공유할 수 있게 합니다. 이를 코드로 선언하려면, 다음에 추가하세요 `global_helpers` 규칙 및 정책과 유사한 패턴의 폴더에

{% hint style="info" %}
다음 바깥에서 정의된 전역은 `global_helpers` 폴더는 로드되지 않습니다.
{% endhint %}

1. Python 파일을 만드세요 (`global_helpers/acmecorp.py`):

```python
from fnmatch import fnmatch

RESOURCE_PATTERN = 'acme-corp-*-[0-9]'


def matches_internal_naming(resource_name):
  return fnmatch(resource_name, RESOURCE_PATTERN)
```

2\. 사양 파일을 만드세요:

```yaml
AnalysisType: global
GlobalID: acmecorp
Filename: acmecorp.py
설명: acme-corp 내부용 헬퍼 모음
```

3\. 이 헬퍼를 정책(또는 룰)에 사용하세요:

```python
import acmecorp


def policy(resource):
  return acmecorp.matches_internal_naming(resource['Name'])
```

{% endtab %}
{% endtabs %}

### 디택션에서 전역 가져오기

전역 헬퍼를 가져오려면 `import` 문을 분석 파일 상단에 추가한 다음, 이 헬퍼를 마치 다른 Python 라이브러리처럼 호출하세요.

예:

```python
import panther_aws_helpers

def 룰(event):
  return event['name'] == 'test-bucket'

def title(event):
  # 계정 ID에서 계정 이름을 조회합니다
  account_name = panther_aws_helpers.lookup_aws_account_name(event['accountId'])
  return 'Suspicious request made to account ' + account_name
```

### 디택션에서 헬퍼 함수에 대한 참조 제거하기

* 디택션에서 종속성을 제거하기로 결정했다면, 우리는 권장합니다 [변경 사항을 단계적으로 적용하는 것](https://help.panther.com/Detections/Detection_Features/Why_do_I_receive_rule_import_errors_after_removing_helper_functions_from_my_Panther_detection%3F).

## 공통 헬퍼

### `deep_get()`

{% hint style="warning" %}
`deep_get()` 또한 다음으로도 사용할 수 있습니다: [이벤트 객체 자체의 함수](/ko/detections/rules/python.md#deep_get). 편의를 위해, 이 전역 헬퍼 함수 대신 해당 이벤트 함수를 사용하는 것이 좋습니다.
{% endhint %}

위치: [panther\_base\_helpers](https://github.com/panther-labs/panther-analysis/blob/master/global_helpers/panther_base_helpers.py).

`deep_get()` Python 딕셔너리 내부에 중첩된 키를 반환하는 데 사용할 수 있습니다. 이 함수는 중첩된 키를 안전하게 반환하고 다음을 피하는 데 유용합니다. `AttributeError` 키가 존재하지 않을 때.

액세스하려는 키가 리스트 내부에 중첩되어 있다면, [`deep_walk()`](#deep_walk) 를 사용하세요.

#### 예시

다음 JSON에서 deep\_get 함수는 result의 값을 반환합니다.

```python
{ "outcome": { "reason": "VERIFICATION_ERROR", "result": "FAILURE" }}
```

```python
deep_get(event, "outcome", "result") == "FAILURE"
```

이는 다음에서 찾을 수 있습니다: [지리적으로 불가능한 Okta 로그인](https://github.com/panther-labs/panther-analysis/blob/cd220c87982011d4ad156c7daecd2857c358d154/rules/okta_rules/okta_geo_improbable_access.py) 디택션.

#### 기본값

`deep_get()` 선택적 `기본값` 매개변수를 받습니다. 키가 예상 위치에 없거나 해당 위치의 값이 `None`, 기본값이 반환됩니다.

```python
deep_get(event, "outcome", "nonexistent_key", default="Key Not Found") == "Key Not Found"
```

### `deep_walk()`

{% hint style="warning" %}
`deep_walk()` 또한 다음으로도 사용할 수 있습니다: [이벤트 객체 자체의 함수](/ko/detections/rules/python.md#deep_walk). 편의를 위해, 이 전역 헬퍼 함수 대신 해당 이벤트 함수를 사용하는 것이 좋습니다.
{% endhint %}

위치: [panther\_base\_helpers](https://github.com/panther-labs/panther-analysis/blob/3ecca4a198646ab6dcad0320968fe075420572a7/global_helpers/panther_base_helpers.py#L313-L370).

`deep_walk()` Python 딕셔너리 안에 깊게 중첩된 키와 연결된 값을 반환하는 데 사용할 수 있으며, 딕셔너리나 리스트를 얼마든지 포함할 수 있습니다. 이 기능은 다음 간의 핵심 차별점입니다. `deep_walk()` 그리고 [`deep_get()`](#deep_get).

\~와 마찬가지로 `deep_get()`, 이 순회를 사용하면 안전하며 어떤 예외나 오류도 방지합니다. 구조에 키가 존재하지 않으면 기본값이 반환됩니다.

#### 예시

다음 객체에서, `deep_walk()` 다음의 값을 반환합니다 `very_nested_key`:

<pre class="language-json"><code class="lang-json"><strong>{"key": {"multiple_nested_lists_with_dict": [[[{"very_nested_key": "very_nested_value"}]]]}}
</strong></code></pre>

```python
deep_walk(event, "key", "multiple_nested_lists_with_dict", "very_nested_key", default="") == "very_nested_value"
```

이는 다음에서 찾을 수 있습니다: [GCP 서비스 계정 접근 거부](https://github.com/panther-labs/panther-analysis/blob/master/rules/gcp_audit_rules/gcp_service_account_access_denied.py) 디택션.

#### 기본값

예를 들어 `deep_get()`, `deep_walk()` 선택적 `기본값` 매개변수입니다. 제공된 이벤트에 키가 없으면, 해당 키는 `None`, 또는 키가 빈 리스트이면, 대신 기본값이 반환됩니다.

위 예시를 사용하면:

```python
deep_walk(event, "key", "multiple_nested_lists_with_dict", "very_nested_nonexistent_key", default="") == ""
```

#### return\_val

와 달리 `deep_get()`, `deep_walk()` 은 세 가지 서로 다른 값 분류를 반환할 수 있습니다:

* `모든`
* `첫 번째`
* `마지막`

**`모든`**

기본적으로, `deep_walk()` 는 반환합니다 `모든` 주어진 키에 대한 값을 반환합니다. 이는 이벤트에서 키가 중복되는 경우에 유용합니다. 그러나 `모든` 에 의해 반환된 값의 수가 하나라면, 해당 값만 반환됩니다.

예:

```json
{"key": {"inner_key": [{"nested_key": "nested_value"}, {"nested_key": "nested_value2"}]}}
```

```python
deep_walk(event, "key", "inner_key", "nested_key", default="") == ['nested_value', 'nested_value2']
```

사용할 때 `모든` 를 사용하여 여러 값을 반환하면, 리스트의 요소는 다른 Python 리스트처럼 접근할 수 있습니다.

**`첫 번째`**

키에 대해 첫 번째로 발견된 값만 반환하려면, 다음을 지정하세요 `return_val="first"`.

예:

```python
deep_walk(event, "key", "inner_key", "nested_key", default="", return_val="first") == "nested_value"
```

**`마지막`**

키에 대해 마지막으로 발견된 값만 반환하려면, 다음을 지정하세요 `return_val="last"`.

예:

```python
deep_walk(event, "key", "inner_key", "nested_key", default="", return_val="last") == "nested_value2"
```

### `is_ip_in_network()`

위치: [panther\_base\_helpers](https://github.com/panther-labs/panther-analysis/blob/master/global_helpers/panther_base_helpers.py).

`is_ip_in_network()` 는 IP 주소가 IP 범위 목록 안에 있는지 확인하는 함수입니다. 이 함수는 디택션에 대한 추가적인 맥락을 위해 알려진 내부 네트워크 목록과 함께 사용할 수 있습니다.

예:

```python
SHARED_IP_SPACE = [
    "192.168.0.0/16",
]

if is_ip_in_network(event.get("ipaddr"), SHARED_IP_SPACE):
    ...
```

예시는 다음에서 찾을 수 있습니다 [OneLogin Active Login Activity](https://github.com/panther-labs/panther-analysis/blob/cd220c87982011d4ad156c7daecd2857c358d154/rules/onelogin_rules/onelogin_active_login_activity.py) 디택션.

### `pattern_match()`

위치: [panther\_base\_helpers](https://github.com/panther-labs/panther-analysis/blob/master/global_helpers/panther_base_helpers.py).

에 대한 래퍼 [fnmatch](https://docs.python.org/3/library/fnmatch.html) 기본 패턴 글롭을 위한. 정규식을 사용할 필요 없이 단순한 패턴 매칭이 필요할 때 사용할 수 있습니다.

예:

다음 JSON에서 pattern\_match() 함수는 true를 반환합니다.

```python
{ "operation": "REST.PUT.OBJECT" }
```

```python
pattern_match(event.get("operation", ""), "REST.*.OBJECT")
```

예시는 AWS S3 Access Error 디택션에서 찾을 수 있습니다.

### `pattern_match_list()`

위치: [panther\_base\_helpers](https://github.com/panther-labs/panther-analysis/blob/master/global_helpers/panther_base_helpers.py).

와 유사하게 `pattern_match()`, `pattern_match_list()` 는 문자열이 주어진 목록의 어떤 패턴과도 일치하는지 확인할 수 있습니다.

예:

다음 JSON을 사용하면 pattern\_match\_list() 함수가 true를 반환합니다.

```python
{ "userAgent": "aws-sdk-go/1.29.7 (go1.13.7; darwin; amd64) APN/1.0 HashiCorp/1.0 Terraform/0.12.24 (+https://www.terraform.io)" }
```

```python
ALLOWED_USER_AGENTS = {
    "* HashiCorp/?.0 Terraform/*",
    # 'console.ec2.amazonaws.com',
    # 'cloudformation.amazonaws.com',
}

pattern_match_list(event.get("userAgent"), ALLOWED_USER_AGENTS)
```

예시는 다음에서 찾을 수 있습니다 [AWS EC2 수동 보안 그룹 변경](https://github.com/panther-labs/panther-analysis/blob/cd220c87982011d4ad156c7daecd2857c358d154/rules/aws_cloudtrail_rules/aws_ec2_security_group_modified.py) 디택션.

### `aws_strip_role_session_id()`

위치: [panther\_aws\_helpers](https://github.com/panther-labs/panther-analysis/blob/main/global_helpers/panther_aws_helpers.py).

`aws_strip_role_session_id()` ARN에서 세션 ID를 제거합니다.

예:

다음 값이 있으면, `aws_strip_role_session_id()` 다음과 같이 반환됩니다 `arn:aws:sts::123456789012:assumed-role/demo`

```python
{ "arn": "arn:aws:sts::123456789012:assumed-role/demo/sessionName" }
```

```python
aws_strip_role_session_id(user_identity.get("arn", ""))
```

예시는 다음에서 찾을 수 있습니다 [AWS 승인되지 않은 API 호출](https://github.com/panther-labs/panther-analysis/blob/main/rules/aws_cloudtrail_rules/aws_unauthorized_api_call.py) 디택션.

### `is_base64()`

위치: [panther\_base\_helpers](https://github.com/panther-labs/panther-analysis/blob/master/global_helpers/panther_base_helpers.py).

`is_base64()` 문자열이 base64로 인코딩되었는지 확인하고, 그렇다면 디코딩된 문자열을 반환합니다. 그렇지 않으면 빈 문자열을 반환합니다.

다음에서 예시를 확인하세요 [`Crowdstrike.Base64EncodedArgs` 디택션](https://github.com/panther-labs/panther-analysis/blob/release/rules/crowdstrike_rules/crowdstrike_base64_encoded_args.py).

### `get_string_set()`

위치: [panther\_디택션\_helpers](https://pypi.org/project/panther-detection-helpers/). 다음에 대해 자세히 알아보세요 `panther_디택션_helpers` 패키지 [Python Rules 캐싱에 대한](/ko/detections/rules/python/caching.md#cache-helper-functions-in-panther_detection_helpers).

`get_string_set` 키를 기반으로 Panther가 관리하는 캐시에서 값을 가져오는 데 사용됩니다. 이는 디택션 호출 간 상태를 가져오는 데 유용합니다.

[panther-analysis에서 사용된 예시는 여기에서 확인할 수 있습니다](https://github.com/panther-labs/panther-analysis/blob/a0b6039dbe1966d29ddd80937b9a790a59ef9cfe/rules/standard_rules/impossible_travel_login.py#L105-L106).

### `put_string_set()`

위치: [panther\_디택션\_helpers](https://pypi.org/project/panther-detection-helpers/). 다음에 대해 자세히 알아보세요 `panther_디택션_helpers` 패키지 [Python Rules 캐싱에 대한](/ko/detections/rules/python/caching.md#cache-helper-functions-in-panther_detection_helpers).

`put_string_set` 키를 기반으로 Panther가 관리하는 캐시에 값을 저장하는 데 사용됩니다. 이는 디택션 호출 간 상태를 저장하는 데 유용합니다.

[panther-analysis에서 사용된 예시는 여기에서 확인할 수 있습니다](https://github.com/panther-labs/panther-analysis/blob/a0b6039dbe1966d29ddd80937b9a790a59ef9cfe/rules/standard_rules/impossible_travel_login.py#L111-L115).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.panther.com/ko/detections/rules/python/globals.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
