# AWS - Step Functions Enum

{{#include ../../../banners/hacktricks-training.md}}

## Step Functions

AWS Step Functions is a workflow service that enables you to coordinate and orchestrate multiple AWS services into serverless workflows. By using AWS Step Functions, you can design and run workflows that connect various AWS services such as AWS Lambda, Amazon S3, Amazon DynamoDB, and many more, in a sequence of steps. This orchestration service provides a visual workflow interface and offers **state machine** capabilities, allowing you to define each step of the workflow in a declarative manner using JSON-based **Amazon States Language** (ASL).

## Key concepts

### Standard vs. Express Workflows

AWS Step Functions offers two types of **state machine workflows**: Standard and Express.

- **Standard Workflow**: This default workflow type is designed for long-running, durable, and auditable processes. It supports **exactly-once execution**, ensuring tasks run only once unless retries are specified. It is ideal for workflows needing detailed execution history and can run for up to one year.
- **Express Workflow**: This type is ideal for high-volume, short-duration tasks, running up to five minutes. They support **at-least-once execution**, suitable for idempotent tasks like data processing. These workflows are optimized for cost and performance, charging based on executions, duration, and memory usage.

### States

States are the essential units of state machines. They define the individual steps within a workflow, being able to perform a variety of functions depending on its type:

- **Task:** Executes a job, often using an AWS service like Lambda.
- **Choice:** Makes decisions based on input.
- **Fail/Succeed:** Ends the execution with a failure or success.
- **Pass:** Passes input to output or injects data.
- **Wait:** Delays execution for a set time.
- **Parallel:** Initiates parallel branches.
- **Map:** Dynamically iterates steps over items.

### Task

A **Task** state represents a single unit of work executed by a state machine. Tasks can invoke various resources, including activities, Lambda functions, AWS services, or third-party APIs.

- **Activities**: Custom workers you manage, suitable for long-running processes.
  - Resource: **`arn:aws:states:region:account:activity:name`**.
- **Lambda Functions**: Executes AWS Lambda functions.
  - Resource: **`arn:aws:lambda:region:account:function:function-name`**.
- **AWS Services**: Integrates directly with other AWS services, like DynamoDB or S3.
  - Resource: **`arn:partition:states:region:account:servicename:APIname`**.
- **HTTP Task**: Calls third-party APIs.
  - Resource field: **`arn:aws:states:::http:invoke`**. Then, you should provide the API endpoint configuration details, such as the API URL, method, and authentication details.

The following example shows a Task state definition that invokes a Lambda function called HelloWorld:

```json
"HelloWorld": {
  "Type": "Task",
  "Resource": "arn:aws:states:::lambda:invoke",
  "Parameters": {
    "Payload.$": "$",
    "FunctionName": "arn:aws:lambda:<region>:<account-id>:function:HelloWorld"
  },
  "End": true
}
```

### Choice

A **Choice** state adds conditional logic to a workflow, enabling decisions based on input data. It evaluates the specified conditions and transitions to the corresponding state based on the results.

- **Comparison**: Each choice rule includes a comparison operator (e.g., **`NumericEquals`**, **`StringEquals`**) that compares an input variable to a specified value or another variable.
- **Next Field**: Choice states do not support don't support the **`End`** field, instead, they define the **`Next`** state to transition to if the comparison is true.

Example of **Choice** state:

```json
{
  "Variable": "$.timeStamp",
  "TimestampEquals": "2000-01-01T00:00:00Z",
  "Next": "TimeState"
}
```

### Fail/Succeed

A **`Fail`** state stops the execution of a state machine and marks it as a failure. It is used to specify an error name and a cause, providing details about the failure. This state is terminal, meaning it ends the execution flow.

A **`Succeed`** state stops the execution successfully. It is typically used to terminate the workflow when it completes successfully. This state does not require a **`Next`** field.

{{#tabs }}
{{#tab name="Fail example" }}

```json
"FailState": {
  "Type": "Fail",
  "Error": "ErrorName",
  "Cause": "Error details"
}
```

{{#endtab }}

{{#tab name="Succeed example" }}

```json
"SuccessState": {
  "Type": "Succeed"
}
```

{{#endtab }}
{{#endtabs }}

### Pass

A **Pass** state passes its input to its output either without performing any work or transformin JSON state input using filters, and then passing the transformed data to the next state. It is useful for testing and constructing state machines, allowing you to inject static data or transform it.

```json
"PassState": {
  "Type": "Pass",
  "Result": {"key": "value"},
  "ResultPath": "$.newField",
  "Next": "NextState"
}
```

### Wait

A **Wait** state delays the execution of the state machine for a specified duration. There are three primary methods to configure the wait time:

- **X Seconds**: A fixed number of seconds to wait.

  ```json
  "WaitState": {
  	"Type": "Wait",
  	"Seconds": 10,
  	"Next": "NextState"
  }
  ```

- **Absolute Timestamp**: An exact time to wait until.

  ```json
  "WaitState": {
    "Type": "Wait",
    "Timestamp": "2024-03-14T01:59:00Z",
    "Next": "NextState"
  }
  ```

- **Dynamic Wait**: Based on input using **`SecondsPath`** or **`TimestampPath`**.

  ```json
  jsonCopiar código
  "WaitState": {
    "Type": "Wait",
    "TimestampPath": "$.expirydate",
    "Next": "NextState"
  }
  ```

### Parallel

A **Parallel** state allows you to execute multiple branches of tasks concurrently within your workflow. Each branch runs independently and processes its own sequence of states. The execution waits until all branches complete before proceeding to the next state. Its key fields are:

- **Branches**: An array defining the parallel execution paths. Each branch is a separate state machine.
- **ResultPath**: Defines where (in the input) to place the combined output of the branches.
- **Retry and Catch**: Error handling configurations for the parallel state.

```json
"ParallelState": {
  "Type": "Parallel",
  "Branches": [
    {
      "StartAt": "Task1",
      "States": { ... }
    },
    {
      "StartAt": "Task2",
      "States": { ... }
    }
  ],
  "Next": "NextState"
}
```

### Map

A **Map** state enables the execution of a set of steps for each item in an dataset. It's used for parallel processing of data. Depending on how you want to process the items of the dataset, Step Functions provides the following modes:

- **Inline Mode**: Executes a subset of states for each JSON array item. Suitable for small-scale tasks with less than 40 parallel iterations, running each of them in the context of the workflow that contains the **`Map`** state.

  ```json
  "MapState": {
    "Type": "Map",
    "ItemsPath": "$.arrayItems",
    "ItemProcessor": {
        "ProcessorConfig": {
            "Mode": "INLINE"
        },
        "StartAt": "AddState",
        "States": {
            "AddState": {
                "Type": "Task",
                "Resource": "arn:aws:states:::lambda:invoke",
                "OutputPath": "$.Payload",
                "Parameters": {
                    "FunctionName": "arn:aws:lambda:<region>:<account-id>:function:add-function"
                },
                "End": true
            }
        }
    },
    "End": true
    "ResultPath": "$.detail.added",
    "ItemsPath": "$.added"
  }
  ```

- **Distributed Mode**: Designed for large-scale parallel processing with high concurrency. Supports processing large datasets, such as those stored in Amazon S3, enabling a high concurrency of up 10,000 parallel child workflow executions, running these child as a separate child execution.

  ```json
  "DistributedMapState": {
    "Type": "Map",
    "ItemReader": {
      "Resource": "arn:aws:states:::s3:getObject",
      "Parameters": {
        "Bucket": "my-bucket",
        "Key": "data.csv"
      }
    },
    "ItemProcessor": {
      "ProcessorConfig": {
        "Mode": "DISTRIBUTED",
        "ExecutionType": "EXPRESS"
      },
      "StartAt": "ProcessItem",
      "States": {
        "ProcessItem": {
          "Type": "Task",
          "Resource": "arn:aws:lambda:region:account-id:function:my-function",
          "End": true
  	    }
      }
    },
    "End": true
    "ResultWriter": {
      "Resource": "arn:aws:states:::s3:putObject",
      "Parameters": {
        "Bucket": "myOutputBucket",
        "Prefix": "csvProcessJobs"
  	  }
  	}
  }
  ```

### Versions and aliases

Step Functions also lets you manage workflow deployments through **versions** and **aliases** of state machines. A version represents a snapshot of a state machine that can be executed. Aliases serve as pointers to up to two versions of a state machine.

- **Versions**: These immutable snapshots of a state machine are created from the most recent revision of that state machine. Each version is identified by a unique ARN that combines the state machine ARN with the version number, separated by a colon (**`arn:aws:states:region:account-id:stateMachine:StateMachineName:version-number`**). Versions cannot be edited, but you can update the state machine and publish a new version, or use the desired state machine version.
- **Aliases**: These pointers can reference up to two versions of the same state machine. Multiple aliases can be created for a single state machine, each identified by a unique ARN constructed by combining the state machine ARN with the alias name, separated by a colon (**`arn:aws:states:region:account-id:stateMachine:StateMachineName:aliasName`**). Aliases enable routing of traffic between one of the two versions of a state machine. Alternatively, an alias can point to a single specific version of the state machine, but not to other aliases. They can be updated to redirect to a different version of the state machine as needed, facilitating controlled deployments and workflow management.

For more detailed information about **ASL**, check: [**Amazon States Language**](https://states-language.net/spec.html).

## IAM Roles for State machines

AWS Step Functions utilizes AWS Identity and Access Management (IAM) roles to control access to resources and actions within state machines. Here are the key aspects related to security and IAM roles in AWS Step Functions:

- **Execution Role**: Each state machine in AWS Step Functions is associated with an IAM execution role. This role defines what actions the state machine can perform on your behalf. When a state machine transitions between states that interact with AWS services (like invoking Lambda functions, accessing DynamoDB, etc.), it assumes this execution role to carry out those actions.
- **Permissions**: The IAM execution role must be configured with permissions that allow the necessary actions on other AWS services. For example, if your state machine needs to invoke AWS Lambda functions, the IAM role must have **`lambda:InvokeFunction`** permissions. Similarly, if it needs to write to DynamoDB, appropriate permissions (**`dynamodb:PutItem`**, **`dynamodb:UpdateItem`**, etc.) must be granted.

## Enumeration

ReadOnlyAccess policy is enough for all the following enumeration actions.

```bash
# State machines #

## List state machines
aws stepfunctions list-state-machines
## Retrieve informatio about the specified state machine
aws stepfunctions describe-state-machine --state-machine-arn <value>

## List versions for the specified state machine
aws stepfunctions list-state-machine-versions --state-machine-arn <value>
## List aliases for the specified state machine
aws stepfunctions list-state-machine-aliases --state-machine-arn <value>
## Retrieve information about the specified state machine alias
aws stepfunctions describe-state-machine-alias --state-machine-alias-arn <value>

## List executions of a state machine
aws stepfunctions list-executions --state-machine-arn <value> [--status-filter <RUNNING | SUCCEEDED | FAILED | TIMED_OUT | ABORTED | PENDING_REDRIVE>] [--redrive-filter <REDRIVEN | NOT_REDRIVEN>]
## Retrieve information and relevant metadata about a state machine execution (output included)
aws stepfunctions describe-execution --execution-arn <value>
## Retrieve information about the state machine associated to the specified execution
aws stepfunctions describe-state-machine-for-execution --execution-arn <value>
## Retrieve the history of the specified execution as a list of events
aws stepfunctions get-execution-history --execution-arn <value> [--reverse-order | --no-reverse-order] [--include-execution-data | --no-include-execution-data]

## List tags for the specified step Functions resource
aws stepfunctions list-tags-for-resource --resource-arn <value>

## Validate the definition of a state machine without creating the resource
aws stepfunctions validate-state-machine-definition --definition <value> [--type <STANDARD | EXPRESS>]

# Activities #

## List existing activities
aws stepfunctions list-activities
## Retrieve information about the specified activity
aws stepfunctions describe-activity --activity-arn <value>

# Map Runs #

## List map runs of an execution
aws stepfunctions list-map-runs --execution-arn <value>
## Provide information about the configuration, progress and results of a Map Run
aws stepfunctions describe-map-run --map-run-arn <value>
## Lists executions of a Map Run
aws stepfunctions list-executions --map-run-arn <value> [--status-filter <RUNNING | SUCCEEDED | FAILED | TIMED_OUT | ABORTED | PENDING_REDRIVE>] [--redrive-filter <REDRIVEN | NOT_REDRIVEN>]
```

## Privesc

In the following page, you can check how to **abuse Step Functions permissions to escalate privileges**:

{{#ref}}
../aws-privilege-escalation/aws-stepfunctions-privesc/README.md
{{#endref}}

## Post Exploitation

{{#ref}}
../aws-post-exploitation/aws-stepfunctions-post-exploitation/README.md
{{#endref}}

## Persistence

{{#ref}}
../aws-persistence/aws-step-functions-persistence/README.md
{{#endref}}

## References

- [https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsstepfunctions.html](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsstepfunctions.html)
- [https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)
- [https://states-language.net/spec.html](https://states-language.net/spec.html)

{{#include ../../../banners/hacktricks-training.md}}




