PageRenderTime 103ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 0ms

/resources/lib/twisted/twisted/conch/ssh/transport.py

https://github.com/analogue/mythbox
Python | 1362 lines | 1195 code | 38 blank | 129 comment | 16 complexity | 378d68201d5894b7a74ca11da695be94 MD5 | raw file
  1. # -*- test-case-name: twisted.conch.test.test_transport -*-
  2. #
  3. # Copyright (c) 2001-2008 Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. The lowest level SSH protocol. This handles the key negotiation, the
  7. encryption and the compression. The transport layer is described in
  8. RFC 4253.
  9. Maintainer: Paul Swartz
  10. """
  11. # base library imports
  12. import struct
  13. import zlib
  14. import array
  15. # external library imports
  16. from Crypto import Util
  17. from Crypto.Cipher import XOR
  18. # twisted imports
  19. from twisted.internet import protocol, defer
  20. from twisted.conch import error
  21. from twisted.python import log, randbytes
  22. from twisted.python.hashlib import md5, sha1
  23. # sibling imports
  24. from twisted.conch.ssh import keys
  25. from twisted.conch.ssh.common import NS, getNS, MP, getMP, _MPpow, ffs
  26. class SSHTransportBase(protocol.Protocol):
  27. """
  28. Protocol supporting basic SSH functionality: sending/receiving packets
  29. and message dispatch. To connect to or run a server, you must use
  30. SSHClientTransport or SSHServerTransport.
  31. @ivar protocolVersion: A string representing the version of the SSH
  32. protocol we support. Currently defaults to '2.0'.
  33. @ivar version: A string representing the version of the server or client.
  34. Currently defaults to 'Twisted'.
  35. @ivar comment: An optional string giving more information about the
  36. server or client.
  37. @ivar supportedCiphers: A list of strings representing the encryption
  38. algorithms supported, in order from most-preferred to least.
  39. @ivar supportedMACs: A list of strings representing the message
  40. authentication codes (hashes) supported, in order from most-preferred
  41. to least. Both this and supportedCiphers can include 'none' to use
  42. no encryption or authentication, but that must be done manually,
  43. @ivar supportedKeyExchanges: A list of strings representing the
  44. key exchanges supported, in order from most-preferred to least.
  45. @ivar supportedPublicKeys: A list of strings representing the
  46. public key types supported, in order from most-preferred to least.
  47. @ivar supportedCompressions: A list of strings representing compression
  48. types supported, from most-preferred to least.
  49. @ivar supportedLanguages: A list of strings representing languages
  50. supported, from most-preferred to least.
  51. @ivar supportedVersions: A container of strings representing supported ssh
  52. protocol version numbers.
  53. @ivar isClient: A boolean indicating whether this is a client or server.
  54. @ivar gotVersion: A boolean indicating whether we have receieved the
  55. version string from the other side.
  56. @ivar buf: Data we've received but hasn't been parsed into a packet.
  57. @ivar outgoingPacketSequence: the sequence number of the next packet we
  58. will send.
  59. @ivar incomingPacketSequence: the sequence number of the next packet we
  60. are expecting from the other side.
  61. @ivar outgoingCompression: an object supporting the .compress(str) and
  62. .flush() methods, or None if there is no outgoing compression. Used to
  63. compress outgoing data.
  64. @ivar outgoingCompressionType: A string representing the outgoing
  65. compression type.
  66. @ivar incomingCompression: an object supporting the .decompress(str)
  67. method, or None if there is no incoming compression. Used to
  68. decompress incoming data.
  69. @ivar incomingCompressionType: A string representing the incoming
  70. compression type.
  71. @ivar ourVersionString: the version string that we sent to the other side.
  72. Used in the key exchange.
  73. @ivar otherVersionString: the version string sent by the other side. Used
  74. in the key exchange.
  75. @ivar ourKexInitPayload: the MSG_KEXINIT payload we sent. Used in the key
  76. exchange.
  77. @ivar otherKexInitPayload: the MSG_KEXINIT payload we received. Used in
  78. the key exchange
  79. @ivar sessionID: a string that is unique to this SSH session. Created as
  80. part of the key exchange, sessionID is used to generate the various
  81. encryption and authentication keys.
  82. @ivar service: an SSHService instance, or None. If it's set to an object,
  83. it's the currently running service.
  84. @ivar kexAlg: the agreed-upon key exchange algorithm.
  85. @ivar keyAlg: the agreed-upon public key type for the key exchange.
  86. @ivar currentEncryptions: an SSHCiphers instance. It represents the
  87. current encryption and authentication options for the transport.
  88. @ivar nextEncryptions: an SSHCiphers instance. Held here until the
  89. MSG_NEWKEYS messages are exchanged, when nextEncryptions is
  90. transitioned to currentEncryptions.
  91. @ivar first: the first bytes of the next packet. In order to avoid
  92. decrypting data twice, the first bytes are decrypted and stored until
  93. the whole packet is available.
  94. """
  95. protocolVersion = '2.0'
  96. version = 'Twisted'
  97. comment = ''
  98. ourVersionString = ('SSH-' + protocolVersion + '-' + version + ' '
  99. + comment).strip()
  100. supportedCiphers = ['aes256-ctr', 'aes256-cbc', 'aes192-ctr', 'aes192-cbc',
  101. 'aes128-ctr', 'aes128-cbc', 'cast128-ctr',
  102. 'cast128-cbc', 'blowfish-ctr', 'blowfish-cbc',
  103. '3des-ctr', '3des-cbc'] # ,'none']
  104. supportedMACs = ['hmac-sha1', 'hmac-md5'] # , 'none']
  105. # both of the above support 'none', but for security are disabled by
  106. # default. to enable them, subclass this class and add it, or do:
  107. # SSHTransportBase.supportedCiphers.append('none')
  108. supportedKeyExchanges = ['diffie-hellman-group-exchange-sha1',
  109. 'diffie-hellman-group1-sha1']
  110. supportedPublicKeys = ['ssh-rsa', 'ssh-dss']
  111. supportedCompressions = ['none', 'zlib']
  112. supportedLanguages = ()
  113. supportedVersions = ('1.99', '2.0')
  114. isClient = False
  115. gotVersion = False
  116. buf = ''
  117. outgoingPacketSequence = 0
  118. incomingPacketSequence = 0
  119. outgoingCompression = None
  120. incomingCompression = None
  121. sessionID = None
  122. service = None
  123. def connectionLost(self, reason):
  124. if self.service:
  125. self.service.serviceStopped()
  126. if hasattr(self, 'avatar'):
  127. self.logoutFunction()
  128. log.msg('connection lost')
  129. def connectionMade(self):
  130. """
  131. Called when the connection is made to the other side. We sent our
  132. version and the MSG_KEXINIT packet.
  133. """
  134. self.transport.write('%s\r\n' % (self.ourVersionString,))
  135. self.currentEncryptions = SSHCiphers('none', 'none', 'none', 'none')
  136. self.currentEncryptions.setKeys('', '', '', '', '', '')
  137. self.sendKexInit()
  138. def sendKexInit(self):
  139. self.ourKexInitPayload = (chr(MSG_KEXINIT) +
  140. randbytes.secureRandom(16) +
  141. NS(','.join(self.supportedKeyExchanges)) +
  142. NS(','.join(self.supportedPublicKeys)) +
  143. NS(','.join(self.supportedCiphers)) +
  144. NS(','.join(self.supportedCiphers)) +
  145. NS(','.join(self.supportedMACs)) +
  146. NS(','.join(self.supportedMACs)) +
  147. NS(','.join(self.supportedCompressions)) +
  148. NS(','.join(self.supportedCompressions)) +
  149. NS(','.join(self.supportedLanguages)) +
  150. NS(','.join(self.supportedLanguages)) +
  151. '\000' + '\000\000\000\000')
  152. self.sendPacket(MSG_KEXINIT, self.ourKexInitPayload[1:])
  153. def sendPacket(self, messageType, payload):
  154. """
  155. Sends a packet. If it's been set up, compress the data, encrypt it,
  156. and authenticate it before sending.
  157. @param messageType: The type of the packet; generally one of the
  158. MSG_* values.
  159. @type messageType: C{int}
  160. @param payload: The payload for the message.
  161. @type payload: C{str}
  162. """
  163. payload = chr(messageType) + payload
  164. if self.outgoingCompression:
  165. payload = (self.outgoingCompression.compress(payload)
  166. + self.outgoingCompression.flush(2))
  167. bs = self.currentEncryptions.encBlockSize
  168. # 4 for the packet length and 1 for the padding length
  169. totalSize = 5 + len(payload)
  170. lenPad = bs - (totalSize % bs)
  171. if lenPad < 4:
  172. lenPad = lenPad + bs
  173. packet = (struct.pack('!LB',
  174. totalSize + lenPad - 4, lenPad) +
  175. payload + randbytes.secureRandom(lenPad))
  176. encPacket = (
  177. self.currentEncryptions.encrypt(packet) +
  178. self.currentEncryptions.makeMAC(
  179. self.outgoingPacketSequence, packet))
  180. self.transport.write(encPacket)
  181. self.outgoingPacketSequence += 1
  182. def getPacket(self):
  183. """
  184. Try to return a decrypted, authenticated, and decompressed packet
  185. out of the buffer. If there is not enough data, return None.
  186. @rtype: C{str}/C{None}
  187. """
  188. bs = self.currentEncryptions.decBlockSize
  189. ms = self.currentEncryptions.verifyDigestSize
  190. if len(self.buf) < bs: return # not enough data
  191. if not hasattr(self, 'first'):
  192. first = self.currentEncryptions.decrypt(self.buf[:bs])
  193. else:
  194. first = self.first
  195. del self.first
  196. packetLen, paddingLen = struct.unpack('!LB', first[:5])
  197. if packetLen > 1048576: # 1024 ** 2
  198. self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
  199. 'bad packet length %s' % packetLen)
  200. return
  201. if len(self.buf) < packetLen + 4 + ms:
  202. self.first = first
  203. return # not enough packet
  204. if(packetLen + 4) % bs != 0:
  205. self.sendDisconnect(
  206. DISCONNECT_PROTOCOL_ERROR,
  207. 'bad packet mod (%i%%%i == %i)' % (packetLen + 4, bs,
  208. (packetLen + 4) % bs))
  209. return
  210. encData, self.buf = self.buf[:4 + packetLen], self.buf[4 + packetLen:]
  211. packet = first + self.currentEncryptions.decrypt(encData[bs:])
  212. if len(packet) != 4 + packetLen:
  213. self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
  214. 'bad decryption')
  215. return
  216. if ms:
  217. macData, self.buf = self.buf[:ms], self.buf[ms:]
  218. if not self.currentEncryptions.verify(self.incomingPacketSequence,
  219. packet, macData):
  220. self.sendDisconnect(DISCONNECT_MAC_ERROR, 'bad MAC')
  221. return
  222. payload = packet[5:-paddingLen]
  223. if self.incomingCompression:
  224. try:
  225. payload = self.incomingCompression.decompress(payload)
  226. except: # bare except, because who knows what kind of errors
  227. # decompression can raise
  228. log.err()
  229. self.sendDisconnect(DISCONNECT_COMPRESSION_ERROR,
  230. 'compression error')
  231. return
  232. self.incomingPacketSequence += 1
  233. return payload
  234. def _unsupportedVersionReceived(self, remoteVersion):
  235. """
  236. Called when an unsupported version of the ssh protocol is received from
  237. the remote endpoint.
  238. @param remoteVersion: remote ssh protocol version which is unsupported
  239. by us.
  240. @type remoteVersion: C{str}
  241. """
  242. self.sendDisconnect(DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED,
  243. 'bad version ' + remoteVersion)
  244. def dataReceived(self, data):
  245. """
  246. First, check for the version string (SSH-2.0-*). After that has been
  247. received, this method adds data to the buffer, and pulls out any
  248. packets.
  249. @type data: C{str}
  250. """
  251. self.buf = self.buf + data
  252. if not self.gotVersion:
  253. if self.buf.find('\n', self.buf.find('SSH-')) == -1:
  254. return
  255. lines = self.buf.split('\n')
  256. for p in lines:
  257. if p.startswith('SSH-'):
  258. self.gotVersion = True
  259. self.otherVersionString = p.strip()
  260. remoteVersion = p.split('-')[1]
  261. if remoteVersion not in self.supportedVersions:
  262. self._unsupportedVersionReceived(remoteVersion)
  263. return
  264. i = lines.index(p)
  265. self.buf = '\n'.join(lines[i + 1:])
  266. packet = self.getPacket()
  267. while packet:
  268. messageNum = ord(packet[0])
  269. self.dispatchMessage(messageNum, packet[1:])
  270. packet = self.getPacket()
  271. def dispatchMessage(self, messageNum, payload):
  272. """
  273. Send a received message to the appropriate method.
  274. @type messageNum: C{int}
  275. @type payload: c{str}
  276. """
  277. if messageNum < 50 and messageNum in messages:
  278. messageType = messages[messageNum][4:]
  279. f = getattr(self, 'ssh_%s' % messageType, None)
  280. if f is not None:
  281. f(payload)
  282. else:
  283. log.msg("couldn't handle %s" % messageType)
  284. log.msg(repr(payload))
  285. self.sendUnimplemented()
  286. elif self.service:
  287. log.callWithLogger(self.service, self.service.packetReceived,
  288. messageNum, payload)
  289. else:
  290. log.msg("couldn't handle %s" % messageNum)
  291. log.msg(repr(payload))
  292. self.sendUnimplemented()
  293. def ssh_KEXINIT(self, packet):
  294. """
  295. Called when we receive a MSG_KEXINIT message. Payload::
  296. bytes[16] cookie
  297. string keyExchangeAlgorithms
  298. string keyAlgorithms
  299. string incomingEncryptions
  300. string outgoingEncryptions
  301. string incomingAuthentications
  302. string outgoingAuthentications
  303. string incomingCompressions
  304. string outgoingCompressions
  305. string incomingLanguages
  306. string outgoingLanguages
  307. bool firstPacketFollows
  308. unit32 0 (reserved)
  309. Starts setting up the key exchange, keys, encryptions, and
  310. authentications. Extended by ssh_KEXINIT in SSHServerTransport and
  311. SSHClientTransport.
  312. """
  313. self.otherKexInitPayload = chr(MSG_KEXINIT) + packet
  314. #cookie = packet[: 16] # taking this is useless
  315. k = getNS(packet[16:], 10)
  316. strings, rest = k[:-1], k[-1]
  317. (kexAlgs, keyAlgs, encCS, encSC, macCS, macSC, compCS, compSC, langCS,
  318. langSC) = [s.split(',') for s in strings]
  319. # these are the server directions
  320. outs = [encSC, macSC, compSC]
  321. ins = [encCS, macSC, compCS]
  322. if self.isClient:
  323. outs, ins = ins, outs # switch directions
  324. server = (self.supportedKeyExchanges, self.supportedPublicKeys,
  325. self.supportedCiphers, self.supportedCiphers,
  326. self.supportedMACs, self.supportedMACs,
  327. self.supportedCompressions, self.supportedCompressions)
  328. client = (kexAlgs, keyAlgs, outs[0], ins[0], outs[1], ins[1],
  329. outs[2], ins[2])
  330. if self.isClient:
  331. server, client = client, server
  332. self.kexAlg = ffs(client[0], server[0])
  333. self.keyAlg = ffs(client[1], server[1])
  334. self.nextEncryptions = SSHCiphers(
  335. ffs(client[2], server[2]),
  336. ffs(client[3], server[3]),
  337. ffs(client[4], server[4]),
  338. ffs(client[5], server[5]))
  339. self.outgoingCompressionType = ffs(client[6], server[6])
  340. self.incomingCompressionType = ffs(client[7], server[7])
  341. if None in (self.kexAlg, self.keyAlg, self.outgoingCompressionType,
  342. self.incomingCompressionType):
  343. self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
  344. "couldn't match all kex parts")
  345. return
  346. if None in self.nextEncryptions.__dict__.values():
  347. self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
  348. "couldn't match all kex parts")
  349. return
  350. log.msg('kex alg, key alg: %s %s' % (self.kexAlg, self.keyAlg))
  351. log.msg('outgoing: %s %s %s' % (self.nextEncryptions.outCipType,
  352. self.nextEncryptions.outMACType,
  353. self.outgoingCompressionType))
  354. log.msg('incoming: %s %s %s' % (self.nextEncryptions.inCipType,
  355. self.nextEncryptions.inMACType,
  356. self.incomingCompressionType))
  357. return kexAlgs, keyAlgs, rest # for SSHServerTransport to use
  358. def ssh_DISCONNECT(self, packet):
  359. """
  360. Called when we receive a MSG_DISCONNECT message. Payload::
  361. long code
  362. string description
  363. This means that the other side has disconnected. Pass the message up
  364. and disconnect ourselves.
  365. """
  366. reasonCode = struct.unpack('>L', packet[: 4])[0]
  367. description, foo = getNS(packet[4:])
  368. self.receiveError(reasonCode, description)
  369. self.transport.loseConnection()
  370. def ssh_IGNORE(self, packet):
  371. """
  372. Called when we receieve a MSG_IGNORE message. No payload.
  373. This means nothing; we simply return.
  374. """
  375. def ssh_UNIMPLEMENTED(self, packet):
  376. """
  377. Called when we receieve a MSG_UNIMPLEMENTED message. Payload::
  378. long packet
  379. This means that the other side did not implement one of our packets.
  380. """
  381. seqnum, = struct.unpack('>L', packet)
  382. self.receiveUnimplemented(seqnum)
  383. def ssh_DEBUG(self, packet):
  384. """
  385. Called when we receieve a MSG_DEBUG message. Payload::
  386. bool alwaysDisplay
  387. string message
  388. string language
  389. This means the other side has passed along some debugging info.
  390. """
  391. alwaysDisplay = bool(packet[0])
  392. message, lang, foo = getNS(packet[1:], 2)
  393. self.receiveDebug(alwaysDisplay, message, lang)
  394. def setService(self, service):
  395. """
  396. Set our service to service and start it running. If we were
  397. running a service previously, stop it first.
  398. @type service: C{SSHService}
  399. """
  400. log.msg('starting service %s' % service.name)
  401. if self.service:
  402. self.service.serviceStopped()
  403. self.service = service
  404. service.transport = self
  405. self.service.serviceStarted()
  406. def sendDebug(self, message, alwaysDisplay=False, language=''):
  407. """
  408. Send a debug message to the other side.
  409. @param message: the message to send.
  410. @type message: C{str}
  411. @param alwaysDisplay: if True, tell the other side to always
  412. display this message.
  413. @type alwaysDisplay: C{bool}
  414. @param language: optionally, the language the message is in.
  415. @type language: C{str}
  416. """
  417. self.sendPacket(MSG_DEBUG, chr(alwaysDisplay) + NS(message) +
  418. NS(language))
  419. def sendIgnore(self, message):
  420. """
  421. Send a message that will be ignored by the other side. This is
  422. useful to fool attacks based on guessing packet sizes in the
  423. encrypted stream.
  424. @param message: data to send with the message
  425. @type message: C{str}
  426. """
  427. self.sendPacket(MSG_IGNORE, NS(message))
  428. def sendUnimplemented(self):
  429. """
  430. Send a message to the other side that the last packet was not
  431. understood.
  432. """
  433. seqnum = self.incomingPacketSequence
  434. self.sendPacket(MSG_UNIMPLEMENTED, struct.pack('!L', seqnum))
  435. def sendDisconnect(self, reason, desc):
  436. """
  437. Send a disconnect message to the other side and then disconnect.
  438. @param reason: the reason for the disconnect. Should be one of the
  439. DISCONNECT_* values.
  440. @type reason: C{int}
  441. @param desc: a descrption of the reason for the disconnection.
  442. @type desc: C{str}
  443. """
  444. self.sendPacket(
  445. MSG_DISCONNECT, struct.pack('>L', reason) + NS(desc) + NS(''))
  446. log.msg('Disconnecting with error, code %s\nreason: %s' % (reason,
  447. desc))
  448. self.transport.loseConnection()
  449. def _getKey(self, c, sharedSecret, exchangeHash):
  450. """
  451. Get one of the keys for authentication/encryption.
  452. @type c: C{str}
  453. @type sharedSecret: C{str}
  454. @type exchangeHash: C{str}
  455. """
  456. k1 = sha1(sharedSecret + exchangeHash + c + self.sessionID)
  457. k1 = k1.digest()
  458. k2 = sha1(sharedSecret + exchangeHash + k1).digest()
  459. return k1 + k2
  460. def _keySetup(self, sharedSecret, exchangeHash):
  461. """
  462. Set up the keys for the connection and sends MSG_NEWKEYS when
  463. finished,
  464. @param sharedSecret: a secret string agreed upon using a Diffie-
  465. Hellman exchange, so it is only shared between
  466. the server and the client.
  467. @type sharedSecret: C{str}
  468. @param exchangeHash: A hash of various data known by both sides.
  469. @type exchangeHash: C{str}
  470. """
  471. if not self.sessionID:
  472. self.sessionID = exchangeHash
  473. initIVCS = self._getKey('A', sharedSecret, exchangeHash)
  474. initIVSC = self._getKey('B', sharedSecret, exchangeHash)
  475. encKeyCS = self._getKey('C', sharedSecret, exchangeHash)
  476. encKeySC = self._getKey('D', sharedSecret, exchangeHash)
  477. integKeyCS = self._getKey('E', sharedSecret, exchangeHash)
  478. integKeySC = self._getKey('F', sharedSecret, exchangeHash)
  479. outs = [initIVSC, encKeySC, integKeySC]
  480. ins = [initIVCS, encKeyCS, integKeyCS]
  481. if self.isClient: # reverse for the client
  482. log.msg('REVERSE')
  483. outs, ins = ins, outs
  484. self.nextEncryptions.setKeys(outs[0], outs[1], ins[0], ins[1],
  485. outs[2], ins[2])
  486. self.sendPacket(MSG_NEWKEYS, '')
  487. def isEncrypted(self, direction="out"):
  488. """
  489. Return True if the connection is encrypted in the given direction.
  490. Direction must be one of ["out", "in", "both"].
  491. """
  492. if direction == "out":
  493. return self.currentEncryptions.outCipType != 'none'
  494. elif direction == "in":
  495. return self.currentEncryptions.inCipType != 'none'
  496. elif direction == "both":
  497. return self.isEncrypted("in") and self.isEncrypted("out")
  498. else:
  499. raise TypeError('direction must be "out", "in", or "both"')
  500. def isVerified(self, direction="out"):
  501. """
  502. Return True if the connecction is verified/authenticated in the
  503. given direction. Direction must be one of ["out", "in", "both"].
  504. """
  505. if direction == "out":
  506. return self.currentEncryptions.outMACType != 'none'
  507. elif direction == "in":
  508. return self.currentEncryptions.inMACType != 'none'
  509. elif direction == "both":
  510. return self.isVerified("in")and self.isVerified("out")
  511. else:
  512. raise TypeError('direction must be "out", "in", or "both"')
  513. def loseConnection(self):
  514. """
  515. Lose the connection to the other side, sending a
  516. DISCONNECT_CONNECTION_LOST message.
  517. """
  518. self.sendDisconnect(DISCONNECT_CONNECTION_LOST,
  519. "user closed connection")
  520. # client methods
  521. def receiveError(self, reasonCode, description):
  522. """
  523. Called when we receive a disconnect error message from the other
  524. side.
  525. @param reasonCode: the reason for the disconnect, one of the
  526. DISCONNECT_ values.
  527. @type reasonCode: C{int}
  528. @param description: a human-readable description of the
  529. disconnection.
  530. @type description: C{str}
  531. """
  532. log.msg('Got remote error, code %s\nreason: %s' % (reasonCode,
  533. description))
  534. def receiveUnimplemented(self, seqnum):
  535. """
  536. Called when we receive an unimplemented packet message from the other
  537. side.
  538. @param seqnum: the sequence number that was not understood.
  539. @type seqnum: C{int}
  540. """
  541. log.msg('other side unimplemented packet #%s' % seqnum)
  542. def receiveDebug(self, alwaysDisplay, message, lang):
  543. """
  544. Called when we receive a debug message from the other side.
  545. @param alwaysDisplay: if True, this message should always be
  546. displayed.
  547. @type alwaysDisplay: C{bool}
  548. @param message: the debug message
  549. @type message: C{str}
  550. @param lang: optionally the language the message is in.
  551. @type lang: C{str}
  552. """
  553. if alwaysDisplay:
  554. log.msg('Remote Debug Message: %s' % message)
  555. class SSHServerTransport(SSHTransportBase):
  556. """
  557. SSHServerTransport implements the server side of the SSH protocol.
  558. @ivar isClient: since we are never the client, this is always False.
  559. @ivar ignoreNextPacket: if True, ignore the next key exchange packet. This
  560. is set when the client sends a guessed key exchange packet but with
  561. an incorrect guess.
  562. @ivar dhGexRequest: the KEX_DH_GEX_REQUEST(_OLD) that the client sent.
  563. The key generation needs this to be stored.
  564. @ivar g: the Diffie-Hellman group generator.
  565. @ivar p: the Diffie-Hellman group prime.
  566. """
  567. isClient = False
  568. ignoreNextPacket = 0
  569. def ssh_KEXINIT(self, packet):
  570. """
  571. Called when we receive a MSG_KEXINIT message. For a description
  572. of the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally,
  573. this method checks if a guessed key exchange packet was sent. If
  574. it was sent, and it guessed incorrectly, the next key exchange
  575. packet MUST be ignored.
  576. """
  577. retval = SSHTransportBase.ssh_KEXINIT(self, packet)
  578. if not retval: # disconnected
  579. return
  580. else:
  581. kexAlgs, keyAlgs, rest = retval
  582. if ord(rest[0]): # first_kex_packet_follows
  583. if (kexAlgs[0] != self.supportedKeyExchanges[0] or
  584. keyAlgs[0] != self.supportedPublicKeys[0]):
  585. self.ignoreNextPacket = True # guess was wrong
  586. def ssh_KEX_DH_GEX_REQUEST_OLD(self, packet):
  587. """
  588. This represents two different key exchange methods that share the
  589. same integer value.
  590. KEXDH_INIT (for diffie-hellman-group1-sha1 exchanges) payload::
  591. integer e (the client's Diffie-Hellman public key)
  592. We send the KEXDH_REPLY with our host key and signature.
  593. KEX_DH_GEX_REQUEST_OLD (for diffie-hellman-group-exchange-sha1)
  594. payload::
  595. integer ideal (ideal size for the Diffie-Hellman prime)
  596. We send the KEX_DH_GEX_GROUP message with the group that is
  597. closest in size to ideal.
  598. If we were told to ignore the next key exchange packet by
  599. ssh_KEXINIT, drop it on the floor and return.
  600. """
  601. if self.ignoreNextPacket:
  602. self.ignoreNextPacket = 0
  603. return
  604. if self.kexAlg == 'diffie-hellman-group1-sha1':
  605. # this is really KEXDH_INIT
  606. clientDHpublicKey, foo = getMP(packet)
  607. y = Util.number.getRandomNumber(512, randbytes.secureRandom)
  608. serverDHpublicKey = _MPpow(DH_GENERATOR, y, DH_PRIME)
  609. sharedSecret = _MPpow(clientDHpublicKey, y, DH_PRIME)
  610. h = sha1()
  611. h.update(NS(self.otherVersionString))
  612. h.update(NS(self.ourVersionString))
  613. h.update(NS(self.otherKexInitPayload))
  614. h.update(NS(self.ourKexInitPayload))
  615. h.update(NS(self.factory.publicKeys[self.keyAlg].blob()))
  616. h.update(MP(clientDHpublicKey))
  617. h.update(serverDHpublicKey)
  618. h.update(sharedSecret)
  619. exchangeHash = h.digest()
  620. self.sendPacket(
  621. MSG_KEXDH_REPLY,
  622. NS(self.factory.publicKeys[self.keyAlg].blob()) +
  623. serverDHpublicKey +
  624. NS(self.factory.privateKeys[self.keyAlg].sign(exchangeHash)))
  625. self._keySetup(sharedSecret, exchangeHash)
  626. elif self.kexAlg == 'diffie-hellman-group-exchange-sha1':
  627. self.dhGexRequest = packet
  628. ideal = struct.unpack('>L', packet)[0]
  629. self.g, self.p = self.factory.getDHPrime(ideal)
  630. self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p) + MP(self.g))
  631. else:
  632. raise error.ConchError('bad kexalg: %s' % self.kexAlg)
  633. def ssh_KEX_DH_GEX_REQUEST(self, packet):
  634. """
  635. Called when we receive a MSG_KEX_DH_GEX_REQUEST message. Payload::
  636. integer minimum
  637. integer ideal
  638. integer maximum
  639. The client is asking for a Diffie-Hellman group between minimum and
  640. maximum size, and close to ideal if possible. We reply with a
  641. MSG_KEX_DH_GEX_GROUP message.
  642. If we were told to ignore the next key exchange packekt by
  643. ssh_KEXINIT, drop it on the floor and return.
  644. """
  645. if self.ignoreNextPacket:
  646. self.ignoreNextPacket = 0
  647. return
  648. self.dhGexRequest = packet
  649. min, ideal, max = struct.unpack('>3L', packet)
  650. self.g, self.p = self.factory.getDHPrime(ideal)
  651. self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p) + MP(self.g))
  652. def ssh_KEX_DH_GEX_INIT(self, packet):
  653. """
  654. Called when we get a MSG_KEX_DH_GEX_INIT message. Payload::
  655. integer e (client DH public key)
  656. We send the MSG_KEX_DH_GEX_REPLY message with our host key and
  657. signature.
  658. """
  659. clientDHpublicKey, foo = getMP(packet)
  660. # TODO: we should also look at the value they send to us and reject
  661. # insecure values of f (if g==2 and f has a single '1' bit while the
  662. # rest are '0's, then they must have used a small y also).
  663. # TODO: This could be computed when self.p is set up
  664. # or do as openssh does and scan f for a single '1' bit instead
  665. pSize = Util.number.size(self.p)
  666. y = Util.number.getRandomNumber(pSize, randbytes.secureRandom)
  667. serverDHpublicKey = _MPpow(self.g, y, self.p)
  668. sharedSecret = _MPpow(clientDHpublicKey, y, self.p)
  669. h = sha1()
  670. h.update(NS(self.otherVersionString))
  671. h.update(NS(self.ourVersionString))
  672. h.update(NS(self.otherKexInitPayload))
  673. h.update(NS(self.ourKexInitPayload))
  674. h.update(NS(self.factory.publicKeys[self.keyAlg].blob()))
  675. h.update(self.dhGexRequest)
  676. h.update(MP(self.p))
  677. h.update(MP(self.g))
  678. h.update(MP(clientDHpublicKey))
  679. h.update(serverDHpublicKey)
  680. h.update(sharedSecret)
  681. exchangeHash = h.digest()
  682. self.sendPacket(
  683. MSG_KEX_DH_GEX_REPLY,
  684. NS(self.factory.publicKeys[self.keyAlg].blob()) +
  685. serverDHpublicKey +
  686. NS(self.factory.privateKeys[self.keyAlg].sign(exchangeHash)))
  687. self._keySetup(sharedSecret, exchangeHash)
  688. def ssh_NEWKEYS(self, packet):
  689. """
  690. Called when we get a MSG_NEWKEYS message. No payload.
  691. When we get this, the keys have been set on both sides, and we
  692. start using them to encrypt and authenticate the connection.
  693. """
  694. log.msg('NEW KEYS')
  695. if packet != '':
  696. self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
  697. "NEWKEYS takes no data")
  698. return
  699. self.currentEncryptions = self.nextEncryptions
  700. if self.outgoingCompressionType == 'zlib':
  701. self.outgoingCompression = zlib.compressobj(6)
  702. if self.incomingCompressionType == 'zlib':
  703. self.incomingCompression = zlib.decompressobj()
  704. def ssh_SERVICE_REQUEST(self, packet):
  705. """
  706. Called when we get a MSG_SERVICE_REQUEST message. Payload::
  707. string serviceName
  708. The client has requested a service. If we can start the service,
  709. start it; otherwise, disconnect with
  710. DISCONNECT_SERVICE_NOT_AVAILABLE.
  711. """
  712. service, rest = getNS(packet)
  713. cls = self.factory.getService(self, service)
  714. if not cls:
  715. self.sendDisconnect(DISCONNECT_SERVICE_NOT_AVAILABLE,
  716. "don't have service %s" % service)
  717. return
  718. else:
  719. self.sendPacket(MSG_SERVICE_ACCEPT, NS(service))
  720. self.setService(cls())
  721. class SSHClientTransport(SSHTransportBase):
  722. """
  723. SSHClientTransport implements the client side of the SSH protocol.
  724. @ivar isClient: since we are always the client, this is always True.
  725. @ivar _gotNewKeys: if we receive a MSG_NEWKEYS message before we are
  726. ready to transition to the new keys, this is set to True so we
  727. can transition when the keys are ready locally.
  728. @ivar x: our Diffie-Hellman private key.
  729. @ivar e: our Diffie-Hellman public key.
  730. @ivar g: the Diffie-Hellman group generator.
  731. @ivar p: the Diffie-Hellman group prime
  732. @ivar instance: the SSHService object we are requesting.
  733. """
  734. isClient = True
  735. def connectionMade(self):
  736. """
  737. Called when the connection is started with the server. Just sets
  738. up a private instance variable.
  739. """
  740. SSHTransportBase.connectionMade(self)
  741. self._gotNewKeys = 0
  742. def ssh_KEXINIT(self, packet):
  743. """
  744. Called when we receive a MSG_KEXINIT message. For a description
  745. of the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally,
  746. this method sends the first key exchange packet. If the agreed-upon
  747. exchange is diffie-hellman-group1-sha1, generate a public key
  748. and send it in a MSG_KEXDH_INIT message. If the exchange is
  749. diffie-hellman-group-exchange-sha1, ask for a 2048 bit group with a
  750. MSG_KEX_DH_GEX_REQUEST_OLD message.
  751. """
  752. if SSHTransportBase.ssh_KEXINIT(self, packet) is None:
  753. return # we disconnected
  754. if self.kexAlg == 'diffie-hellman-group1-sha1':
  755. self.x = Util.number.getRandomNumber(512, randbytes.secureRandom)
  756. self.e = _MPpow(DH_GENERATOR, self.x, DH_PRIME)
  757. self.sendPacket(MSG_KEXDH_INIT, self.e)
  758. elif self.kexAlg == 'diffie-hellman-group-exchange-sha1':
  759. self.sendPacket(MSG_KEX_DH_GEX_REQUEST_OLD, '\x00\x00\x08\x00')
  760. else:
  761. raise error.ConchError("somehow, the kexAlg has been set "
  762. "to something we don't support")
  763. def ssh_KEX_DH_GEX_GROUP(self, packet):
  764. """
  765. This handles two different message which share an integer value.
  766. If the key exchange is diffie-hellman-group1-sha1, this is
  767. MSG_KEXDH_REPLY. Payload::
  768. string serverHostKey
  769. integer f (server Diffie-Hellman public key)
  770. string signature
  771. We verify the host key by calling verifyHostKey, then continue in
  772. _continueKEXDH_REPLY.
  773. If the key exchange is diffie-hellman-group-exchange-sha1, this is
  774. MSG_KEX_DH_GEX_GROUP. Payload::
  775. string g (group generator)
  776. string p (group prime)
  777. We generate a Diffie-Hellman public key and send it in a
  778. MSG_KEX_DH_GEX_INIT message.
  779. """
  780. if self.kexAlg == 'diffie-hellman-group1-sha1':
  781. # actually MSG_KEXDH_REPLY
  782. pubKey, packet = getNS(packet)
  783. f, packet = getMP(packet)
  784. signature, packet = getNS(packet)
  785. fingerprint = ':'.join([ch.encode('hex') for ch in
  786. md5(pubKey).digest()])
  787. d = self.verifyHostKey(pubKey, fingerprint)
  788. d.addCallback(self._continueKEXDH_REPLY, pubKey, f, signature)
  789. d.addErrback(
  790. lambda unused: self.sendDisconnect(
  791. DISCONNECT_HOST_KEY_NOT_VERIFIABLE, 'bad host key'))
  792. return d
  793. else:
  794. self.p, rest = getMP(packet)
  795. self.g, rest = getMP(rest)
  796. self.x = Util.number.getRandomNumber(320, randbytes.secureRandom)
  797. self.e = _MPpow(self.g, self.x, self.p)
  798. self.sendPacket(MSG_KEX_DH_GEX_INIT, self.e)
  799. def _continueKEXDH_REPLY(self, ignored, pubKey, f, signature):
  800. """
  801. The host key has been verified, so we generate the keys.
  802. @param pubKey: the public key blob for the server's public key.
  803. @type pubKey: C{str}
  804. @param f: the server's Diffie-Hellman public key.
  805. @type f: C{long}
  806. @param signature: the server's signature, verifying that it has the
  807. correct private key.
  808. @type signature: C{str}
  809. """
  810. serverKey = keys.Key.fromString(pubKey)
  811. sharedSecret = _MPpow(f, self.x, DH_PRIME)
  812. h = sha1()
  813. h.update(NS(self.ourVersionString))
  814. h.update(NS(self.otherVersionString))
  815. h.update(NS(self.ourKexInitPayload))
  816. h.update(NS(self.otherKexInitPayload))
  817. h.update(NS(pubKey))
  818. h.update(self.e)
  819. h.update(MP(f))
  820. h.update(sharedSecret)
  821. exchangeHash = h.digest()
  822. if not serverKey.verify(signature, exchangeHash):
  823. self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
  824. 'bad signature')
  825. return
  826. self._keySetup(sharedSecret, exchangeHash)
  827. def ssh_KEX_DH_GEX_REPLY(self, packet):
  828. """
  829. Called when we receieve a MSG_KEX_DH_GEX_REPLY message. Payload::
  830. string server host key
  831. integer f (server DH public key)
  832. We verify the host key by calling verifyHostKey, then continue in
  833. _continueGEX_REPLY.
  834. """
  835. pubKey, packet = getNS(packet)
  836. f, packet = getMP(packet)
  837. signature, packet = getNS(packet)
  838. fingerprint = ':'.join(map(lambda c: '%02x'%ord(c),
  839. md5(pubKey).digest()))
  840. d = self.verifyHostKey(pubKey, fingerprint)
  841. d.addCallback(self._continueGEX_REPLY, pubKey, f, signature)
  842. d.addErrback(
  843. lambda unused: self.sendDisconnect(
  844. DISCONNECT_HOST_KEY_NOT_VERIFIABLE, 'bad host key'))
  845. return d
  846. def _continueGEX_REPLY(self, ignored, pubKey, f, signature):
  847. """
  848. The host key has been verified, so we generate the keys.
  849. @param pubKey: the public key blob for the server's public key.
  850. @type pubKey: C{str}
  851. @param f: the server's Diffie-Hellman public key.
  852. @type f: C{long}
  853. @param signature: the server's signature, verifying that it has the
  854. correct private key.
  855. @type signature: C{str}
  856. """
  857. serverKey = keys.Key.fromString(pubKey)
  858. sharedSecret = _MPpow(f, self.x, self.p)
  859. h = sha1()
  860. h.update(NS(self.ourVersionString))
  861. h.update(NS(self.otherVersionString))
  862. h.update(NS(self.ourKexInitPayload))
  863. h.update(NS(self.otherKexInitPayload))
  864. h.update(NS(pubKey))
  865. h.update('\x00\x00\x08\x00')
  866. h.update(MP(self.p))
  867. h.update(MP(self.g))
  868. h.update(self.e)
  869. h.update(MP(f))
  870. h.update(sharedSecret)
  871. exchangeHash = h.digest()
  872. if not serverKey.verify(signature, exchangeHash):
  873. self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
  874. 'bad signature')
  875. return
  876. self._keySetup(sharedSecret, exchangeHash)
  877. def _keySetup(self, sharedSecret, exchangeHash):
  878. """
  879. See SSHTransportBase._keySetup().
  880. """
  881. SSHTransportBase._keySetup(self, sharedSecret, exchangeHash)
  882. if self._gotNewKeys:
  883. self.ssh_NEWKEYS('')
  884. def ssh_NEWKEYS(self, packet):
  885. """
  886. Called when we receieve a MSG_NEWKEYS message. No payload.
  887. If we've finished setting up our own keys, start using them.
  888. Otherwise, remeber that we've receieved this message.
  889. """
  890. if packet != '':
  891. self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
  892. "NEWKEYS takes no data")
  893. return
  894. if not self.nextEncryptions.encBlockSize:
  895. self._gotNewKeys = 1
  896. return
  897. log.msg('NEW KEYS')
  898. self.currentEncryptions = self.nextEncryptions
  899. if self.outgoingCompressionType == 'zlib':
  900. self.outgoingCompression = zlib.compressobj(6)
  901. if self.incomingCompressionType == 'zlib':
  902. self.incomingCompression = zlib.decompressobj()
  903. self.connectionSecure()
  904. def ssh_SERVICE_ACCEPT(self, packet):
  905. """
  906. Called when we receieve a MSG_SERVICE_ACCEPT message. Payload::
  907. string service name
  908. Start the service we requested.
  909. """
  910. name = getNS(packet)[0]
  911. if name != self.instance.name:
  912. self.sendDisconnect(
  913. DISCONNECT_PROTOCOL_ERROR,
  914. "received accept for service we did not request")
  915. self.setService(self.instance)
  916. def requestService(self, instance):
  917. """
  918. Request that a service be run over this transport.
  919. @type instance: subclass of L{twisted.conch.ssh.service.SSHService}
  920. """
  921. self.sendPacket(MSG_SERVICE_REQUEST, NS(instance.name))
  922. self.instance = instance
  923. # client methods
  924. def verifyHostKey(self, hostKey, fingerprint):
  925. """
  926. Returns a Deferred that gets a callback if it is a valid key, or
  927. an errback if not.
  928. @type hostKey: C{str}
  929. @type fingerprint: C{str}
  930. @rtype: L{twisted.internet.defer.Deferred}
  931. """
  932. # return if it's good
  933. return defer.fail(NotImplementedError())
  934. def connectionSecure(self):
  935. """
  936. Called when the encryption has been set up. Generally,
  937. requestService() is called to run another service over the transport.
  938. """
  939. raise NotImplementedError()
  940. class _DummyCipher:
  941. """
  942. A cipher for the none encryption method.
  943. @ivar block_size: the block size of the encryption. In the case of the
  944. none cipher, this is 8 bytes.
  945. """
  946. block_size = 8
  947. def encrypt(self, x):
  948. return x
  949. decrypt = encrypt
  950. class SSHCiphers:
  951. """
  952. SSHCiphers represents all the encryption operations that need to occur
  953. to encrypt and authenticate the SSH connection.
  954. @cvar cipherMap: A dictionary mapping SSH encryption names to 3-tuples of
  955. (<Crypto.Cipher.* name>, <block size>, <counter mode>)
  956. @cvar macMap: A dictionary mapping SSH MAC names to hash modules.
  957. @ivar outCipType: the string type of the outgoing cipher.
  958. @ivar inCipType: the string type of the incoming cipher.
  959. @ivar outMACType: the string type of the incoming MAC.
  960. @ivar inMACType: the string type of the incoming MAC.
  961. @ivar encBlockSize: the block size of the outgoing cipher.
  962. @ivar decBlockSize: the block size of the incoming cipher.
  963. @ivar verifyDigestSize: the size of the incoming MAC.
  964. @ivar outMAC: a tuple of (<hash module>, <inner key>, <outer key>,
  965. <digest size>) representing the outgoing MAC.
  966. @ivar inMAc: see outMAC, but for the incoming MAC.
  967. """
  968. cipherMap = {
  969. '3des-cbc':('DES3', 24, 0),
  970. 'blowfish-cbc':('Blowfish', 16,0 ),
  971. 'aes256-cbc':('AES', 32, 0),
  972. 'aes192-cbc':('AES', 24, 0),
  973. 'aes128-cbc':('AES', 16, 0),
  974. 'cast128-cbc':('CAST', 16, 0),
  975. 'aes128-ctr':('AES', 16, 1),
  976. 'aes192-ctr':('AES', 24, 1),
  977. 'aes256-ctr':('AES', 32, 1),
  978. '3des-ctr':('DES3', 24, 1),
  979. 'blowfish-ctr':('Blowfish', 16, 1),
  980. 'cast128-ctr':('CAST', 16, 1),
  981. 'none':(None, 0, 0),
  982. }
  983. macMap = {
  984. 'hmac-sha1': sha1,
  985. 'hmac-md5': md5,
  986. 'none': None
  987. }
  988. def __init__(self, outCip, inCip, outMac, inMac):
  989. self.outCipType = outCip
  990. self.inCipType = inCip
  991. self.outMACType = outMac
  992. self.inMACType = inMac
  993. self.encBlockSize = 0
  994. self.decBlockSize = 0
  995. self.verifyDigestSize = 0
  996. self.outMAC = (None, '', '', 0)
  997. self.inMAC = (None, '', '', 0)
  998. def setKeys(self, outIV, outKey, inIV, inKey, outInteg, inInteg):
  999. """
  1000. Set up the ciphers and hashes using the given keys,
  1001. @param outIV: the outgoing initialization vector
  1002. @param outKey: the outgoing encryption key
  1003. @param inIV: the incoming initialization vector
  1004. @param inKey: the incoming encryption key
  1005. @param outInteg: the outgoing integrity key
  1006. @param inInteg: the incoming integrity key.
  1007. """
  1008. o = self._getCipher(self.outCipType, outIV, outKey)
  1009. self.encrypt = o.encrypt
  1010. self.encBlockSize = o.block_size
  1011. o = self._getCipher(self.inCipType, inIV, inKey)
  1012. self.decrypt = o.decrypt
  1013. self.decBlockSize = o.block_size
  1014. self.outMAC = self._getMAC(self.outMACType, outInteg)
  1015. self.inMAC = self._getMAC(self.inMACType, inInteg)
  1016. if self.inMAC:
  1017. self.verifyDigestSize = self.inMAC[3]
  1018. def _getCipher(self, cip, iv, key):
  1019. """
  1020. Creates an initialized cipher object.
  1021. @param cip: the name of the cipher: maps into Crypto.Cipher.*
  1022. @param iv: the initialzation vector
  1023. @param key: the encryption key
  1024. """
  1025. modName, keySize, counterMode = self.cipherMap[cip]
  1026. if not modName: # no cipher
  1027. return _DummyCipher()
  1028. mod = __import__('Crypto.Cipher.%s'%modName, {}, {}, 'x')
  1029. if counterMode:
  1030. return mod.new(key[:keySize], mod.MODE_CTR, iv[:mod.block_size],
  1031. counter=_Counter(iv, mod.block_size))
  1032. else:
  1033. return mod.new(key[:keySize], mod.MODE_CBC, iv[:mod.block_size])
  1034. def _getMAC(self, mac, key):
  1035. """
  1036. Gets a 4-tuple representing the message authentication code.
  1037. (<hash module>, <inner hash value>, <outer hash value>,
  1038. <digest size>)
  1039. @param mac: a key mapping into macMap
  1040. @type mac: C{str}
  1041. @param key: the MAC key.
  1042. @type key: C{str}
  1043. """
  1044. mod = self.macMap[mac]
  1045. if not mod:
  1046. return (None, '', '', 0)
  1047. ds = mod().digest_size
  1048. key = key[:ds] + '\x00' * (64 - ds)
  1049. i = XOR.new('\x36').encrypt(key)
  1050. o = XOR.new('\x5c').encrypt(key)
  1051. return mod, i, o, ds
  1052. def encrypt(self, blocks):
  1053. """
  1054. Encrypt blocks. Overridden by the encrypt method of a
  1055. Crypto.Cipher.* object in setKeys().
  1056. @type blocks: C{str}
  1057. """
  1058. raise NotImplementedError()
  1059. def decrypt(self, blocks):
  1060. """
  1061. Decrypt blocks. See encrypt().
  1062. @type blocks: C{str}
  1063. """
  1064. raise NotImplementedError()
  1065. def makeMAC(self, seqid, data):
  1066. """
  1067. Create a message authentication code (MAC) for the given packet using
  1068. the outgoing MAC values.
  1069. @param seqid: the sequence ID of the outgoing packet
  1070. @type seqid: C{int}
  1071. @param data: the data to create a MAC for
  1072. @type data: C{str}
  1073. @rtype: C{str}
  1074. """
  1075. if not self.outMAC[0]:
  1076. return ''
  1077. data = struct.pack('>L', seqid) + data
  1078. mod, i, o, ds = self.outMAC
  1079. inner = mod(i + data)
  1080. outer = mod(o + inner.digest())
  1081. return outer.digest()
  1082. def verify(self, seqid, data, mac):
  1083. """
  1084. Verify an incoming MAC using the incoming MAC values. Return True
  1085. if the MAC is valid.
  1086. @param seqid: the sequence ID of the incoming packet
  1087. @type seqid: C{int}
  1088. @param data: the packet data to verify
  1089. @type data: C{str}
  1090. @param mac: the MAC sent with the packet
  1091. @type mac: C{str}
  1092. @rtype: C{bool}
  1093. """
  1094. if not self.inMAC[0]:
  1095. return mac == ''
  1096. data = struct.pack('>L', seqid) + data
  1097. mod, i, o, ds = self.inMAC
  1098. inner = mod(i + data)
  1099. outer = mod(o + inner.digest())
  1100. return mac == outer.digest()
  1101. class _Counter:
  1102. """
  1103. Stateful counter which returns results packed in a byte string
  1104. """
  1105. def __init__(self, initialVector, blockSize):
  1106. """
  1107. @type initialVector: C{str}
  1108. @param initialVector: A byte string representing the initial counter
  1109. value.
  1110. @type blockSize: C{int}
  1111. @param blockSize: The length of the output buffer, as well as the
  1112. number of bytes at the beginning of C{initialVector} to consider.
  1113. """
  1114. initialVector = initialVector[:blockSize]
  1115. self.count = getMP('\xff\xff\xff\xff' + initialVector)[0]
  1116. self.blockSize = blockSize
  1117. self.count = Util.number.long_to_bytes(self.count - 1)
  1118. self.count = '\x00' * (self.blockSize - len(self.count)) + self.count
  1119. self.count = array.array('c', self.count)
  1120. self.len = len(self.count) - 1
  1121. def __call__(self):
  1122. """
  1123. Increment the counter and return the new value.
  1124. """
  1125. i = self.len
  1126. while i > -1:
  1127. self.count[i] = n = chr((ord(self.count[i]) + 1) % 256)
  1128. if n == '\x00':