4

希望你做得很好!

用例

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

为了做到这一点,我将在 Python 3.7 中使用 Lambda,我目前在本地制作我的 PoC。我能够打开 websocket,发送令牌有效负载并获得包含外壳的输出。

问题是字节输出包含python decode 函数在很多测试字符编码中无法解码的字符,每次都有东西阻塞。

输出

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

打印(事件)

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 输出。

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

尽情享受您的一天!

4

1 回答 1

1

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

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

上述结构的字段也通过附加结构分解为模型。

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

于 2019-09-12T15:47:59.190 回答