

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Monitoraggio delle modifiche nei tuoi account AMS Accelerate
<a name="acc-change-record"></a>

**Importante**  
Il servizio Change Record è obsoleto a partire dal 1° luglio 2025.  
I nuovi account non possono essere inseriti nel servizio Change Record.  
Per interrogare CloudTrail i dati nei tuoi account AMS Accelerate, puoi utilizzare questi servizi:  
In AWS CloudTrail, scegli **Cronologia eventi** e filtra gli eventi utilizzando gli attributi di ricerca. Puoi utilizzare il filtro dell'intervallo di tempo e scegliere di filtrare la cronologia degli eventi per origine degli eventi, come `s3.amazon.aws.com` specificato, oppure scegliere di filtrare la cronologia degli eventi per nome utente. Per ulteriori informazioni, consulta [Lavorare con la cronologia CloudTrail degli eventi](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/view-cloudtrail-events.html).
Usa AWS CloudTrail Lake per raccogliere dati tramite query. In AWS CloudTrail scegli **Lake**, quindi scegli **Query**. Puoi creare query personalizzate, utilizzare il generatore di query o utilizzare query di esempio per raccogliere dati basati sugli eventi. Ad esempio, puoi chiedere chi ha eliminato un' EC2 istanza Amazon la settimana scorsa. Per ulteriori informazioni, consulta [Creazione di un data lake da una AWS CloudTrail fonte](https://docs.aws.amazon.com/lake-formation/latest/dg/getting-started-cloudtrail-tutorial.html) e [CloudTrailLake interrogazioni](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake-queries.html).
Crea una tabella Amazon Athena AWS CloudTrail e imposta la posizione di archiviazione come bucket Amazon S3 associato al tuo percorso. Verifica che la regione iniziale del percorso e del bucket Amazon S3 coincidano. In Amazon Athena, usa l'editor di query per eseguire le [query predefinite](#acc-cr-canned-queries) che Accelerate fornisce per l'uso con la console Athena. [Per ulteriori informazioni su come creare una tabella Athena per interrogare i log, vedere Query CloudTrail logs. AWS CloudTrail](https://docs.aws.amazon.com/athena/latest/ug/cloudtrail-logs.html)

**Topics**
+ [Visualizzazione dei record delle modifiche](#acc-cr-using)
+ [Interrogazioni predefinite](#acc-cr-canned-queries)
+ [Modificare le autorizzazioni di registrazione](#acc-cr-permissions)

AWS Managed Services ti aiuta a tenere traccia delle modifiche apportate dal team AMS Accelerate Operations e dall'automazione di AMS Accelerate fornendo un'interfaccia interrogabile utilizzando la console [Amazon Athena (Athena](https://docs.aws.amazon.com/athena/)) e la gestione dei log di AMS Accelerate.

Athena è un servizio di query interattivo che puoi utilizzare per analizzare i dati in Amazon S3 utilizzando lo Structured Query Language (SQL) standard ([vedi SQL Reference per Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/ddl-sql-reference.html)). Athena è un servizio serverless, perciò non occorre installare o gestire alcuna infrastruttura e vengono addebitati solo i costi relativi all'esecuzione delle query. AMS Accelerate crea tabelle Athena con partizioni giornaliere sui CloudTrail log e fornisce query sulla AWS regione principale e all'interno del gruppo di lavoro. **ams-change-record** Puoi scegliere una qualsiasi delle query predefinite ed eseguirle secondo necessità. Per ulteriori informazioni sui gruppi di lavoro Athena, consulta [Come](https://docs.aws.amazon.com/athena/latest/ug/user-created-workgroups.html) funzionano i gruppi di lavoro.

**Nota**  
Solo Accelerate può interrogare CloudTrail gli eventi per il tuo account Accelerate utilizzando Athena quando Accelerate [è integrato con il percorso CloudTrail dell'organizzazione](https://docs.aws.amazon.com/managedservices/latest/accelerate-guide/acc-onb-trail-choices.html), a meno che l'amministratore dell'organizzazione non abbia implementato un ruolo IAM per utilizzare Athena per interrogare e analizzare CloudTrail gli eventi nel tuo account, durante l'onboarding.

Utilizzando change record, puoi rispondere facilmente a domande come:
+ Chi (AMS Accelerate Systems o AMS Accelerate Operators) ha avuto accesso al tuo account
+ Quali modifiche sono state apportate da AMS Accelerate al tuo account
+ Quando AMS Accelerate ha apportato modifiche al tuo account
+ A chi rivolgerti per visualizzare le modifiche apportate al tuo account
+ Perché AMS Accelerate aveva bisogno di apportare le modifiche al tuo account
+ Come modificare le query per ottenere risposte a tutte quelle domande anche per eventuali modifiche non relative ad AMS

## Visualizzazione dei record delle modifiche
<a name="acc-cr-using"></a>

Per utilizzare le query Athena, accedi alla console di AWS gestione e accedi alla console Athena nella tua regione principale. AWS 

**Nota**  
Se vedi la pagina **Get Started di Amazon Athena mentre esegui uno dei passaggi, fai clic su **Inizia****. Questo potrebbe apparire anche se la tua infrastruttura Change Record è già attiva.

1. Scegli **Workgroup** dal pannello di navigazione superiore della console Athena.

1. **Scegli il **ams-change-record**gruppo di lavoro, quindi fai clic su Cambia gruppo di lavoro.**

1. Scegliete **ams-change-record-database**dalla casella **combinata Database**. **ams-change-record-database**Include la **ams-change-record-table**tabella.

1. Scegli **Query salvate** dal pannello di navigazione superiore.

1. La finestra **Interrogazioni salvate** mostra un elenco di interrogazioni fornite da AMS Accelerate, che puoi eseguire. Scegli la query che desideri eseguire dall'elenco delle **interrogazioni salvate**. Ad esempio, la query **ams\$1session\$1accesses\$1v1**.

   Per l'elenco completo delle query AMS Accelerate preimpostate, consulta. [Interrogazioni predefinite](#acc-cr-canned-queries)

1. Se necessario, modifica il filtro **datetime** nella casella dell'editor di query; per impostazione predefinita, la query controlla solo le modifiche dell'ultimo giorno.

1. Scegli **Esegui query**.

## Interrogazioni predefinite
<a name="acc-cr-canned-queries"></a>

AMS Accelerate fornisce diverse query predefinite che è possibile utilizzare all'interno della console Athena. Le interrogazioni predefinite sono elencate nelle seguenti tabelle.

**Nota**  
Tutte le query accettano l'**intervallo di data** e ora come filtro opzionale; per impostazione predefinita, tutte le query vengono eseguite nelle ultime 24 ore. Per l'input previsto, vedere la seguente sottosezione,. [Modifica del filtro datetime nelle query](#acc-cr-canned-queries-mod-timestamp)
Gli input dei parametri che è possibile o necessario modificare vengono visualizzati nella query come nel caso delle parentesi *<PARAMETER\$1NAME>* angolari. Sostituite il segnaposto **e** le parentesi angolari con il valore del parametro.
Tutti i filtri sono opzionali. Nelle query, alcuni filtri opzionali sono commentati con un doppio trattino (--) all'inizio della riga. Tutte le query verranno eseguite senza di essi, con parametri predefiniti. Se desideri specificare i valori dei parametri per questi filtri opzionali, rimuovi il doppio trattino (--) all'inizio della riga e sostituisci il parametro come desideri.
Tutte le interrogazioni restituiscono `IAM PincipalId` e `IAM SessionId` negli output
Il costo calcolato per l'esecuzione di una query dipende dal numero di CloudTrail log generati per l'account. Per calcolare il costo, utilizza il calcolatore dei [prezzi di AWS Athena](https://aws.amazon.com/athena/pricing/).


**Query predefinite**  

| Scopo/descrizione | Input | Output | 
| --- | --- | --- | 
| **Nome della query:** `ams\$1access\$1session\$1query\$1v1` | 
| Tracciamento delle sessioni di accesso con AMS Fornisce informazioni su una sessione di accesso AMS Accelerate specifica. La query accetta l'IAM Principal ID come filtro opzionale e restituisce l'ora dell'evento, le esigenze aziendali di accesso all'account, il richiedente e così via. Puoi filtrare in base a uno specifico IAM Principal ID decommentando la riga e sostituendo il segnaposto *IAM PrincipalId* con un ID specifico nell'editor di query. Puoi anche elencare le sessioni di accesso non AMS rimuovendo la riga del filtro **useragent** nella clausola WHERE della query. | (Facoltativo)`IAM PrincipalId`: l'identificatore principale IAM della risorsa a cui sta tentando di accedere. Il formato è*UNIQUE\$1IDENTIFIER*:*RESOURCE\$1NAME*. Per i dettagli, vedere gli [identificatori univoci](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids). Puoi eseguire la query senza questo filtro per determinare lo IAM PrincipalId esatto con cui desideri filtrare. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/managedservices/latest/accelerate-guide/acc-change-record.html) | 
| Nome della query**:** `ams\$1events\$1query\$1v1` | 
| Tieni traccia di tutte le azioni di mutazione eseguite da AMS Accelerate Restituisce tutte le azioni di scrittura eseguite sull'account utilizzando quel filtro di ruolo AMS Accelerate. Puoi anche tenere traccia delle azioni di mutazione eseguite da ruoli non AMS rimuovendo le righe del filtro **useridentity.arn** dalla clausola WHERE della query. | (Facoltativo) **Solo intervallo di data/ora.** Per informazioni, consulta [Modifica del filtro datetime nelle query](#acc-cr-canned-queries-mod-timestamp). | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/managedservices/latest/accelerate-guide/acc-change-record.html) | 
| **Nome della query**: `ams\$1instance\$1access\$1sessions\$1query\$1v1` | 
| Tieni traccia degli accessi alle istanze tramite AMS Accelerate Restituisce un elenco di accessi alle istanze AMS Accelerate; ogni record include l'ora dell'evento, la regione dell'evento, l'ID dell'istanza, l'ID principale IAM, l'ID della sessione IAM, l'ID della sessione SSM. Puoi utilizzare l'IAM Principal ID per ottenere maggiori dettagli sulle esigenze aziendali di accesso all'istanza utilizzando la query `ams_access_sessions_query_v1` Athena. Puoi utilizzare l'ID di sessione SSM per ottenere maggiori dettagli sulla sessione di accesso all'istanza, tra cui l'ora di inizio e di fine della sessione, i dettagli del registro e l'utilizzo della console di AWS Session Manager nella regione dell' AWS istanza. Gli utenti possono anche elencare gli accessi alle istanze non AMS rimuovendo la riga del filtro **useridentity** nella clausola WHERE della query. | Solo `datetime range`. Per informazioni, consulta [Modifica del filtro datetime nelle query](#acc-cr-canned-queries-mod-timestamp). | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/managedservices/latest/accelerate-guide/acc-change-record.html) | 
| **Nome della query**: `ams\$1privilege\$1escalation\$1events\$1query\$1v1` | 
| Tieni traccia degli eventi di autorizzazione (escalation) per utenti AMS e non AMS Fornisce un elenco di eventi che possono portare direttamente o potenzialmente a un'escalation dei privilegi. La query viene ActionedBy accettata come filtro opzionale e restituisce EventName, EventId EventTime, e così via. Vengono inoltre restituiti tutti i campi associati all'evento. I campi sono vuoti se non applicabili per quell'evento. Per impostazione predefinita, il ActionedBy filtro è disabilitato; per attivarlo, rimuovi «--" da quella riga. Per impostazione predefinita, il ActionedBy filtro è disabilitato (mostrerà gli eventi di escalation dei privilegi di tutti gli utenti). Per mostrare gli eventi per un particolare utente o ruolo, rimuovi il doppio trattino (--) dalla riga del filtro **useridentity** nella clausola WHERE e sostituisci il segnaposto *ACTIONEDBY\$1PUT\$1USER\$1NAME\$1HERE* con un nome utente o di ruolo IAM. Puoi eseguire la query senza il filtro per determinare l'utente esatto con cui desideri filtrare. | (Facoltativo)`ACTIONEDBY_PUT_USER_NAME`: nome utente per l'utente ActionedBy. Può trattarsi di un utente o di un ruolo IAM. Ad esempio,. ams-access-admin (Facoltativo)`datetime range`. Per informazioni, consulta [Modifica del filtro datetime nelle query](#acc-cr-canned-queries-mod-timestamp). | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/managedservices/latest/accelerate-guide/acc-change-record.html) | 
| **Nome della query**: `ams\$1resource\$1events\$1query\$1v1` | 
| Tieni traccia degli eventi di scrittura per risorse specifiche (AMS o non AMS) Fornisce un elenco di eventi eseguiti su una risorsa specifica. La query accetta l'ID della risorsa come parte dei filtri (sostituisci il segnaposto *RESOURCE\$1INFO* nella clausola WHERE della query) e restituisce tutte le azioni di scrittura eseguite su quella risorsa. | (Obbligatorio)`RESOURCE_INFO`: l'identificatore di risorsa può essere un ID per qualsiasi risorsa AWS nell'account. Non confonderlo con una risorsa. ARNs Ad esempio, un ID di istanza per un' EC2 istanza, un nome di tabella per una tabella DynamoDB logGroupName , per CloudWatch un registro, ecc. (Facoltativo). `datetime range` Per informazioni, consulta [Modifica del filtro datetime nelle query](#acc-cr-canned-queries-mod-timestamp). | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/managedservices/latest/accelerate-guide/acc-change-record.html) | 
| **Nome della query**: `ams\$1session\$1events\$1query\$1v1` | 
| Tieni traccia delle azioni di scrittura eseguite da AMS Accelerate durante una sessione specifica Fornisce un elenco di eventi eseguiti in una sessione specifica. La query accetta l'ID principale IAM come parte dei filtri (sostituisce il segnaposto *PRINCIPAL\$1ID* nella clausola WHERE della query) e restituisce tutte le azioni di scrittura eseguite su quella risorsa. | (Obbligatorio)`PRINCIPAL_ID`: ID principale per la sessione. Il formato è*UNIQUE\$1IDENTIFIER*:*RESOURCE\$1NAME*. Per i dettagli, vedere gli [identificatori univoci](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids). Puoi eseguire la query «ams\$1session\$1ids\$1by\$1requester\$1v1" per ottenere l'elenco degli IAM Principal per un richiedente. IDs Puoi anche eseguire la query senza questo filtro per determinare l'esatto IAM con cui desideri filtrare. PrincipalId  (Facoltativo)`datetime range`. Per informazioni, consulta [Modifica del filtro datetime nelle query](#acc-cr-canned-queries-mod-timestamp). | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/managedservices/latest/accelerate-guide/acc-change-record.html) | 
| **Nome della query**: `ams\$1session\$1ids\$1by\$1requester\$1v1` | 
| Tieni traccia di IAM Principal/Session IDs per un richiedente specifico. La query accetta «richiedente» (sostituisce il segnaposto *Requester* nella clausola WHERE della query) e restituisce tutti gli ID principali IAM di quel richiedente durante l'intervallo di tempo specificato.  | (Obbligatorio)`Requester`: ID operatore che accede all'account (ad esempio: alias di un operatore) o sistema di automazione che accede all'account (ad esempio:,, ecc.). OsConfiguration AlarmManager (Facoltativo). `datetime range` Per informazioni, consulta [Modifica del filtro datetime nelle query](#acc-cr-canned-queries-mod-timestamp). | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/managedservices/latest/accelerate-guide/acc-change-record.html) | 

### Modifica del filtro datetime nelle query
<a name="acc-cr-canned-queries-mod-timestamp"></a>

Tutte le query accettano l'intervallo di **data e ora** come filtro opzionale. Per impostazione predefinita, tutte le query vengono eseguite nell'ultimo giorno.

Il formato utilizzato per il campo **datetime** è yyyy/MM/dd (ad esempio: 01/01/2021). Ricorda che memorizza solo la data e non l'intero timestamp. **Per l'intero timestamp, usa il campo **eventime**, che memorizza il timestamp nel formato ISO 8601 yyyy-MM-dd **T HH:mm:ss Z (ad esempio: 2021-01-01T 23:59:59** Z).** Tuttavia, poiché la tabella è [partizionata nel campo datetime, dovrai passare sia il filtro datetime che il filtro eventtime alla query](https://docs.aws.amazon.com/athena/latest/ug/partitions.html). Fare riferimento agli esempi riportati di seguito.

**Nota**  
Per vedere tutti i modi accettati per modificare l'intervallo, consulta l'ultima [documentazione delle funzioni Presto](https://docs.aws.amazon.com/athena/latest/ug/presto-functions.html) basata sulla versione del motore Athena attualmente utilizzata per le **funzioni e gli operatori di data e ora** per vedere tutti i modi accettati per modificare l'intervallo.

**Livello di data: Ultimo giorno o ultime 24 ore (impostazione predefinita)** Esempio: se CURRENT\$1DATE='2021/01/01', il filtro sottrarrà un giorno dalla data corrente e la formatterà come datetime > '2020/12/31'

```
datetime > date_format(date_add('day', - 1, CURRENT_DATE), '%Y/%m/%d')
```

**Livello di data: esempio degli ultimi 2** mesi:

```
datetime > date_format(date_add('month', - 2, CURRENT_DATE), '%Y/%m/%d')
```

**Livello di data: esempio tra 2 date**:

```
datetime > '2021/01/01'
      AND
      datetime < '2021/01/10'
```

**Livello di timestamp: esempio delle ultime 12 ore**:

Suddividi i dati in modo che durino 1 giorno, quindi filtra tutti gli eventi delle ultime 12 ore

```
datetime > date_format(date_add('day', - 1, CURRENT_DATE), '%Y/%m/%d')
      AND
      eventtime > date_format(date_add('hour', - 12, CURRENT_TIMESTAMP), '%Y-%m-%dT%H:%i:%sZ')
```

**Livello di timestamp: tra 2 timestamp. Esempio:**

Ricevi eventi tra le 12:00 del 1 gennaio 2021 e le 15:00 del 10 gennaio 2021.

```
datetime > '2021/01/01' AND datetime < '2021/01/10'
      AND
      eventtime > '2021-01-01T12:00:00Z' AND eventtime < '2021-01-10T15:00:00Z'
```

### Esempi di query predefiniti
<a name="acc-default-query-examples"></a>

#### `ams_access_session_query_v1`
<a name="ams-access-session-query-v1"></a>

```
Name: ams_access_session_query_v1

Description: >-
   The query provides more information on specific AMS access session.
   The query accepts IAM Principal Id as an optional filter and returns event time, business need for accessing the account, requester, ... etc.
   By default; the query filter last day events only, the user can change the datetime filter to search for more wide time range.
   By default; the IAM PrincipalId filter is disabled. To enable it, remove "-- " from that line.

AthenaQueryString: |-
   /*
     The query provides list of AMS access sessions during specific time range.
     The query accepts IAM Principal Id as an optional filter and returns event time, business need for accessing the account, requester, ... etc.

     By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

     By default; the IAM Principal ID filter is disabled (it shows access sessions for all IAM principals).
     If you want to only show access sessions for a particular IAM principal ID, remove the double-dash (--) from
     the "IAM Principal ID" filter line in the WHERE clause of the query, and replace the placeholder "<IAM PrincipalId>" with the specific ID that you want.
     You can run the query without the filter to determine the exact IAM PrincipalId you want to filter with.

     By default; the query only shows AMS access sessions. If you also want to show non-AMS access sessions,
     remove the "useragent" filter in the WHERE clause of the query.

     For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
   */

   SELECT
      json_extract_scalar(responseelements, '$.assumedRoleUser.assumedRoleId') AS "IAM PrincipalId",
      json_extract_scalar(responseelements, '$.credentials.accessKeyId') AS "IAM SessionId",
      eventtime AS "EventTime",
      eventname AS "EventName",
      awsregion AS "EventRegion",
      eventid AS "EventId",
      json_extract_scalar(requestparameters, '$.tags[0].value') AS "BusinessNeed",
      json_extract_scalar(requestparameters, '$.tags[1].value') AS "BusinessNeedType",
      json_extract_scalar(requestparameters, '$.tags[2].value') AS "Requester",
      json_extract_scalar(requestparameters, '$.tags[3].value') AS "AccessRequestType"
   FROM
       "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate
   WHERE
      datetime > date_format(date_add('day', - 1, CURRENT_DATE), '%Y/%m/%d')
      AND eventname = 'AssumeRole'
      AND useragent = 'access.managedservices.amazonaws.com'
      -- AND  json_extract_scalar(responseelements, '$.assumedRoleUser.assumedRoleId') = '<IAM PrincipalId>'
   ORDER BY eventtime

InsightsQueryString: |-
   # The query provides list of AMS access sessions during specific time range.
   # The query accepts IAM Principal Id as an optional filter and returns event time, business need for accessing the account, requester, ... etc.
   #
   # By default; the IAM Principal ID filter is disabled (it shows access sessions for all IAM principals).
   # If you want to only show access sessions for a particular IAM principal ID, remove the # (#) from
   # the "IAM Principal ID" filter of the query, and replace the placeholder "<IAM PrincipalId>" with the specific ID that you want.
   # You can run the query without the filter to determine the exact IAM PrincipalId you want to filter with.
   #
   # By default; the query only shows AMS access sessions. If you also want to show non-AMS access sessions,
   # remove the "useragent" filter from the query.
   #
   # For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries

   filter eventName="AssumeRole" AND userAgent="access.managedservices.amazonaws.com"
   # | filter responseElements.assumedRoleUser.assumedRoleId= "<IAM PrincipalId>"
   | sort eventTime desc
   | fields
      responseElements.assumedRoleUser.assumedRoleId as IAMPrincipalId,
      responseElements.credentials.accessKeyId as IAMSessionId,
      eventTime as EventTime,
      eventName as EventName,
      awsRegion as EventRegion,
      eventID as EventId,
      requestParameters.tags.0.value as BusinessNeed,
      requestParameters.tags.1.value as BusinessNeedType,
      requestParameters.tags.2.value as Requester,
      requestParameters.tags.3.value as AccessRequestType
```

#### `ams_events_query_v1`
<a name="ams-events-query-v1"></a>

```
ams_events_query_v1.yaml
/*
  The query provides list of events to track write actions for all AMS changes.
  The query returns all write actions done on the account using that AMS role filter.

  By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

  You can also track mutating actions done by non-AMS roles by removing the "useridentity.arn" filter lines from the WHERE clause of the query.

  For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
*/

SELECT
   useridentity.principalId AS "IAM PrincipalId",
   useridentity.accesskeyid AS "IAM SessionId",
   useridentity.accountid AS "AccountId",
   useridentity.arn AS "RoleArn",
   eventid AS "EventId",
   eventname AS "EventName",
   awsregion AS "EventRegion",
   eventsource AS "EventService",
   eventtime AS "EventTime",
   requestparameters As "RequestParameters",
   responseelements AS "ResponseElements",
   useragent AS "UserAgent"
FROM
   "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate
WHERE
   readonly <> 'true'
   AND
   (
      LOWER(useridentity.arn) LIKE '%/ams%'
      OR LOWER(useridentity.arn) LIKE '%/customer_ssm_automation_role%'
   )
ORDER BY eventtime
```

#### `ams_instance_access_sessions_query_v1`
<a name="ams-instance-access-sessions-query-v1"></a>

```
ams_instance_access_sessions_query_v1
/*
  The query provides list of AMS Instance accesses during specific time range.

  The query returns the list of AMS instance accesses; every record includes the event time, the event AWS Region, the instance ID, the IAM session ID, and the SSM session ID.
  You can use the IAM Principal ID to get more details on the business need for accessing the instance by using ams_access_session_query_v1 athena query.
  You can use the SSM session ID to get more details on the instance access session, including the start and end time of the session and log details, using the AWS Session Manager Console in the instance's AWS Region.

  You can also list non-AMS instance accesses by removing the "useridentity" filter line in the WHERE clause of the query.

  By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

  For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
*/

SELECT
   useridentity.principalId AS "IAM PrincipalId",
   useridentity.accesskeyid AS "IAM SessionId",
   json_extract_scalar(requestparameters, '$.target') AS "InstanceId",
   json_extract_scalar(responseelements, '$.sessionId') AS "SSM SessionId",
   eventname AS "EventName",
   awsregion AS "EventRegion",
   eventid AS "EventId",
   eventsource AS "EventService",
   eventtime AS "EventTime" 
FROM
   "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate
WHERE
   useridentity.sessionContext.sessionIssuer.arn like '%/ams_%' 
   AND eventname = 'StartSession' 
ORDER BY eventtime
```

#### `ams_privilege_escalation_events_query_v1`
<a name="ams-privilege-escalation-events-query-v1"></a>

```
ams_privilege_escalation_events_query_v1.yaml
/*
  The query provides list of events that can directly or potentially lead to a privilege escalation.

  The query accepts ActionedBy as an optional filter and returns EventName, EventId, EventTime, ... etc.
  All fields associated with the event are also returned. Some fields are blank if not applicable for that event.
  You can use the IAM Session ID to get more details about events happened in that session by using ams_session_events_query_v1 query.

  By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

  By default, the ActionedBy filter is disabled (it shows privilege escalation events from all users).
  To show events for a particular user or role, remove the double-dash (--) from the useridentity filter line in the WHERE clause of the query
  and replace the placeholder "<ACTIONEDBY_PUT_USER_NAME_HERE>" with an IAM user or role name.
  You can run the query without the filter to determine the exact user you want to filter with.

  For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
*/

SELECT
   useridentity.principalId AS "IAM PrincipalId",
   useridentity.accesskeyid AS "IAM SessionId",
   useridentity.accountid AS "AccountId",
   reverse(split_part(reverse(useridentity.arn), ':', 1)) AS "ActionedBy",
   eventname AS "EventName",
   awsregion AS "EventRegion",
   eventid AS "EventId",
   eventtime AS "EventTime",
   json_extract_scalar(requestparameters, '$.userName') AS "UserName",
   json_extract_scalar(requestparameters, '$.roleName') AS "RoleName",
   json_extract_scalar(requestparameters, '$.groupName') AS "GroupName",
   json_extract_scalar(requestparameters, '$.policyArn') AS "PolicyArn",
   json_extract_scalar(requestparameters, '$.policyName') AS "PolicyName",
   json_extract_scalar(requestparameters, '$.permissionsBoundary') AS "PermissionsBoundary",
   json_extract_scalar(requestparameters, '$.instanceProfileName') AS "InstanceProfileName",
   json_extract_scalar(requestparameters, '$.openIDConnectProviderArn') AS "OpenIDConnectProviderArn",
   json_extract_scalar(requestparameters, '$.serialNumber') AS "SerialNumber",
   json_extract_scalar(requestparameters, '$.serverCertificateName') AS "ServerCertificateName",
   json_extract_scalar(requestparameters, '$.accessKeyId') AS "AccessKeyId",
   json_extract_scalar(requestparameters, '$.certificateId') AS "CertificateId",
   json_extract_scalar(requestparameters, '$.newUserName') AS "NewUserName",
   json_extract_scalar(requestparameters, '$.newGroupName') AS "NewGroupName",
   json_extract_scalar(requestparameters, '$.newServerCertificateName') AS "NewServerCertificateName",
   json_extract_scalar(requestparameters, '$.name') AS "SAMLProviderName",
   json_extract_scalar(requestparameters, '$.sAMLProviderArn') AS "SAMLProviderArn",
   json_extract_scalar(requestparameters, '$.sSHPublicKeyId') AS "SSHPublicKeyId",
   json_extract_scalar(requestparameters, '$.virtualMFADeviceName') AS "VirtualMFADeviceName"
FROM
   "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate
WHERE
   (
     -- More event names can be found at https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html
     eventname LIKE 'Add%' OR
     eventname LIKE 'Attach%' OR
     eventname LIKE 'Delete%' AND eventname != 'DeleteAccountAlias' OR
     eventname LIKE 'Detach%' OR
     eventname LIKE 'Create%' AND eventname != 'CreateAccountAlias' OR
     eventname LIKE 'Put%' OR
     eventname LIKE 'Remove%' OR
     eventname LIKE 'Update%' OR
     eventname LIKE 'Upload%' OR
     eventname = 'DeactivateMFADevice' OR
     eventname = 'EnableMFADevice' OR
     eventname = 'ResetServiceSpecificCredential' OR
     eventname = 'SetDefaultPolicyVersion'
   )
   AND eventsource = 'iam.amazonaws.com'
ORDER BY eventtime
```

#### `ams_resource_events_query_v1`
<a name="ams-resource-events-query-v1"></a>

```
Name: ams_resource_events_query_v1

Description: >-
   The query provides list of events done on specific resource.
   The query accepts resource id as part of the filters, and return all write actions done on that resource.
   By default; the query list the accesses for last day, the user can change the time range by changing the datetime filter.

AthenaQueryString: |-
   /*
     The query provides list of events done on specific resource.

     The query accepts the resource ID as part of the filters (replace the placeholder "<RESOURCE_INFO>" in the WHERE clause of the query),
     and returns all write actions done on that resource. The resource ID can be an ID for any AWS resource in the account.
     Example: An instance ID for an EC2 instance, table name for a DynamoDB table, logGroupName for a CloudWatch Log, etc.

     By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

     For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
   */

   SELECT
      useridentity.principalId AS "IAM PrincipalId",
      useridentity.accesskeyid AS "IAM SessionId",
      useridentity.accountid AS "AccountId",
      reverse(split_part(reverse(useridentity.arn), ':', 1)) AS "ActionedBy",
      eventname AS "EventName",
      awsregion AS "EventRegion",
      eventid AS "EventId",
      eventsource AS "EventService",
      eventtime AS "EventTime" 
   FROM
       "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate
   WHERE
      datetime > date_format(date_add('day', - 1, CURRENT_DATE), '%Y/%m/%d')
      AND readonly <> 'true'
      AND 
      (
         requestparameters LIKE '%<RESOURCE_INFO>%' 
         OR responseelements LIKE '%<RESOURCE_INFO>%'
      )
   ORDER BY eventtime

InsightsQueryString: |-
   # The query provides list of events done on specific resource.
   #
   # The query accepts the resource ID as part of the filters (replace the placeholder "<RESOURCE_INFO>" in the filter of the query),
   # and returns all write actions done on that resource. The resource ID can be an ID for any AWS resource in the account.
   # Example: An instance ID for an EC2 instance, table name for a DynamoDB table, logGroupName for a CloudWatch Log, etc.
   #
   # For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries

   filter readOnly=0
   | parse @message '"requestParameters":{*}' as RequestParameters
   | parse @message '"responseElements":{*}' as ResponseElements
   # | filter RequestParameters like "RESOURCE_INFO" or ResponseElements like "<RESOURCE_INFO>"
   | fields
      userIdentity.principalId as IAMPrincipalId,
      userIdentity.accessKeyId as IAMSessionId,
      userIdentity.accountId as AccountId,
      userIdentity.arn as ActionedBy,
      eventName as EventName,
      awsRegion as EventRegion,
      eventID as EventId,
      eventSource as EventService,
      eventTime as EventTime
   | display IAMPrincipalId, IAMSessionId, AccountId, ActionedBy, EventName, EventRegion, EventId, EventService, EventTime
   | sort eventTime desc
```

#### `ams_session_events_query_v1`
<a name="ams-session-events-query-v1"></a>

```
Name: ams_session_events_query_v1

Description: >-
   The query provides list of events done on specific session.
   The query accepts IAM Principal Id as part of the filters, and return all write actions done on that resource.
   By default; the query list the accesses for last day, the user can change the time range by changing the datetime filter.

AthenaQueryString: |-
   /*
     The query provides a list of events executed on a specific session.

     The query accepts the IAM principal ID as part of the filters (replace the placeholder "<PRINCIPAL_ID>" in the WHERE clause of the query),
     and returns all write actions done on that resource.

     By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

     For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
   */

   SELECT
      useridentity.principalId AS "IAM PrincipalId",
      useridentity.accesskeyid AS "IAM SessionId",
      useridentity.accountid AS "AccountId",
      reverse(split_part(reverse(useridentity.arn), ':', 1)) AS "ActionedBy",
      eventname AS "EventName",
      awsregion AS "EventRegion",
      eventsource AS "EventService",
      eventtime AS "EventTime",
      requestparameters As "RequestParameters",
      responseelements AS "ResponseElements",
      useragent AS "UserAgent"
   FROM
       "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate   WHERE
      useridentity.principalid = '<PRINCIPAL_ID>'
      AND datetime > date_format(date_add('day', - 1, CURRENT_DATE), '%Y/%m/%d')
      AND readonly <> 'true'
   ORDER BY eventtime

InsightsQueryString: |-
   # The query provides a list of events executed on a specific session.
   #
   # The query accepts the IAM principal ID as part of the filters (replace the placeholder "<PRINCIPAL_ID>" in the filter of the query),
   # and returns all write actions done on that resource.
   #
   # For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries

   filter readOnly=0 AND userIdentity.principalId = "<IAM Principal>"
   | sort eventTime desc
   | fields
      userIdentity.accessKeyId as IAMSessionId,
      userIdentity.principalId as IAMPrincipalId,
      userIdentity.accountId as AccountId,
      userIdentity.arn as ActionedBy,
      eventName as EventName,
      awsRegion as EventRegion,
      eventSource as EventService,
      eventTime as EventTime,
      userAgent as UserAgent
   | parse @message '"requestParameters":{*}' as RequestParameters
   | parse @message '"responseElements":{*}' as ResponseElements
```

#### `ams_session_ids_by_requester_v1`
<a name="ams-session-ids-by-requester-v1"></a>

```
Name: ams_session_ids_by_requester_v1

Description: >-
   The query provides list of IAM Principal/Session Ids for specific requester.
   The query accepts requester and return all IAM Principal/Session Ids by that requester during specific time range.
   By default; the query list the accesses for last day, the user can change the time range by changing the datetime filter.

AthenaQueryString: |-
   /*
     The query provides list of IAM Principal IDs for a specific requester.

     The query accepts the requester (replace placeholder "<Requester>" in the WHERE clause of the query),
     and returns all IAM Principal IDs by that requester during a specific time range.

     By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

     For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
   */

   SELECT
      json_extract_scalar(responseelements, '$.assumedRoleUser.assumedRoleId') AS "IAM PrincipalId",
      json_extract_scalar(responseelements, '$.credentials.accessKeyId') AS "IAM SessionIId",
      eventtime AS "EventTime"
   FROM
       "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate
   WHERE
      datetime > date_format(date_add('day', - 1, CURRENT_DATE), '%Y/%m/%d') 
      AND json_extract_scalar(requestparameters, '$.tags[2].value') = '<Requester>'
   ORDER BY eventtime

InsightsQueryString: |-
   # The query provides list of IAM Principal IDs for a specific requester.
   #
   # The query accepts the requester (replace placeholder "<Requester>" in the filter of the query),
   # and returns all IAM Principal IDs by that requester during a specific time range.
   #
   # For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
   filter eventName="AssumeRole" AND requestParameters.tags.2.value="<Requester>"
   | sort eventTime desc
   | fields
      responseElements.assumedRoleUser.assumedRoleId as IAMPrincipalId,
      responseElements.credentials.accessKeyId as IAMSessionId,
      eventTime as EventTime
```

## Modificare le autorizzazioni di registrazione
<a name="acc-cr-permissions"></a>

Le seguenti autorizzazioni sono necessarie per eseguire le query di modifica dei record:
+ **Athena**
  + atena: GetWorkGroup
  + atena: StartQueryExecution
  + atena: ListDataCatalogs
  + atena: GetQueryExecution
  + atena: GetQueryResults
  + atena: BatchGetNamedQuery
  + atena: ListWorkGroups
  + atena: UpdateWorkGroup
  + atena: GetNamedQuery
  + atena: ListQueryExecutions
  + atena: ListNamedQueries
+ **AWS KMS**
  + kms:Decrypt
  + AWS KMS [ID chiave di AMSCloudTrailLogManagement, o i tuoi ID AWS KMS chiave, se Accelerate utilizza il tuo archivio dati del bucket di eventi CloudTrail trail Amazon S3 utilizzando la crittografia SSE-KMS.](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html)
+ **AWS Glue**
  + colla: GetDatabase
  + colla: GetTables
  + colla: GetDatabases
  + colla: GetTable
+ **Accesso in lettura ad Amazon S3**
  +  CloudTrail Datastore del bucket Amazon S3: ams-a *AccountId* -cloudtrail- o il nome del tuo bucket Amazon S3*primary region*, trail events Amazon S3 bucket data store. CloudTrail 
+ **Accesso in scrittura ad Amazon S3**
  + Risultati delle query sugli eventi Athena Bucket Amazon S3: ams-a athena-results- *AccountId* *primary region*