> 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는 이 패턴을 `전역` 분석 유형으로 지원합니다. Panther는 여러 개의 [내장 전역 헬퍼](#built-in-globals), 그리고 또한 [직접 만든 사용자 지정 전역도 추가할 수 있습니다](#adding-custom-globals). 특정한 [일반 헬퍼](#common-helpers) 아래에서.

{% hint style="warning" %}
전역 헬퍼는 자주 변경되는 용도에는 가장 적합하지 않습니다. 만약 당신이 *그렇다면* 자주 변경해야 한다면, 대신 [Custom Lookup Tables](/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 Caching](/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의 왼쪽 탐색 표시줄에서 클릭하세요 **디택션,** 그런 다음 **Helpers** 탭을 클릭하세요.

<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 콘솔" %}
Panther Console에서 새 전역을 만들려면:

1. Panther Console의 왼쪽 탐색 표시줄에서 **디택션**.
2. 를 클릭하세요. **Helpers** 탭을 클릭하세요.
3. 오른쪽 상단 모서리에서 다음을 클릭하세요 **Create New**.\
   ![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
Description: 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 '계정에 대한 의심스러운 요청이 발생함 ' + 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()` 을 반환합니다 `모든` 주어진 키의 값들입니다. 이는 이벤트에서 키가 중복되는 경우에 유용합니다. 그러나, `모든` 가 1이면, 해당 값만 반환됩니다.

예를 들면:

```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 Caching](/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 Caching](/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.
