userauth.py 27 KB

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