userauth.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. # -*- test-case-name: twisted.conch.test.test_userauth -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Implementation of the ssh-userauth service.
  6. Currently implemented authentication types are public-key and password.
  7. Maintainer: Paul Swartz
  8. """
  9. from __future__ import absolute_import, division
  10. import struct
  11. from twisted.conch import error, interfaces
  12. from twisted.conch.ssh import keys, transport, service
  13. from twisted.conch.ssh.common import NS, getNS
  14. from twisted.cred import credentials
  15. from twisted.cred.error import UnauthorizedLogin
  16. from twisted.internet import defer, reactor
  17. from twisted.python import failure, log
  18. from twisted.python.compat import nativeString, _bytesChr as chr
  19. class SSHUserAuthServer(service.SSHService):
  20. """
  21. A service implementing the server side of the 'ssh-userauth' service. It
  22. is used to authenticate the user on the other side as being able to access
  23. this server.
  24. @ivar name: the name of this service: 'ssh-userauth'
  25. @type name: L{bytes}
  26. @ivar authenticatedWith: a list of authentication methods that have
  27. already been used.
  28. @type authenticatedWith: L{list}
  29. @ivar loginTimeout: the number of seconds we wait before disconnecting
  30. the user for taking too long to authenticate
  31. @type loginTimeout: L{int}
  32. @ivar attemptsBeforeDisconnect: the number of failed login attempts we
  33. allow before disconnecting.
  34. @type attemptsBeforeDisconnect: L{int}
  35. @ivar loginAttempts: the number of login attempts that have been made
  36. @type loginAttempts: L{int}
  37. @ivar passwordDelay: the number of seconds to delay when the user gives
  38. an incorrect password
  39. @type passwordDelay: L{int}
  40. @ivar interfaceToMethod: a L{dict} mapping credential interfaces to
  41. authentication methods. The server checks to see which of the
  42. cred interfaces have checkers and tells the client that those methods
  43. are valid for authentication.
  44. @type interfaceToMethod: L{dict}
  45. @ivar supportedAuthentications: A list of the supported authentication
  46. methods.
  47. @type supportedAuthentications: L{list} of L{bytes}
  48. @ivar user: the last username the client tried to authenticate with
  49. @type user: L{bytes}
  50. @ivar method: the current authentication method
  51. @type method: L{bytes}
  52. @ivar nextService: the service the user wants started after authentication
  53. has been completed.
  54. @type nextService: L{bytes}
  55. @ivar portal: the L{twisted.cred.portal.Portal} we are using for
  56. authentication
  57. @type portal: L{twisted.cred.portal.Portal}
  58. @ivar clock: an object with a callLater method. Stubbed out for testing.
  59. """
  60. name = b'ssh-userauth'
  61. loginTimeout = 10 * 60 * 60
  62. # 10 minutes before we disconnect them
  63. attemptsBeforeDisconnect = 20
  64. # 20 login attempts before a disconnect
  65. passwordDelay = 1 # number of seconds to delay on a failed password
  66. clock = reactor
  67. interfaceToMethod = {
  68. credentials.ISSHPrivateKey : b'publickey',
  69. credentials.IUsernamePassword : b'password',
  70. }
  71. def serviceStarted(self):
  72. """
  73. Called when the userauth service is started. Set up instance
  74. variables, check if we should allow password authentication (only
  75. allow if the outgoing connection is encrypted) and set up a login
  76. timeout.
  77. """
  78. self.authenticatedWith = []
  79. self.loginAttempts = 0
  80. self.user = None
  81. self.nextService = None
  82. self.portal = self.transport.factory.portal
  83. self.supportedAuthentications = []
  84. for i in self.portal.listCredentialsInterfaces():
  85. if i in self.interfaceToMethod:
  86. self.supportedAuthentications.append(self.interfaceToMethod[i])
  87. if not self.transport.isEncrypted('in'):
  88. # don't let us transport password in plaintext
  89. if b'password' in self.supportedAuthentications:
  90. self.supportedAuthentications.remove(b'password')
  91. self._cancelLoginTimeout = self.clock.callLater(
  92. self.loginTimeout,
  93. self.timeoutAuthentication)
  94. def serviceStopped(self):
  95. """
  96. Called when the userauth service is stopped. Cancel the login timeout
  97. if it's still going.
  98. """
  99. if self._cancelLoginTimeout:
  100. self._cancelLoginTimeout.cancel()
  101. self._cancelLoginTimeout = None
  102. def timeoutAuthentication(self):
  103. """
  104. Called when the user has timed out on authentication. Disconnect
  105. with a DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE message.
  106. """
  107. self._cancelLoginTimeout = None
  108. self.transport.sendDisconnect(
  109. transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
  110. b'you took too long')
  111. def tryAuth(self, kind, user, data):
  112. """
  113. Try to authenticate the user with the given method. Dispatches to a
  114. auth_* method.
  115. @param kind: the authentication method to try.
  116. @type kind: L{bytes}
  117. @param user: the username the client is authenticating with.
  118. @type user: L{bytes}
  119. @param data: authentication specific data sent by the client.
  120. @type data: L{bytes}
  121. @return: A Deferred called back if the method succeeded, or erred back
  122. if it failed.
  123. @rtype: C{defer.Deferred}
  124. """
  125. log.msg('%r trying auth %r' % (user, kind))
  126. if kind not in self.supportedAuthentications:
  127. return defer.fail(
  128. error.ConchError('unsupported authentication, failing'))
  129. kind = nativeString(kind.replace(b'-', b'_'))
  130. f = getattr(self, 'auth_%s' % (kind,), None)
  131. if f:
  132. ret = f(data)
  133. if not ret:
  134. return defer.fail(
  135. error.ConchError(
  136. '%s return None instead of a Deferred'
  137. % (kind, )))
  138. else:
  139. return ret
  140. return defer.fail(error.ConchError('bad auth type: %s' % (kind,)))
  141. def ssh_USERAUTH_REQUEST(self, packet):
  142. """
  143. The client has requested authentication. Payload::
  144. string user
  145. string next service
  146. string method
  147. <authentication specific data>
  148. @type packet: L{bytes}
  149. """
  150. user, nextService, method, rest = getNS(packet, 3)
  151. if user != self.user or nextService != self.nextService:
  152. self.authenticatedWith = [] # clear auth state
  153. self.user = user
  154. self.nextService = nextService
  155. self.method = method
  156. d = self.tryAuth(method, user, rest)
  157. if not d:
  158. self._ebBadAuth(
  159. failure.Failure(error.ConchError('auth returned none')))
  160. return
  161. d.addCallback(self._cbFinishedAuth)
  162. d.addErrback(self._ebMaybeBadAuth)
  163. d.addErrback(self._ebBadAuth)
  164. return d
  165. def _cbFinishedAuth(self, result):
  166. """
  167. The callback when user has successfully been authenticated. For a
  168. description of the arguments, see L{twisted.cred.portal.Portal.login}.
  169. We start the service requested by the user.
  170. """
  171. (interface, avatar, logout) = result
  172. self.transport.avatar = avatar
  173. self.transport.logoutFunction = logout
  174. service = self.transport.factory.getService(self.transport,
  175. self.nextService)
  176. if not service:
  177. raise error.ConchError('could not get next service: %s'
  178. % self.nextService)
  179. log.msg('%r authenticated with %r' % (self.user, self.method))
  180. self.transport.sendPacket(MSG_USERAUTH_SUCCESS, b'')
  181. self.transport.setService(service())
  182. def _ebMaybeBadAuth(self, reason):
  183. """
  184. An intermediate errback. If the reason is
  185. error.NotEnoughAuthentication, we send a MSG_USERAUTH_FAILURE, but
  186. with the partial success indicator set.
  187. @type reason: L{twisted.python.failure.Failure}
  188. """
  189. reason.trap(error.NotEnoughAuthentication)
  190. self.transport.sendPacket(MSG_USERAUTH_FAILURE,
  191. NS(b','.join(self.supportedAuthentications)) + b'\xff')
  192. def _ebBadAuth(self, reason):
  193. """
  194. The final errback in the authentication chain. If the reason is
  195. error.IgnoreAuthentication, we simply return; the authentication
  196. method has sent its own response. Otherwise, send a failure message
  197. and (if the method is not 'none') increment the number of login
  198. attempts.
  199. @type reason: L{twisted.python.failure.Failure}
  200. """
  201. if reason.check(error.IgnoreAuthentication):
  202. return
  203. if self.method != b'none':
  204. log.msg('%r failed auth %r' % (self.user, self.method))
  205. if reason.check(UnauthorizedLogin):
  206. log.msg('unauthorized login: %s' % reason.getErrorMessage())
  207. elif reason.check(error.ConchError):
  208. log.msg('reason: %s' % reason.getErrorMessage())
  209. else:
  210. log.msg(reason.getTraceback())
  211. self.loginAttempts += 1
  212. if self.loginAttempts > self.attemptsBeforeDisconnect:
  213. self.transport.sendDisconnect(
  214. transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
  215. b'too many bad auths')
  216. return
  217. self.transport.sendPacket(
  218. MSG_USERAUTH_FAILURE,
  219. NS(b','.join(self.supportedAuthentications)) + b'\x00')
  220. def auth_publickey(self, packet):
  221. """
  222. Public key authentication. Payload::
  223. byte has signature
  224. string algorithm name
  225. string key blob
  226. [string signature] (if has signature is True)
  227. Create a SSHPublicKey credential and verify it using our portal.
  228. """
  229. hasSig = ord(packet[0:1])
  230. algName, blob, rest = getNS(packet[1:], 2)
  231. pubKey = keys.Key.fromString(blob)
  232. signature = hasSig and getNS(rest)[0] or None
  233. if hasSig:
  234. b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
  235. NS(self.user) + NS(self.nextService) + NS(b'publickey') +
  236. chr(hasSig) + NS(pubKey.sshType()) + NS(blob))
  237. c = credentials.SSHPrivateKey(self.user, algName, blob, b,
  238. signature)
  239. return self.portal.login(c, None, interfaces.IConchUser)
  240. else:
  241. c = credentials.SSHPrivateKey(self.user, algName, blob, None, None)
  242. return self.portal.login(c, None,
  243. interfaces.IConchUser).addErrback(self._ebCheckKey,
  244. packet[1:])
  245. def _ebCheckKey(self, reason, packet):
  246. """
  247. Called back if the user did not sent a signature. If reason is
  248. error.ValidPublicKey then this key is valid for the user to
  249. authenticate with. Send MSG_USERAUTH_PK_OK.
  250. """
  251. reason.trap(error.ValidPublicKey)
  252. # if we make it here, it means that the publickey is valid
  253. self.transport.sendPacket(MSG_USERAUTH_PK_OK, packet)
  254. return failure.Failure(error.IgnoreAuthentication())
  255. def auth_password(self, packet):
  256. """
  257. Password authentication. Payload::
  258. string password
  259. Make a UsernamePassword credential and verify it with our portal.
  260. """
  261. password = getNS(packet[1:])[0]
  262. c = credentials.UsernamePassword(self.user, password)
  263. return self.portal.login(c, None, interfaces.IConchUser).addErrback(
  264. self._ebPassword)
  265. def _ebPassword(self, f):
  266. """
  267. If the password is invalid, wait before sending the failure in order
  268. to delay brute-force password guessing.
  269. """
  270. d = defer.Deferred()
  271. self.clock.callLater(self.passwordDelay, d.callback, f)
  272. return d
  273. class SSHUserAuthClient(service.SSHService):
  274. """
  275. A service implementing the client side of 'ssh-userauth'.
  276. This service will try all authentication methods provided by the server,
  277. making callbacks for more information when necessary.
  278. @ivar name: the name of this service: 'ssh-userauth'
  279. @type name: L{str}
  280. @ivar preferredOrder: a list of authentication methods that should be used
  281. first, in order of preference, if supported by the server
  282. @type preferredOrder: L{list}
  283. @ivar user: the name of the user to authenticate as
  284. @type user: L{bytes}
  285. @ivar instance: the service to start after authentication has finished
  286. @type instance: L{service.SSHService}
  287. @ivar authenticatedWith: a list of strings of authentication methods we've tried
  288. @type authenticatedWith: L{list} of L{bytes}
  289. @ivar triedPublicKeys: a list of public key objects that we've tried to
  290. authenticate with
  291. @type triedPublicKeys: L{list} of L{Key}
  292. @ivar lastPublicKey: the last public key object we've tried to authenticate
  293. with
  294. @type lastPublicKey: L{Key}
  295. """
  296. name = b'ssh-userauth'
  297. preferredOrder = [b'publickey', b'password', b'keyboard-interactive']
  298. def __init__(self, user, instance):
  299. self.user = user
  300. self.instance = instance
  301. def serviceStarted(self):
  302. self.authenticatedWith = []
  303. self.triedPublicKeys = []
  304. self.lastPublicKey = None
  305. self.askForAuth(b'none', b'')
  306. def askForAuth(self, kind, extraData):
  307. """
  308. Send a MSG_USERAUTH_REQUEST.
  309. @param kind: the authentication method to try.
  310. @type kind: L{bytes}
  311. @param extraData: method-specific data to go in the packet
  312. @type extraData: L{bytes}
  313. """
  314. self.lastAuth = kind
  315. self.transport.sendPacket(MSG_USERAUTH_REQUEST, NS(self.user) +
  316. NS(self.instance.name) + NS(kind) + extraData)
  317. def tryAuth(self, kind):
  318. """
  319. Dispatch to an authentication method.
  320. @param kind: the authentication method
  321. @type kind: L{bytes}
  322. """
  323. kind = nativeString(kind.replace(b'-', b'_'))
  324. log.msg('trying to auth with %s' % (kind,))
  325. f = getattr(self,'auth_%s' % (kind,), None)
  326. if f:
  327. return f()
  328. def _ebAuth(self, ignored, *args):
  329. """
  330. Generic callback for a failed authentication attempt. Respond by
  331. asking for the list of accepted methods (the 'none' method)
  332. """
  333. self.askForAuth(b'none', b'')
  334. def ssh_USERAUTH_SUCCESS(self, packet):
  335. """
  336. We received a MSG_USERAUTH_SUCCESS. The server has accepted our
  337. authentication, so start the next service.
  338. """
  339. self.transport.setService(self.instance)
  340. def ssh_USERAUTH_FAILURE(self, packet):
  341. """
  342. We received a MSG_USERAUTH_FAILURE. Payload::
  343. string methods
  344. byte partial success
  345. If partial success is C{True}, then the previous method succeeded but is
  346. not sufficient for authentication. C{methods} is a comma-separated list
  347. of accepted authentication methods.
  348. We sort the list of methods by their position in C{self.preferredOrder},
  349. removing methods that have already succeeded. We then call
  350. C{self.tryAuth} with the most preferred method.
  351. @param packet: the C{MSG_USERAUTH_FAILURE} payload.
  352. @type packet: L{bytes}
  353. @return: a L{defer.Deferred} that will be callbacked with L{None} as
  354. soon as all authentication methods have been tried, or L{None} if no
  355. more authentication methods are available.
  356. @rtype: C{defer.Deferred} or L{None}
  357. """
  358. canContinue, partial = getNS(packet)
  359. partial = ord(partial)
  360. if partial:
  361. self.authenticatedWith.append(self.lastAuth)
  362. def orderByPreference(meth):
  363. """
  364. Invoked once per authentication method in order to extract a
  365. comparison key which is then used for sorting.
  366. @param meth: the authentication method.
  367. @type meth: L{bytes}
  368. @return: the comparison key for C{meth}.
  369. @rtype: L{int}
  370. """
  371. if meth in self.preferredOrder:
  372. return self.preferredOrder.index(meth)
  373. else:
  374. # put the element at the end of the list.
  375. return len(self.preferredOrder)
  376. canContinue = sorted([meth for meth in canContinue.split(b',')
  377. if meth not in self.authenticatedWith],
  378. key=orderByPreference)
  379. log.msg('can continue with: %s' % canContinue)
  380. return self._cbUserauthFailure(None, iter(canContinue))
  381. def _cbUserauthFailure(self, result, iterator):
  382. if result:
  383. return
  384. try:
  385. method = next(iterator)
  386. except StopIteration:
  387. self.transport.sendDisconnect(
  388. transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
  389. b'no more authentication methods available')
  390. else:
  391. d = defer.maybeDeferred(self.tryAuth, method)
  392. d.addCallback(self._cbUserauthFailure, iterator)
  393. return d
  394. def ssh_USERAUTH_PK_OK(self, packet):
  395. """
  396. This message (number 60) can mean several different messages depending
  397. on the current authentication type. We dispatch to individual methods
  398. in order to handle this request.
  399. """
  400. func = getattr(self, 'ssh_USERAUTH_PK_OK_%s' %
  401. nativeString(self.lastAuth.replace(b'-', b'_')), None)
  402. if func is not None:
  403. return func(packet)
  404. else:
  405. self.askForAuth(b'none', b'')
  406. def ssh_USERAUTH_PK_OK_publickey(self, packet):
  407. """
  408. This is MSG_USERAUTH_PK. Our public key is valid, so we create a
  409. signature and try to authenticate with it.
  410. """
  411. publicKey = self.lastPublicKey
  412. b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
  413. NS(self.user) + NS(self.instance.name) + NS(b'publickey') +
  414. b'\x01' + NS(publicKey.sshType()) + NS(publicKey.blob()))
  415. d = self.signData(publicKey, b)
  416. if not d:
  417. self.askForAuth(b'none', b'')
  418. # this will fail, we'll move on
  419. return
  420. d.addCallback(self._cbSignedData)
  421. d.addErrback(self._ebAuth)
  422. def ssh_USERAUTH_PK_OK_password(self, packet):
  423. """
  424. This is MSG_USERAUTH_PASSWD_CHANGEREQ. The password given has expired.
  425. We ask for an old password and a new password, then send both back to
  426. the server.
  427. """
  428. prompt, language, rest = getNS(packet, 2)
  429. self._oldPass = self._newPass = None
  430. d = self.getPassword(b'Old Password: ')
  431. d = d.addCallbacks(self._setOldPass, self._ebAuth)
  432. d.addCallback(lambda ignored: self.getPassword(prompt))
  433. d.addCallbacks(self._setNewPass, self._ebAuth)
  434. def ssh_USERAUTH_PK_OK_keyboard_interactive(self, packet):
  435. """
  436. This is MSG_USERAUTH_INFO_RESPONSE. The server has sent us the
  437. questions it wants us to answer, so we ask the user and sent the
  438. responses.
  439. """
  440. name, instruction, lang, data = getNS(packet, 3)
  441. numPrompts = struct.unpack('!L', data[:4])[0]
  442. data = data[4:]
  443. prompts = []
  444. for i in range(numPrompts):
  445. prompt, data = getNS(data)
  446. echo = bool(ord(data[0:1]))
  447. data = data[1:]
  448. prompts.append((prompt, echo))
  449. d = self.getGenericAnswers(name, instruction, prompts)
  450. d.addCallback(self._cbGenericAnswers)
  451. d.addErrback(self._ebAuth)
  452. def _cbSignedData(self, signedData):
  453. """
  454. Called back out of self.signData with the signed data. Send the
  455. authentication request with the signature.
  456. @param signedData: the data signed by the user's private key.
  457. @type signedData: L{bytes}
  458. """
  459. publicKey = self.lastPublicKey
  460. self.askForAuth(b'publickey', b'\x01' + NS(publicKey.sshType()) +
  461. NS(publicKey.blob()) + NS(signedData))
  462. def _setOldPass(self, op):
  463. """
  464. Called back when we are choosing a new password. Simply store the old
  465. password for now.
  466. @param op: the old password as entered by the user
  467. @type op: L{bytes}
  468. """
  469. self._oldPass = op
  470. def _setNewPass(self, np):
  471. """
  472. Called back when we are choosing a new password. Get the old password
  473. and send the authentication message with both.
  474. @param np: the new password as entered by the user
  475. @type np: L{bytes}
  476. """
  477. op = self._oldPass
  478. self._oldPass = None
  479. self.askForAuth(b'password', b'\xff' + NS(op) + NS(np))
  480. def _cbGenericAnswers(self, responses):
  481. """
  482. Called back when we are finished answering keyboard-interactive
  483. questions. Send the info back to the server in a
  484. MSG_USERAUTH_INFO_RESPONSE.
  485. @param responses: a list of L{bytes} responses
  486. @type responses: L{list}
  487. """
  488. data = struct.pack('!L', len(responses))
  489. for r in responses:
  490. data += NS(r.encode('UTF8'))
  491. self.transport.sendPacket(MSG_USERAUTH_INFO_RESPONSE, data)
  492. def auth_publickey(self):
  493. """
  494. Try to authenticate with a public key. Ask the user for a public key;
  495. if the user has one, send the request to the server and return True.
  496. Otherwise, return False.
  497. @rtype: L{bool}
  498. """
  499. d = defer.maybeDeferred(self.getPublicKey)
  500. d.addBoth(self._cbGetPublicKey)
  501. return d
  502. def _cbGetPublicKey(self, publicKey):
  503. if not isinstance(publicKey, keys.Key): # failure or None
  504. publicKey = None
  505. if publicKey is not None:
  506. self.lastPublicKey = publicKey
  507. self.triedPublicKeys.append(publicKey)
  508. log.msg('using key of type %s' % publicKey.type())
  509. self.askForAuth(b'publickey', b'\x00' + NS(publicKey.sshType()) +
  510. NS(publicKey.blob()))
  511. return True
  512. else:
  513. return False
  514. def auth_password(self):
  515. """
  516. Try to authenticate with a password. Ask the user for a password.
  517. If the user will return a password, return True. Otherwise, return
  518. False.
  519. @rtype: L{bool}
  520. """
  521. d = self.getPassword()
  522. if d:
  523. d.addCallbacks(self._cbPassword, self._ebAuth)
  524. return True
  525. else: # returned None, don't do password auth
  526. return False
  527. def auth_keyboard_interactive(self):
  528. """
  529. Try to authenticate with keyboard-interactive authentication. Send
  530. the request to the server and return True.
  531. @rtype: L{bool}
  532. """
  533. log.msg('authing with keyboard-interactive')
  534. self.askForAuth(b'keyboard-interactive', NS(b'') + NS(b''))
  535. return True
  536. def _cbPassword(self, password):
  537. """
  538. Called back when the user gives a password. Send the request to the
  539. server.
  540. @param password: the password the user entered
  541. @type password: L{bytes}
  542. """
  543. self.askForAuth(b'password', b'\x00' + NS(password))
  544. def signData(self, publicKey, signData):
  545. """
  546. Sign the given data with the given public key.
  547. By default, this will call getPrivateKey to get the private key,
  548. then sign the data using Key.sign().
  549. This method is factored out so that it can be overridden to use
  550. alternate methods, such as a key agent.
  551. @param publicKey: The public key object returned from L{getPublicKey}
  552. @type publicKey: L{keys.Key}
  553. @param signData: the data to be signed by the private key.
  554. @type signData: L{bytes}
  555. @return: a Deferred that's called back with the signature
  556. @rtype: L{defer.Deferred}
  557. """
  558. key = self.getPrivateKey()
  559. if not key:
  560. return
  561. return key.addCallback(self._cbSignData, signData)
  562. def _cbSignData(self, privateKey, signData):
  563. """
  564. Called back when the private key is returned. Sign the data and
  565. return the signature.
  566. @param privateKey: the private key object
  567. @type publicKey: L{keys.Key}
  568. @param signData: the data to be signed by the private key.
  569. @type signData: L{bytes}
  570. @return: the signature
  571. @rtype: L{bytes}
  572. """
  573. return privateKey.sign(signData)
  574. def getPublicKey(self):
  575. """
  576. Return a public key for the user. If no more public keys are
  577. available, return L{None}.
  578. This implementation always returns L{None}. Override it in a
  579. subclass to actually find and return a public key object.
  580. @rtype: L{Key} or L{None}
  581. """
  582. return None
  583. def getPrivateKey(self):
  584. """
  585. Return a L{Deferred} that will be called back with the private key
  586. object corresponding to the last public key from getPublicKey().
  587. If the private key is not available, errback on the Deferred.
  588. @rtype: L{Deferred} called back with L{Key}
  589. """
  590. return defer.fail(NotImplementedError())
  591. def getPassword(self, prompt = None):
  592. """
  593. Return a L{Deferred} that will be called back with a password.
  594. prompt is a string to display for the password, or None for a generic
  595. 'user@hostname's password: '.
  596. @type prompt: L{bytes}/L{None}
  597. @rtype: L{defer.Deferred}
  598. """
  599. return defer.fail(NotImplementedError())
  600. def getGenericAnswers(self, name, instruction, prompts):
  601. """
  602. Returns a L{Deferred} with the responses to the promopts.
  603. @param name: The name of the authentication currently in progress.
  604. @param instruction: Describes what the authentication wants.
  605. @param prompts: A list of (prompt, echo) pairs, where prompt is a
  606. string to display and echo is a boolean indicating whether the
  607. user's response should be echoed as they type it.
  608. """
  609. return defer.fail(NotImplementedError())
  610. MSG_USERAUTH_REQUEST = 50
  611. MSG_USERAUTH_FAILURE = 51
  612. MSG_USERAUTH_SUCCESS = 52
  613. MSG_USERAUTH_BANNER = 53
  614. MSG_USERAUTH_INFO_RESPONSE = 61
  615. MSG_USERAUTH_PK_OK = 60
  616. messages = {}
  617. for k, v in list(locals().items()):
  618. if k[:4] == 'MSG_':
  619. messages[v] = k
  620. SSHUserAuthServer.protocolMessages = messages
  621. SSHUserAuthClient.protocolMessages = messages
  622. del messages
  623. del v
  624. # Doubles, not included in the protocols' mappings
  625. MSG_USERAUTH_PASSWD_CHANGEREQ = 60
  626. MSG_USERAUTH_INFO_REQUEST = 60