繁体   English   中英

无法在 python 中解码 AWS Session Manager websocket 输出

[英]Unable to decode AWS Session Manager websocket output in python

希望你做得很好!

用例

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

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

预先感谢您对此的任何帮助。

享受剩下的一天吧!

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM