如何生成SSH代理签名响应

时间:2017-07-20 04:46:35

标签: python ssh rsa pycrypto ssh-agent

我正在编写一个内部管理系统,它也需要实现SSH代理。到目前为止,我已正确实施SSH_AGENTC_REQUEST_IDENTITIESSSH_AGENT_IDENTITIES_ANSWER,导致SSH根据https://tools.ietf.org/id/draft-miller-ssh-agent-00.html发送SSH_AGENTC_SIGN_REQUEST

我遇到的问题是如何签署请求,此时我只需要支持ssh-rsa。我已根据https://tools.ietf.org/html/rfc4253尝试实施此功能,但我似乎无法生成将进行身份验证的回复。

根据我对此规范的理解,SSH_AGENTC_SIGN_REQUEST消息的整个数据部分需要使用RSASSA-PKCS1-v1_5

进行签名

以下是接收请求的代码

if msgType == SSH_AGENTC_SIGN_REQUEST:
  blobLen = struct.unpack('!I', sock.recv(4))[0]
  blob    = sock.recv(blobLen)
  dataLen = struct.unpack('!I', sock.recv(4))[0]
  data    = sock.recv(dataLen)
  flags   = struct.unpack('!I', sock.recv(4))[0]

  print("blob: %s\ndata: %s\n flags: %d" % (blob, data, flags))

  if base64.b64decode(server["public_key"]) != blob:
    sock.sendall(struct.pack('!IB', 1, SSH_AGENT_FAILURE))
    continue

  signed = rpc.root.signSSHData(server_id, data)
  if not signed:
    sock.sendall(struct.pack('!IB', 1, SSH_AGENT_FAILURE))
    continue

  buff = bytearray()
  buff.extend(struct.pack('!B', SSH_AGENT_SIGN_RESPONSE))
  packBytes(buff, bytes("ssh-rsa", "UTF-8"))
  packBytes(buff, signed)
  head = struct.pack('!I', len(buff))

  sock.sendall(head);
  sock.sendall(buff);

以下是rpc.root.signSSHData的来源:

  def exposed_signSSHData(self, server_id, data):
    query = "SELECT private_key FROM servers WHERE deleted = 0 AND id = %s LIMIT 1"
    cursor = self.core.getDBC().cursor()
    cursor.execute(query, (server_id, ))
    row    = cursor.fetchone();
    if row is None:
      cursor.close()
      return False

    key    = self.core.decryptData(row[0])
    key    = RSA.importKey(key);
    h      = SHA.new(data)
    signer = PKCS1_v1_5.new(key)
    return signer.sign(h)

更新1:我相信我可能已经弄清楚了,似乎data是RFC4252中定义的SSH_MSG_USERAUTH_REQUEST。我将更新我的应用程序,看看它是怎么回事。

1 个答案:

答案 0 :(得分:1)

我找到了解决方案,回复格式不正确,下面是更正后的代码:

if msgType == SSH_AGENTC_SIGN_REQUEST:
  blobLen = struct.unpack('!I', sock.recv(4))[0]
  blob    = sock.recv(blobLen)
  dataLen = struct.unpack('!I', sock.recv(4))[0]
  data    = sock.recv(dataLen)
  flags   = struct.unpack('!I', sock.recv(4))[0]

  if base64.b64decode(server["public_key"]) != blob:
    sock.sendall(struct.pack('!IB', 1, SSH_AGENT_FAILURE))
    continue

  sig = rpc.root.signSSHData(server_id, data);
  if not sig:
    sock.sendall(struct.pack('!IB', 1, SSH_AGENT_FAILURE))
    continue

  signature = bytearray()
  packBytes(signature, bytes("ssh-rsa", "UTF-8"))
  packBytes(signature, sig)

  buff = bytearray()
  buff.extend(struct.pack('!B', SSH_AGENT_SIGN_RESPONSE))
  packBytes(buff, signature)
  head = struct.pack('!I', len(buff))

  sock.sendall(head);
  sock.sendall(buff);
  continue