# Импорт отчетов с помощью AWS Lambda Function в AWS Security Hub

Для этого используется функция AWS Lambda, написанная на языке Python. Функция извлекает API-ключ из AWS Secrets Manager, формирует запрос с данными сканирования и отправляет его на указанный адрес Security Center.

## Шаг 1: Подготовка к интеграции

1. AWS Lambda: Убедитесь, что у вас настроена и функционирует функция AWS Lambda
2. AWS Secrets Manager: Создайте секрет в AWS Secrets Manager, содержащий API-ключ для доступа к Security Center. Убедитесь, что у вас есть права на чтение этого секрета

## Шаг 2: Создание функции AWS Lambda

1. Перейдите в консоль AWS Lambda
2. Создайте новую лямбда-функцию согласно вашим требованиям
3. Убедитесь, что функция имеет необходимые разрешения для доступа к Secrets Manager и выполнения HTTP-запросов.
4. Вставьте код в редактор кода вашей функции:

```python
import json
import boto3
import urllib.request
import urllib3


def lambda_handler(event, context):
    
    # Fetch Security Center API key from AWS Secrets Manager
    client_sm = boto3.client('secretsmanager')
    security_center_secret_raw = client_sm.get_secret_value(
        SecretId="<secret_name>"
    )
    security_center_api_json = json.loads(security_center_secret_raw["SecretString"])
    security_center_api_token = "Token " + security_center_api_json['key']
    
    while True:
        try:
            url = 'https://<security_center_address>/api/v1/scan/import/'
            body = {
                "file": ("event.json", json.dumps(event)),
                "product_name": "AWS",
                "product_type": "AWS",
                "scanner_name": "AWS Security Hub Scan"
            }
            data, header = urllib3.encode_multipart_formdata(body)
            r = urllib.request.Request(url, data=data)
            r.add_header('Authorization', security_center_api_token)
            r.add_header('Content-Type', header)
            response = urllib.request.urlopen(r)
            print(response.getcode())
        except Exception as e:
            raise e
        break
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }
```

Замените "***\<secret\_name>***" на имя секрета в AWS Secrets Manager, содержащего ваш API-ключ для Security Center

Замените "**\<security\_center*****\_address>***" адресом вашего Security Center

5. Сохраните изменения, внесенные в функцию

## Шаг 3: Запустите функцию

1. В разделе "Тест" консоли AWS Lambda создайте тестовое событие с содержимым, аналогичным вашему отчету, чтобы проверить работу функции
2. Если функция успешно прошла тестирование, опубликуйте ее

Поздравляем! Теперь ваша функция готова отправлять отчеты на Security Center


---

# Agent Instructions: 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:

```
GET https://docs.cybercodereview.ru/security-center/scanners/scanner-description/infrastructure-scanners/aws-security-hub-scan/importing-reports-via-aws-lambda-function-within-aws-security-hub.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
