コンテンツにスキップ

Python 用 XDR SDK を使い始める🔗

注意

テナントのリージョンに応じて、次のリージョンまたは環境識別子を使用してください。

  • https://ctpx.secureworks.com/ には US1 または charlie または production
  • https://delta.taegis.secureworks.com/ には US2 または delta
  • https://echo.taegis.secureworks.com/ には EU または echo
  • https://foxtrot.taegis.secureworks.com/ には US3 または foxtrot
  • https://golf.taegis.secureworks.com/ には EUW1 または golf
  • https://hotel.taegis.secureworks.com/ には APSE2 または hotel
  • https://india.taegis.secureworks.com/ には APS1 または india
  • https://juliet.taegis.secureworks.com/ には APNE1 または juliet
  • https://kilo.taegis.secureworks.com/ には SAE1 または kilo
  • https://quebec.taegis.secureworks.com/ には CAC1 または quebec

注意

production は、Tenants API を使用して複数のテナントにまたがって API 呼び出しを反復実行したい子テナントを持つパートナーにとって便利です。Tenants API は charlie や US1 ではなく production 識別子を使用しますが、これにより SDK は正しいリージョンに送られます。

Python 用 Taegis SDK をインストールする🔗

Python 3.8+ がすでにインストールされていることを前提として、Python 用 Taegis SDK をインストールします。

python -m pip install taegis-sdk-python

認証🔗

インストール時に、お客様の Secureworks® Taegis™ XDR アカウントでの認証を求められます。組織で SSO 認証に登録されていない限り、これにはパスワードと MFA トークンが必要です。SSO が有効になっている場合は、デバイスコード認証リンクが表示されます。

詳細については、Python 用 Taegis SDK で認証する を参照してください。

使用例🔗

from taegis_sdk_python import GraphQLService

from pprint import pprint as pp

service = GraphQLService()

results = service.subjects.query.current_subject()

pp(results)

SDK を調べる🔗

SDK は、Python 組み込みの help を活用することを中心に構築されています。GraphQLService オブジェクト構造内の任意のオブジェクトに対して help を使用して、利用可能なものやその呼び出し方法を理解できます。help メニューは、入力タイプを判断するための優れたリソースです。各サービスは自己完結しているため、SearchRequestInput のような入力が必要な場合は、taegis_sdk_python.services.<service>.types の下にあります。

from taegis_sdk_python import GraphQLService
from taegis_sdk_python.services.alerts.types import SearchRequestInput

service = GraphQLService()

# Find available services (Service Endpoints)
help(service)
# Find available service queries (or mutations or subscriptions)
help(service.alerts.query)
help(service.alerts.mutation)
help(service.alerts.subscription)
# Reference documentation on specific endpoint
help(service.alerts.query.alerts_service_search)
# Help on an Input variable
help(SearchRequestInput)
# service
class GraphQLService(builtins.object)
 |  GraphQLService(*, environment: Optional[str] = None, tenant_id: Optional[str] = None, environments: Optional[Dict[str, str]] = None, gateway: Optional[str] = None)
...
 |  agent
 |      Events Service Endpoint.
 |
 |  alerts
 |      Alerts2 Service Endpoint.
 |
 |  assets
 |      Assets
...
# Alerts Query
class TaegisSDKAlertsQuery(builtins.object)
 |  TaegisS
...
 |  alerts_service_aggregate_alerts_by_severity(self, in_: 'Optional[AggregateAlertsBySeverityInputInput]' = None) -> 'AlertsAggregateResponse'
 |      Pull alert severity aggregates based on `group_by` parameters: domain, watchlist, hostname, detector, user..
 |
 |  alerts_service_alerts_dashboard_triage(self, in_: 'Optional[TriageDashboardInputInput]' = None) -> 'TriageDashboardOutput'
 |      None.
 |
 |  alerts_service_poll(self, in_: 'Optional[PollRequestInput]' = None) -> 'AlertsResponse'
 |      Poll for results for a specific `search
...
# SearchRequestInput
class SearchRequestInput(builtins.object)
 |  SearchRequestInput(cql_query: Optional[str] = None, offset: Optional[int] = None, limit: Optional[int] = None) -> None
...

注意: 出力は冗長さのために切り詰められています。

コンテキストマネージャー🔗

サービスオブジェクトは、API 呼び出し時にデフォルト値を一時的に上書きするのに役立つコンテキストマネージャーでもあります。これには、environment、tenant_id、output、access_token などのフィールドを含めることができます。

from taegis_sdk_python import GraphQLService
from taegis_sdk_python.services.alerts.types import SearchRequestInput

service = GraphQLService()

with service(
    environment="US2",
    tenant_id="00000",
    output="""
        reason
        alerts {
            total_results
            list {
                id
                tenant_id
                metadata {
                    title
                    severity
                }
                status
            }
        }
    """,
):
    result = service.alerts.query.alerts_service_search(SearchRequestInput(
        offset=0,
        limit=10,
        cql_query="""
        FROM alert
        WHERE
            severity >= 0.6
        EARLIEST=-1d
        """
    ))

テナントコンテキストを変更する🔗

from taegis_sdk_python import GraphQLService
from taegis_sdk_python.services.investigations.types import InvestigationsV2Arguments

service = GraphQLService()

# specify the output fields, and start the service context
with service(tenant_id="00000"):
    result = service.investigations2.query.investigations_v2(InvestigationsV2Arguments(
        page=1,
        per_page=3,
        cql="WHERE deleted_at IS NOT NULL EARLIEST=-90d"
    ))
pp(result)

環境を変更する🔗

from taegis_sdk_python import GraphQLService
from taegis_sdk_python.services.investigations.types import InvestigationsV2Arguments

service = GraphQLService()

# specify the output fields, and start the service context
with service(environment="US2"):
    result = service.investigations2.query.investigations_v2(InvestigationsV2Arguments(
        page=1,
        per_page=3,
        cql="WHERE deleted_at IS NOT NULL EARLIEST=-90d"
    ))
pp(result)

既存のアクセストークンを使用する🔗

from taegis_sdk_python import GraphQLService
from taegis_sdk_python.services.investigations.types import InvestigationsV2Arguments

service = GraphQLService()

# specify the output fields, and start the service context
with service(access_token="<your access token>"):
    result = service.investigations2.query.investigations_v2(InvestigationsV2Arguments(
        page=1,
        per_page=3,
        cql="WHERE deleted_at IS NOT NULL EARLIEST=-90d"
    ))
pp(result)

GraphQL 出力を絞り込む🔗

GraphQL を使用する利点の 1 つは、返されるフィールドを定義できることです。デフォルトでは、使い始められるように GraphQL に関する知識がほとんどない、またはまったくないことを想定しているため、確認のために API 呼び出し内のすべてのフィールドを提供しています。これは、特定のアプリケーションやレポートの目的では不要な場合があります。

これを支援するために、build_output_string というユーティリティがあります。これは、戻り値の型に対して可能なすべてのフィールドを含む出力オブジェクトの文字列表現を返します。これを参照として独自のものを作成したり、不要なフィールドを削除するように変更したりできます。

from taegis_sdk_python import build_output_string
from taegis_sdk_python.services.alerts.types import AlertsResponse

print(build_output_string(AlertsResponse))
reason search_id status alerts { previous_offset total_parts list { reference_details { reference {
description url type } } parent_tenant_id entities { entities relationships { relationship to_entity
from_entity type } } sensor_types suppression_rules { id version } resolution_history { timestamp {
nanos seconds } user_id status num_alerts_affected id reason } enrichment_details {
business_email_compromise { user_name source_address_geo_summary { country { confidence iso_code
geoname_id code } city { confidence locale_names { record { value key } } geoname_id name } location {
timezone latitude longitude us_metro_code radius metro_code gmt_offset } asn { autonomous_system_no
autonomous_system_org } continent { code geoname_id } } source_address }
...

注意: 出力は冗長さのために切り詰められています。

サービスオブジェクトは、新しい GraphQL 出力フィールドを割り当てた output を指定してコンテキストマネージャーとして呼び出すことができます。同じオブジェクトが返されますが、定義されていないフィールドには None 値が割り当てられます。

from taegis_sdk_python import GraphQLService
from taegis_sdk_python.services.alerts.types import SearchRequestInput

from pprint import pprint as pp

service = GraphQLService()
with service(output="search_id alerts { list { id status metadata { title severity confidence } } }")
    results = service.alerts.query.alerts_service_search(
        SearchRequestInput(
            offset=0,
            limit=10,
            cql_query="""
            FROM alert
            WHERE
                severity >= 0.6
            EARLIEST=-1d
            """,
        )
    )
pp(results)

カスケードコンテキスト🔗

Taegis SDK for Python サービスは、カスケードコンテキストを処理できます。service コンテキストマネージャーを呼び出すたびに、スタックごとにコンテキストが上書きされます。これの主なユースケースは、コンテキスト全体を終了することなく、より大きなコンテキスト内で単一の API 呼び出しの output を変更することです。新しいレベルは、以前のコンテキスト定義を一時的に上書きし、現在のコンテキストを終了すると以前の定義が再び利用可能になります。

注意: 次の例は、コンテキストマネージャーを説明する目的のものです。API 呼び出しの組み合わせは、一緒に使用しても有用ではない場合があります。

from taegis_sdk_python import GraphQLService
from taegis_sdk_python.services.investigations2.types import InvestigationsV2Arguments
from taegis_sdk_python.services.alerts.types import SearchRequestInput

service = GraphQLService()

with service(environment="US2", tenant_id="00000"):

    # Context
    #    environment: US2
    #    tenant_id: 00000

    with service(output="investigations { id alertsEvidence { id } }")

        # Context
        #    environment: US2
        #    tenant_id: 00000
        #    output: investigations { id alertsEvidence { id } }

        investigation_results = service.investigations2.query.investigations_v2(InvestigationsV2Arguments(
            page=1,
            per_page=3,
            cql="WHERE deleted_at IS NOT NULL EARLIEST=-90d"
        ))

    # Context
    #    environment: US2
    #    tenant_id: 00000

    alert_ids = [
        alert.id
        result for result in investigation_results
        alert for alert in result.alerts_evidence
    ]

    with service(output="alerts { list { id metadata { title } status } }"):

        # Context
        #    environment: US2
        #    tenant_id: 00000
        #    output: alerts { list { id metadata { title } status } }

        alert_results = service.alerts.query.alerts_search_search(SearchRequestInput(
            offset=0,
            limit=10000,
            cql_query=f"FROM alert WHERE resource_id IN ('{'\',\''.join(alert_ids)]}')"
        ))

    # Context
    #    environment: US2
    #    tenant_id: 00000

    # may be useful for users/applications that have access to a parent/child tenant relationship
    with service(tenant_id="00001", output="alerts { list { id metadata { title } status } }"):

        # Context
        #    environment: US2
        #    tenant_id: 00001
        #    output: alerts { list { id metadata { title } status } }

        alert_results = service.alerts.query.alerts_search_search(SearchRequestInput(
            offset=0,
            limit=10000,
            cql_query=f"FROM alert WHERE resource_id IN ('{'\',\''.join(alert_ids)]}')"
        ))

        with service(environment="US1", output="email"):

            # Context
            #    environment: US1
            #    tenant_id: 00001
            #    output: email

            user = service.users.query.current_tdruser()

        # Context
        #    environment: US2
        #    tenant_id: 00001
        #    output: alerts { list { id metadata { title } status } }

    # Context
    #    environment: US2
    #    tenant_id: 00000

# Context is now completely cleared

任意のクエリ🔗

提供されているメソッドとは異なる API 呼び出しを実行したい場合や、SDK がサポートしていない API 呼び出しを実行したい場合は、独自の query/mutation/subscription を作成できます。特定のサービスは異なる設定になっている場合があるため、利用可能な場合は、クエリ対象にしたいサービスエンドポイントを使用することを推奨します。

  • execute_query
  • execute_mutation
  • execute_subscription
from taegis_sdk_python import GraphQLService

from pprint import pprint as pp

service = GraphQLService()

results = service.alerts.execute_query(
    endpoint="alertsServiceSearch",
    variables={
        "in": {
            "limit": 3,
            "offset": 0,
            "cql_query": """
            FROM alert
            WHERE
                severity >= 0.6
            EARLIEST=-1d
            """
        }
    },
    output="""
        search_id
        alerts {
            list {
                id
                tenant_id
                metadata {
                    title
                    severity
                }
                status
            }
        }
    """
)
pp(results)

任意の Mutation🔗

results = service.core.execute_mutation(
    "createInvestigation",
    variables={
        "investigation": {
            "description": "SDK Test Investigation",
            "key_findings": "This is a test.",
            "priority": 1
        }
    },
    output="""
    id
    created_at
    created_by_user {
        id
        given_name
        family_name
    }
    description
    key_findings
    """
)
print(results)

生のクエリ🔗

独自の生の GraphQL 文字列を実行することもできます。これにより最も高い柔軟性が得られますが、ガードレールは最も少なくなります。

  • execute
  • subscribe
from taegis_sdk_python import GraphQLService

from pprint import pprint as pp

service = GraphQLService()

results = service.investigations.execute("""
    query investigationsStatusCount
    {
        investigationsStatusCount
        {
            open closed active awaiting_action suspended total
        }
    }
""")
pp(results)

ヘルパー🔗

build_output_string ユーティリティ🔗

build_output_string というユーティリティがあります。これは、戻り値の型に対して可能なすべてのフィールドを含む出力オブジェクトの文字列表現を返します。

from taegis_sdk_python import build_output_string
from taegis_sdk_python.services.alerts.types import AlertsResponse

print(build_output_string(AlertsResponse))

_build_output_query ユーティリティ🔗

完全な GraphQL クエリ文字列の作成を支援する機能が必要な場合は、サービスエンドポイント _build_output_query を呼び出して支援を受けることができます。これはスキーマからクエリを構築するため、正しいサービスエンドポイントからスキーマを取得していることを確認してください。

from taegis_sdk_python import GraphQLService, build_output_string
from taegis_sdk_python.services.investigations.types import InvestigationStatusCountResponse

service = GraphQLService()
schema = service.alerts.get_sync_schema()

print(service.alerts._build_output_query(
    operation_type="query",
    endpoint="investigationsStatusCount",
    graphql_field=schema.query_type.fields.get("investigationsStatusCount"),
    output=build_output_string(InvestigationStatusCountResponse)
))

非推奨の警告🔗

非推奨の入力フィールド、出力フィールド、およびエンドポイントは、警告をログに記録するよう設定されています。詳細については、Python 用 Taegis SDK における非推奨 を参照してください。

例:

GraphQL Query `allInvestigations` is deprecated: 'replaced by investigationsSearch'
Output field `activity_logs` is deprecated: 'Not Supported - Use audit logs', removing from default output...
Output field `assignee` is deprecated: 'No longer supported', removing from default output...

スキーマの取得🔗

Taegis SDK for Python は、スキーマを 5 分間キャッシュします。取得されたスキーマは、クエリ文字列の生成やエラー処理を支援するために使用されます。時間に敏感なアプリケーションや API 呼び出し数が多いアプリケーションでは、この機能により、検証やエラーのためにスキーマを取得するのに必要な時間を平準化できます。これは、GraphQLService の schema_expiry(分単位)属性で設定できます。スキーマはサービスごとに取得されます(alerts は investigations とは別にスキーマをキャッシュします)。有効期限は、サービスへの最初の API 呼び出し時にコンテキストマネージャーを介してサービスごとに設定できます。

注意

有効期限を長くすると、エラー処理に影響する場合があります。キャッシュと API 呼び出しの間にサーバー側のスキーマが破壊的変更を伴って更新された場合、SDK は展開されているスキーマと整合しないクエリ文字列を構築して検証する可能性があります。

from taegis_sdk_python import GraphQLService

# all schemas will be cached for 15 minutes
service = GraphQLService(schema_expiry=15)

with service(schema_expiry=30): # users schema will now be cached for 30 minutes
    results = service.users.query.current_tdruser()

スキーマは、service.<service>.clear_schema() メソッドを使用してサービスごとにクリアできます。

from taegis_sdk_python import GraphQLService

service = GraphQLService()

user = service.users.query.current_tdruser() # schema will be cached for the users service

service.users.clear_schema()  # local schema will be cleared and re-fetched on next call

サブスクリプションメッセージサイズ🔗

サブスクリプションの最大メッセージサイズは、すべてのサブスクリプションに対して max_message_size パラメーターで設定できます。個別の呼び出しは、コンテキストマネージャーを介して変更できます。デフォルトは 0 に設定されており、これは制限をなくすことを意味します。このオプションはサブスクリプションにのみ影響し、クエリと mutation には影響しません。

メッセージサイズに達した場合、またはそれを超えた場合は、ConnectionResetError がスローされます。

from taegis_sdk_python import GraphQLService

service = GraphQLService(max_message_size=4194304)  # sets default to 4MB

with service(max_message_size=5242880):  # sets specific API call to 5MB
    options = EventQueryOptions(
        timestamp_ascending=True,
        page_size=1000,
        max_rows=1000,
        skip_cache=True,
        aggregation_off=False,
    )
    results = service.events.subscription.event_query("FROM process EARLIEST=-1d", options=options)

try:
    results = service.events.subscription.event_query("FROM process EARLIEST=-1d", options=options)
except ConnectionResetError as exc:
    # handle error