userauth.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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. try:
  232. pubKey = keys.Key.fromString(blob)
  233. except keys.BadKeyError:
  234. error = "Unsupported key type %s or bad key" % (
  235. algName.decode('ascii'),)
  236. log.msg(error)
  237. return defer.fail(UnauthorizedLogin(error))
  238. signature = hasSig and getNS(rest)[0] or None
  239. if hasSig:
  240. b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
  241. NS(self.user) + NS(self.nextService) + NS(b'publickey') +
  242. chr(hasSig) + NS(pubKey.sshType()) + NS(blob))
  243. c = credentials.SSHPrivateKey(self.user, algName, blob, b,
  244. signature)
  245. return self.portal.login(c, None, interfaces.IConchUser)
  246. else:
  247. c = credentials.SSHPrivateKey(self.user, algName, blob, None, None)
  248. return self.portal.login(c, None,
  249. interfaces.IConchUser).addErrback(self._ebCheckKey,
  250. packet[1:])
  251. def _ebCheckKey(self, reason, packet):
  252. """
  253. Called back if the user did not sent a signature. If reason is
  254. error.ValidPublicKey then this key is valid for the user to
  255. authenticate with. Send MSG_USERAUTH_PK_OK.
  256. """
  257. reason.trap(error.ValidPublicKey)
  258. # if we make it here, it means that the publickey is valid
  259. self.transport.sendPacket(MSG_USERAUTH_PK_OK, packet)
  260. return failure.Failure(error.IgnoreAuthentication())
  261. def auth_password(self, packet):
  262. """
  263. Password authentication. Payload::
  264. string password
  265. Make a UsernamePassword credential and verify it with our portal.
  266. """
  267. password = getNS(packet[1:])[0]
  268. c = credentials.UsernamePassword(self.user, password)
  269. return self.portal.login(c, None, interfaces.IConchUser).addErrback(
  270. self._ebPassword)
  271. def _ebPassword(self, f):
  272. """
  273. If the password is invalid, wait before sending the failure in order
  274. to delay brute-force password guessing.
  275. """
  276. d = defer.Deferred()
  277. self.clock.callLater(self.passwordDelay, d.callback, f)
  278. return d
  279. class SSHUserAuthClient(service.SSHService):
  280. """
  281. A service implementing the client side of 'ssh-userauth'.
  282. This service will try all authentication methods provided by the server,
  283. making callbacks for more information when necessary.
  284. @ivar name: the name of this service: 'ssh-userauth'
  285. @type name: L{str}
  286. @ivar preferredOrder: a list of authentication methods that should be used
  287. first, in order of preference, if supported by the server
  288. @type preferredOrder: L{list}
  289. @ivar user: the name of the user to authenticate as
  290. @type user: L{bytes}
  291. @ivar instance: the service to start after authentication has finished
  292. @type instance: L{service.SSHService}
  293. @ivar authenticatedWith: a list of strings of authentication methods we've tried
  294. @type authenticatedWith: L{list} of L{bytes}
  295. @ivar triedPublicKeys: a list of public key objects that we've tried to
  296. authenticate with
  297. @type triedPublicKeys: L{list} of L{Key}
  298. @ivar lastPublicKey: the last public key object we've tried to authenticate
  299. with
  300. @type lastPublicKey: L{Key}
  301. """
  302. name = b'ssh-userauth'
  303. preferredOrder = [b'publickey', b'password', b'keyboard-interactive']
  304. def __init__(self, user, instance):
  305. self.user = user
  306. self.instance = instance
  307. def serviceStarted(self):
  308. self.authenticatedWith = []
  309. self.triedPublicKeys = []
  310. self.lastPublicKey = None
  311. self.askForAuth(b'none', b'')
  312. def askForAuth(self, kind, extraData):
  313. """
  314. Send a MSG_USERAUTH_REQUEST.
  315. @param kind: the authentication method to try.
  316. @type kind: L{bytes}
  317. @param extraData: method-specific data to go in the packet
  318. @type extraData: L{bytes}
  319. """
  320. self.lastAuth = kind
  321. self.transport.sendPacket(MSG_USERAUTH_REQUEST, NS(self.user) +
  322. NS(self.instance.name) + NS(kind) + extraData)
  323. def tryAuth(self, kind):
  324. """
  325. Dispatch to an authentication method.
  326. @param kind: the authentication method
  327. @type kind: L{bytes}
  328. """
  329. kind = nativeString(kind.replace(b'-', b'_'))
  330. log.msg('trying to auth with %s' % (kind,))
  331. f = getattr(self,'auth_%s' % (kind,), None)
  332. if f:
  333. return f()
  334. def _ebAuth(self, ignored, *args):
  335. """
  336. Generic callback for a failed authentication attempt. Respond by
  337. asking for the list of accepted methods (the 'none' method)
  338. """
  339. self.askForAuth(b'none', b'')
  340. def ssh_USERAUTH_SUCCESS(self, packet):
  341. """
  342. We received a MSG_USERAUTH_SUCCESS. The server has accepted our
  343. authentication, so start the next service.
  344. """
  345. self.transport.setService(self.instance)
  346. def ssh_USERAUTH_FAILURE(self, packet):
  347. """
  348. We received a MSG_USERAUTH_FAILURE. Payload::
  349. string methods
  350. byte partial success
  351. If partial success is C{True}, then the previous method succeeded but is
  352. not sufficient for authentication. C{methods} is a comma-separated list
  353. of accepted authentication methods.
  354. We sort the list of methods by their position in C{self.preferredOrder},
  355. removing methods that have already succeeded. We then call
  356. C{self.tryAuth} with the most preferred method.
  357. @param packet: the C{MSG_USERAUTH_FAILURE} payload.
  358. @type packet: L{bytes}
  359. @return: a L{defer.Deferred} that will be callbacked with L{None} as
  360. soon as all authentication methods have been tried, or L{None} if no
  361. more authentication methods are available.
  362. @rtype: C{defer.Deferred} or L{None}
  363. """
  364. canContinue, partial = getNS(packet)
  365. partial = ord(partial)
  366. if partial:
  367. self.authenticatedWith.append(self.lastAuth)
  368. def orderByPreference(meth):
  369. """
  370. Invoked once per authentication method in order to extract a
  371. comparison key which is then used for sorting.
  372. @param meth: the authentication method.
  373. @type meth: L{bytes}
  374. @return: the comparison key for C{meth}.
  375. @rtype: L{int}
  376. """
  377. if meth in self.preferredOrder:
  378. return self.preferredOrder.index(meth)
  379. else:
  380. # put the element at the end of the list.
  381. return len(self.preferredOrder)
  382. canContinue = sorted([meth for meth in canContinue.split(b',')
  383. if meth not in self.authenticatedWith],
  384. key=orderByPreference)
  385. log.msg('can continue with: %s' % canContinue)
  386. return self._cbUserauthFailure(None, iter(canContinue))
  387. def _cbUserauthFailure(self, result, iterator):
  388. if result:
  389. return
  390. try:
  391. method = next(iterator)
  392. except StopIteration:
  393. self.transport.sendDisconnect(
  394. transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
  395. b'no more authentication methods available')
  396. else:
  397. d = defer.maybeDeferred(self.tryAuth, method)
  398. d.addCallback(self._cbUserauthFailure, iterator)
  399. return d
  400. def ssh_USERAUTH_PK_OK(self, packet):
  401. """
  402. This message (number 60) can mean several different messages depending
  403. on the current authentication type. We dispatch to individual methods
  404. in order to handle this request.
  405. """
  406. func = getattr(self, 'ssh_USERAUTH_PK_OK_%s' %
  407. nativeString(self.lastAuth.replace(b'-', b'_')), None)
  408. if func is not None:
  409. return func(packet)
  410. else:
  411. self.askForAuth(b'none', b'')
  412. def ssh_USERAUTH_PK_OK_publickey(self, packet):
  413. """
  414. This is MSG_USERAUTH_PK. Our public key is valid, so we create a
  415. signature and try to authenticate with it.
  416. """
  417. publicKey = self.lastPublicKey
  418. b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
  419. NS(self.user) + NS(self.instance.name) + NS(b'publickey') +
  420. b'\x01' + NS(publicKey.sshType()) + NS(publicKey.blob()))
  421. d = self.signData(publicKey, b)
  422. if not d:
  423. self.askForAuth(b'none', b'')
  424. # this will fail, we'll move on
  425. return
  426. d.addCallback(self._cbSignedData)
  427. d.addErrback(self._ebAuth)
  428. def ssh_USERAUTH_PK_OK_password(self, packet):
  429. """
  430. This is MSG_USERAUTH_PASSWD_CHANGEREQ. The password given has expired.
  431. We ask for an old password and a new password, then send both back to
  432. the server.
  433. """
  434. prompt, language, rest = getNS(packet, 2)
  435. self._oldPass = self._newPass = None
  436. d = self.getPassword(b'Old Password: ')
  437. d = d.addCallbacks(self._setOldPass, self._ebAuth)
  438. d.addCallback(lambda ignored: self.getPassword(prompt))
  439. d.addCallbacks(self._setNewPass, self._ebAuth)
  440. def ssh_USERAUTH_PK_OK_keyboard_interactive(self, packet):
  441. """
  442. This is MSG_USERAUTH_INFO_RESPONSE. The server has sent us the
  443. questions it wants us to answer, so we ask the user and sent the
  444. responses.
  445. """
  446. name, instruction, lang, data = getNS(packet, 3)
  447. numPrompts = struct.unpack('!L', data[:4])[0]
  448. data = data[4:]
  449. prompts = []
  450. for i in range(numPrompts):
  451. prompt, data = getNS(data)
  452. echo = bool(ord(data[0:1]))
  453. data = data[1:]
  454. prompts.append((prompt, echo))
  455. d = self.getGenericAnswers(name, instruction, prompts)
  456. d.addCallback(self._cbGenericAnswers)
  457. d.addErrback(self._ebAuth)
  458. def _cbSignedData(self, signedData):
  459. """
  460. Called back out of self.signData with the signed data. Send the
  461. authentication request with the signature.
  462. @param signedData: the data signed by the user's private key.
  463. @type signedData: L{bytes}
  464. """
  465. publicKey = self.lastPublicKey
  466. self.askForAuth(b'publickey', b'\x01' + NS(publicKey.sshType()) +
  467. NS(publicKey.blob()) + NS(signedData))
  468. def _setOldPass(self, op):
  469. """
  470. Called back when we are choosing a new password. Simply store the old
  471. password for now.
  472. @param op: the old password as entered by the user
  473. @type op: L{bytes}
  474. """
  475. self._oldPass = op
  476. def _setNewPass(self, np):
  477. """
  478. Called back when we are choosing a new password. Get the old password
  479. and send the authentication message with both.
  480. @param np: the new password as entered by the user
  481. @type np: L{bytes}
  482. """
  483. op = self._oldPass
  484. self._oldPass = None
  485. self.askForAuth(b'password', b'\xff' + NS(op) + NS(np))
  486. def _cbGenericAnswers(self, responses):
  487. """
  488. Called back when we are finished answering keyboard-interactive
  489. questions. Send the info back to the server in a
  490. MSG_USERAUTH_INFO_RESPONSE.
  491. @param responses: a list of L{bytes} responses
  492. @type responses: L{list}
  493. """
  494. data = struct.pack('!L', len(responses))
  495. for r in responses:
  496. data += NS(r.encode('UTF8'))
  497. self.transport.sendPacket(MSG_USERAUTH_INFO_RESPONSE, data)
  498. def auth_publickey(self):
  499. """
  500. Try to authenticate with a public key. Ask the user for a public key;
  501. if the user has one, send the request to the server and return True.
  502. Otherwise, return False.
  503. @rtype: L{bool}
  504. """
  505. d = defer.maybeDeferred(self.getPublicKey)
  506. d.addBoth(self._cbGetPublicKey)
  507. return d
  508. def _cbGetPublicKey(self, publicKey):
  509. if not isinstance(publicKey, keys.Key): # failure or None
  510. publicKey = None
  511. if publicKey is not None:
  512. self.lastPublicKey = publicKey
  513. self.triedPublicKeys.append(publicKey)
  514. log.msg('using key of type %s' % publicKey.type())
  515. self.askForAuth(b'publickey', b'\x00' + NS(publicKey.sshType()) +
  516. NS(publicKey.blob()))
  517. return True
  518. else:
  519. return False
  520. def auth_password(self):
  521. """
  522. Try to authenticate with a password. Ask the user for a password.
  523. If the user will return a password, return True. Otherwise, return
  524. False.
  525. @rtype: L{bool}
  526. """
  527. d = self.getPassword()
  528. if d:
  529. d.addCallbacks(self._cbPassword, self._ebAuth)
  530. return True
  531. else: # returned None, don't do password auth
  532. return False
  533. def auth_keyboard_interactive(self):
  534. """
  535. Try to authenticate with keyboard-interactive authentication. Send
  536. the request to the server and return True.
  537. @rtype: L{bool}
  538. """
  539. log.msg('authing with keyboard-interactive')
  540. self.askForAuth(b'keyboard-interactive', NS(b'') + NS(b''))
  541. return True
  542. def _cbPassword(self, password):
  543. """
  544. Called back when the user gives a password. Send the request to the
  545. server.
  546. @param password: the password the user entered
  547. @type password: L{bytes}
  548. """
  549. self.askForAuth(b'password', b'\x00' + NS(password))
  550. def signData(self, publicKey, signData):
  551. """
  552. Sign the given data with the given public key.
  553. By default, this will call getPrivateKey to get the private key,
  554. then sign the data using Key.sign().
  555. This method is factored out so that it can be overridden to use
  556. alternate methods, such as a key agent.
  557. @param publicKey: The public key object returned from L{getPublicKey}
  558. @type publicKey: L{keys.Key}
  559. @param signData: the data to be signed by the private key.
  560. @type signData: L{bytes}
  561. @return: a Deferred that's called back with the signature
  562. @rtype: L{defer.Deferred}
  563. """
  564. key = self.getPrivateKey()
  565. if not key:
  566. return
  567. return key.addCallback(self._cbSignData, signData)
  568. def _cbSignData(self, privateKey, signData):
  569. """
  570. Called back when the private key is returned. Sign the data and
  571. return the signature.
  572. @param privateKey: the private key object
  573. @type publicKey: L{keys.Key}
  574. @param signData: the data to be signed by the private key.
  575. @type signData: L{bytes}
  576. @return: the signature
  577. @rtype: L{bytes}
  578. """
  579. return privateKey.sign(signData)
  580. def getPublicKey(self):
  581. """
  582. Return a public key for the user. If no more public keys are
  583. available, return L{None}.
  584. This implementation always returns L{None}. Override it in a
  585. subclass to actually find and return a public key object.
  586. @rtype: L{Key} or L{None}
  587. """
  588. return None
  589. def getPrivateKey(self):
  590. """
  591. Return a L{Deferred} that will be called back with the private key
  592. object corresponding to the last public key from getPublicKey().
  593. If the private key is not available, errback on the Deferred.
  594. @rtype: L{Deferred} called back with L{Key}
  595. """
  596. return defer.fail(NotImplementedError())
  597. def getPassword(self, prompt = None):
  598. """
  599. Return a L{Deferred} that will be called back with a password.
  600. prompt is a string to display for the password, or None for a generic
  601. 'user@hostname's password: '.
  602. @type prompt: L{bytes}/L{None}
  603. @rtype: L{defer.Deferred}
  604. """
  605. return defer.fail(NotImplementedError())
  606. def getGenericAnswers(self, name, instruction, prompts):
  607. """
  608. Returns a L{Deferred} with the responses to the promopts.
  609. @param name: The name of the authentication currently in progress.
  610. @param instruction: Describes what the authentication wants.
  611. @param prompts: A list of (prompt, echo) pairs, where prompt is a
  612. string to display and echo is a boolean indicating whether the
  613. user's response should be echoed as they type it.
  614. """
  615. return defer.fail(NotImplementedError())
  616. MSG_USERAUTH_REQUEST = 50
  617. MSG_USERAUTH_FAILURE = 51
  618. MSG_USERAUTH_SUCCESS = 52
  619. MSG_USERAUTH_BANNER = 53
  620. MSG_USERAUTH_INFO_RESPONSE = 61
  621. MSG_USERAUTH_PK_OK = 60
  622. messages = {}
  623. for k, v in list(locals().items()):
  624. if k[:4] == 'MSG_':
  625. messages[v] = k
  626. SSHUserAuthServer.protocolMessages = messages
  627. SSHUserAuthClient.protocolMessages = messages
  628. del messages
  629. del v
  630. # Doubles, not included in the protocols' mappings
  631. MSG_USERAUTH_PASSWD_CHANGEREQ = 60
  632. MSG_USERAUTH_INFO_REQUEST = 60