【问题标题】:Unable to decode AWS Session Manager websocket output in python无法在 python 中解码 AWS Session Manager websocket 输出
【发布时间】:2020-01-12 02:08:10
【问题描述】:

希望你做得很好!

用例

我正在尝试在 AWS 上进行 PoC,用例是我们需要能够检查我们所有的基础设施,所有实例都可以通过 AWS Session Manager 访问。

为了做到这一点,我将在 Python 3.7 中使用 Lambda,我目前在本地制作我的 PoC。我能够打开 websocket,发送 Token Payload 并获得包含 shell 的输出。

问题是字节输出包含python解码函数无法在大量测试字符编码中解码的字符,每次都会阻塞。

输出

这是我发送有效负载后的输出:

打印(事件)

b'\x00\x00\x00toutput_stream_data \x00\x00\x00\x01\x00\x00\x01m\x1a\x1b\x9b\x15\x00\x00\x00\x00\x00\x00\x00\x00\ x00\x00\x00\x00\x00\x00\x00\x01\xb1\x0b?\x19\x99A\xfc\xae%\xb2b\xab\xfd\x02A\xd7C\xcd\xd8}L\xa8\xb2J\ xad\x12\xe3\x94\n\xed\xb81\xfa\xb6\x11\x18\xc2\xecR\xf66&4\x18\xf6\xbdd\x00\x00\x00\x01\x00\x00\x00\x10\ x1b[?1034hsh-4.2$ '

我已经尝试过的

我在 stackoverflow 上进行了很多研究,尝试使用 ascii、cp1252、cp1251、cp1250、iso8859-1、utf-16、utf-8、utf_16_be 进行解码,但每次都无法解码任何内容或导致错误,因为字符未知。

我也已经尝试过使用 chardet.detect,但是返回的编码不起作用,而且概率结果也很低。并且还尝试剥离 \x00 但剥离当时不起作用。

我已经知道 shell 输出有时可能包含着色字符和一些使它看起来像乱码的东西,但是在这里,我尝试在其上传递 colorama,尝试将一些 ANSI 字符与一些正则表达式匹配,没有成功解码这个字节回应。

代码

这是我的 PoC 的代码,您可以使用它来尝试,您只需更改目标实例 id(您的实例需要运行最新的 amazon-ssm-agent)。

import boto3
import uuid
import json
from websocket import create_connection

# Setting the boto3 client and the target
client = boto3.client('ssm','eu-west-1')
target = 'i-012345678910'

# Starting a session, this return a WebSocket URL and a Token for the Payload
response = client.start_session(Target=target)

# Creating a session with websocket.create_connection()
ws = create_connection(response['StreamUrl'])

# Building the Payload with the Token
payload = {
    "MessageSchemaVersion": "1.0",
    "RequestId": str(uuid.uuid4()),
    "TokenValue": response['TokenValue']
    }

# Sending the Payload
ws.send(json.dumps(payload))

# Receiving, printing and measuring the received message
event = ws.recv()
print(event)
print(len(event))

# Sending pwd, that should output /usr/bin
ws.send('pwd')

# Checking the result of the received message after the pwd
event = ws.recv()
print(event)
print(len(event))

预期输出

在最终解决方案中,我希望能够通过 websocket 执行 curl http://169.254.169.254/latest/meta-data/instance-id 之类的操作,并将命令输出的 instance-id 与目标进行比较,以验证该实例是否可访问。但我需要能够在实现之前解码 websocket 输出。

提前感谢您对此提供的任何帮助。

尽情享受你的一天!

【问题讨论】:

  • 在同一领域工作,试图通过隧道连接到本地端口。看来我必须使用插件github.com/aws/aws-cli/blob/…(有趣的是会话管理器插件源尚未可用)

标签: python amazon-web-services shell websocket aws-session-manager


【解决方案1】:

根据我对amazon-ssm-agent 代码的阅读,通过websocket 连接交换并由会话管理器通道管理的有效负载遵循称为AgentMessage 的特定结构。

您必须遵守此结构才能通过 MGS 服务将会话管理器与远程代理一起使用,这意味着序列化消息和反序列化响应。

上述结构的字段也通过附加结构分解为models

在 python 中重新实现它应该不会太长。祝你好运!

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 2019-12-14
    • 2020-09-05
    • 2020-07-30
    • 1970-01-01
    • 2020-09-24
    • 2012-06-08
    相关资源
    最近更新 更多