1 # -*- test-case-name: twisted.conch.test.test_userauth -*-
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
6 Implementation of the ssh-userauth service.
7 Currently implemented authentication types are public-key and password.
9 Maintainer: Paul Swartz
12 import struct, warnings
13 from twisted.conch import error, interfaces
14 from twisted.conch.ssh import keys, transport, service
15 from twisted.conch.ssh.common import NS, getNS
16 from twisted.cred import credentials
17 from twisted.cred.error import UnauthorizedLogin
18 from twisted.internet import defer, reactor
19 from twisted.python import failure, log
23 class SSHUserAuthServer(service.SSHService):
25 A service implementing the server side of the 'ssh-userauth' service. It
26 is used to authenticate the user on the other side as being able to access
29 @ivar name: the name of this service: 'ssh-userauth'
31 @ivar authenticatedWith: a list of authentication methods that have
33 @type authenticatedWith: C{list}
34 @ivar loginTimeout: the number of seconds we wait before disconnecting
35 the user for taking too long to authenticate
36 @type loginTimeout: C{int}
37 @ivar attemptsBeforeDisconnect: the number of failed login attempts we
38 allow before disconnecting.
39 @type attemptsBeforeDisconnect: C{int}
40 @ivar loginAttempts: the number of login attempts that have been made
41 @type loginAttempts: C{int}
42 @ivar passwordDelay: the number of seconds to delay when the user gives
44 @type passwordDelay: C{int}
45 @ivar interfaceToMethod: a C{dict} mapping credential interfaces to
46 authentication methods. The server checks to see which of the
47 cred interfaces have checkers and tells the client that those methods
48 are valid for authentication.
49 @type interfaceToMethod: C{dict}
50 @ivar supportedAuthentications: A list of the supported authentication
52 @type supportedAuthentications: C{list} of C{str}
53 @ivar user: the last username the client tried to authenticate with
55 @ivar method: the current authentication method
57 @ivar nextService: the service the user wants started after authentication
59 @type nextService: C{str}
60 @ivar portal: the L{twisted.cred.portal.Portal} we are using for
62 @type portal: L{twisted.cred.portal.Portal}
63 @ivar clock: an object with a callLater method. Stubbed out for testing.
68 loginTimeout = 10 * 60 * 60
69 # 10 minutes before we disconnect them
70 attemptsBeforeDisconnect = 20
71 # 20 login attempts before a disconnect
72 passwordDelay = 1 # number of seconds to delay on a failed password
75 credentials.ISSHPrivateKey : 'publickey',
76 credentials.IUsernamePassword : 'password',
77 credentials.IPluggableAuthenticationModules : 'keyboard-interactive',
81 def serviceStarted(self):
83 Called when the userauth service is started. Set up instance
84 variables, check if we should allow password/keyboard-interactive
85 authentication (only allow if the outgoing connection is encrypted) and
86 set up a login timeout.
88 self.authenticatedWith = []
89 self.loginAttempts = 0
91 self.nextService = None
92 self._pamDeferred = None
93 self.portal = self.transport.factory.portal
95 self.supportedAuthentications = []
96 for i in self.portal.listCredentialsInterfaces():
97 if i in self.interfaceToMethod:
98 self.supportedAuthentications.append(self.interfaceToMethod[i])
100 if not self.transport.isEncrypted('in'):
101 # don't let us transport password in plaintext
102 if 'password' in self.supportedAuthentications:
103 self.supportedAuthentications.remove('password')
104 if 'keyboard-interactive' in self.supportedAuthentications:
105 self.supportedAuthentications.remove('keyboard-interactive')
106 self._cancelLoginTimeout = self.clock.callLater(
108 self.timeoutAuthentication)
111 def serviceStopped(self):
113 Called when the userauth service is stopped. Cancel the login timeout
116 if self._cancelLoginTimeout:
117 self._cancelLoginTimeout.cancel()
118 self._cancelLoginTimeout = None
121 def timeoutAuthentication(self):
123 Called when the user has timed out on authentication. Disconnect
124 with a DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE message.
126 self._cancelLoginTimeout = None
127 self.transport.sendDisconnect(
128 transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
132 def tryAuth(self, kind, user, data):
134 Try to authenticate the user with the given method. Dispatches to a
137 @param kind: the authentication method to try.
139 @param user: the username the client is authenticating with.
141 @param data: authentication specific data sent by the client.
143 @return: A Deferred called back if the method succeeded, or erred back
145 @rtype: C{defer.Deferred}
147 log.msg('%s trying auth %s' % (user, kind))
148 if kind not in self.supportedAuthentications:
150 error.ConchError('unsupported authentication, failing'))
151 kind = kind.replace('-', '_')
152 f = getattr(self,'auth_%s'%kind, None)
157 error.ConchError('%s return None instead of a Deferred'
161 return defer.fail(error.ConchError('bad auth type: %s' % kind))
164 def ssh_USERAUTH_REQUEST(self, packet):
166 The client has requested authentication. Payload::
170 <authentication specific data>
174 user, nextService, method, rest = getNS(packet, 3)
175 if user != self.user or nextService != self.nextService:
176 self.authenticatedWith = [] # clear auth state
178 self.nextService = nextService
180 d = self.tryAuth(method, user, rest)
183 failure.Failure(error.ConchError('auth returned none')))
185 d.addCallback(self._cbFinishedAuth)
186 d.addErrback(self._ebMaybeBadAuth)
187 d.addErrback(self._ebBadAuth)
191 def _cbFinishedAuth(self, (interface, avatar, logout)):
193 The callback when user has successfully been authenticated. For a
194 description of the arguments, see L{twisted.cred.portal.Portal.login}.
195 We start the service requested by the user.
197 self.transport.avatar = avatar
198 self.transport.logoutFunction = logout
199 service = self.transport.factory.getService(self.transport,
202 raise error.ConchError('could not get next service: %s'
204 log.msg('%s authenticated with %s' % (self.user, self.method))
205 self.transport.sendPacket(MSG_USERAUTH_SUCCESS, '')
206 self.transport.setService(service())
209 def _ebMaybeBadAuth(self, reason):
211 An intermediate errback. If the reason is
212 error.NotEnoughAuthentication, we send a MSG_USERAUTH_FAILURE, but
213 with the partial success indicator set.
215 @type reason: L{twisted.python.failure.Failure}
217 reason.trap(error.NotEnoughAuthentication)
218 self.transport.sendPacket(MSG_USERAUTH_FAILURE,
219 NS(','.join(self.supportedAuthentications)) + '\xff')
222 def _ebBadAuth(self, reason):
224 The final errback in the authentication chain. If the reason is
225 error.IgnoreAuthentication, we simply return; the authentication
226 method has sent its own response. Otherwise, send a failure message
227 and (if the method is not 'none') increment the number of login
230 @type reason: L{twisted.python.failure.Failure}
232 if reason.check(error.IgnoreAuthentication):
234 if self.method != 'none':
235 log.msg('%s failed auth %s' % (self.user, self.method))
236 if reason.check(UnauthorizedLogin):
237 log.msg('unauthorized login: %s' % reason.getErrorMessage())
238 elif reason.check(error.ConchError):
239 log.msg('reason: %s' % reason.getErrorMessage())
241 log.msg(reason.getTraceback())
242 self.loginAttempts += 1
243 if self.loginAttempts > self.attemptsBeforeDisconnect:
244 self.transport.sendDisconnect(
245 transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
246 'too many bad auths')
248 self.transport.sendPacket(
249 MSG_USERAUTH_FAILURE,
250 NS(','.join(self.supportedAuthentications)) + '\x00')
253 def auth_publickey(self, packet):
255 Public key authentication. Payload::
257 string algorithm name
259 [string signature] (if has signature is True)
261 Create a SSHPublicKey credential and verify it using our portal.
263 hasSig = ord(packet[0])
264 algName, blob, rest = getNS(packet[1:], 2)
265 pubKey = keys.Key.fromString(blob)
266 signature = hasSig and getNS(rest)[0] or None
268 b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
269 NS(self.user) + NS(self.nextService) + NS('publickey') +
270 chr(hasSig) + NS(pubKey.sshType()) + NS(blob))
271 c = credentials.SSHPrivateKey(self.user, algName, blob, b,
273 return self.portal.login(c, None, interfaces.IConchUser)
275 c = credentials.SSHPrivateKey(self.user, algName, blob, None, None)
276 return self.portal.login(c, None,
277 interfaces.IConchUser).addErrback(self._ebCheckKey,
281 def _ebCheckKey(self, reason, packet):
283 Called back if the user did not sent a signature. If reason is
284 error.ValidPublicKey then this key is valid for the user to
285 authenticate with. Send MSG_USERAUTH_PK_OK.
287 reason.trap(error.ValidPublicKey)
288 # if we make it here, it means that the publickey is valid
289 self.transport.sendPacket(MSG_USERAUTH_PK_OK, packet)
290 return failure.Failure(error.IgnoreAuthentication())
293 def auth_password(self, packet):
295 Password authentication. Payload::
298 Make a UsernamePassword credential and verify it with our portal.
300 password = getNS(packet[1:])[0]
301 c = credentials.UsernamePassword(self.user, password)
302 return self.portal.login(c, None, interfaces.IConchUser).addErrback(
306 def _ebPassword(self, f):
308 If the password is invalid, wait before sending the failure in order
309 to delay brute-force password guessing.
312 self.clock.callLater(self.passwordDelay, d.callback, f)
316 def auth_keyboard_interactive(self, packet):
318 Keyboard interactive authentication. No payload. We create a
319 PluggableAuthenticationModules credential and authenticate with our
322 if self._pamDeferred is not None:
323 self.transport.sendDisconnect(
324 transport.DISCONNECT_PROTOCOL_ERROR,
325 "only one keyboard interactive attempt at a time")
326 return defer.fail(error.IgnoreAuthentication())
327 c = credentials.PluggableAuthenticationModules(self.user,
329 return self.portal.login(c, None, interfaces.IConchUser)
332 def _pamConv(self, items):
334 Convert a list of PAM authentication questions into a
335 MSG_USERAUTH_INFO_REQUEST. Returns a Deferred that will be called
336 back when the user has responses to the questions.
338 @param items: a list of 2-tuples (message, kind). We only care about
339 kinds 1 (password) and 2 (text).
341 @rtype: L{defer.Deferred}
344 for message, kind in items:
345 if kind == 1: # password
346 resp.append((message, 0))
347 elif kind == 2: # text
348 resp.append((message, 1))
350 return defer.fail(error.ConchError(
351 'cannot handle PAM 3 or 4 messages'))
353 return defer.fail(error.ConchError(
354 'bad PAM auth kind %i' % kind))
355 packet = NS('') + NS('') + NS('')
356 packet += struct.pack('>L', len(resp))
357 for prompt, echo in resp:
360 self.transport.sendPacket(MSG_USERAUTH_INFO_REQUEST, packet)
361 self._pamDeferred = defer.Deferred()
362 return self._pamDeferred
365 def ssh_USERAUTH_INFO_RESPONSE(self, packet):
367 The user has responded with answers to PAMs authentication questions.
368 Parse the packet into a PAM response and callback self._pamDeferred.
370 uint32 numer of responses
375 d, self._pamDeferred = self._pamDeferred, None
379 numResps = struct.unpack('>L', packet[:4])[0]
381 while len(resp) < numResps:
382 response, packet = getNS(packet)
383 resp.append((response, 0))
385 raise error.ConchError("%i bytes of extra data" % len(packet))
387 d.errback(failure.Failure())
393 class SSHUserAuthClient(service.SSHService):
395 A service implementing the client side of 'ssh-userauth'.
397 @ivar name: the name of this service: 'ssh-userauth'
399 @ivar preferredOrder: a list of authentication methods we support, in
400 order of preference. The client will try authentication methods in
401 this order, making callbacks for information when necessary.
402 @type preferredOrder: C{list}
403 @ivar user: the name of the user to authenticate as
405 @ivar instance: the service to start after authentication has finished
406 @type instance: L{service.SSHService}
407 @ivar authenticatedWith: a list of strings of authentication methods we've tried
408 @type authenticatedWith: C{list} of C{str}
409 @ivar triedPublicKeys: a list of public key objects that we've tried to
411 @type triedPublicKeys: C{list} of L{Key}
412 @ivar lastPublicKey: the last public key object we've tried to authenticate
414 @type lastPublicKey: L{Key}
418 name = 'ssh-userauth'
419 preferredOrder = ['publickey', 'password', 'keyboard-interactive']
422 def __init__(self, user, instance):
424 self.instance = instance
427 def serviceStarted(self):
428 self.authenticatedWith = []
429 self.triedPublicKeys = []
430 self.lastPublicKey = None
431 self.askForAuth('none', '')
434 def askForAuth(self, kind, extraData):
436 Send a MSG_USERAUTH_REQUEST.
438 @param kind: the authentication method to try.
440 @param extraData: method-specific data to go in the packet
441 @type extraData: C{str}
444 self.transport.sendPacket(MSG_USERAUTH_REQUEST, NS(self.user) +
445 NS(self.instance.name) + NS(kind) + extraData)
448 def tryAuth(self, kind):
450 Dispatch to an authentication method.
452 @param kind: the authentication method
455 kind = kind.replace('-', '_')
456 log.msg('trying to auth with %s' % (kind,))
457 f = getattr(self,'auth_%s' % (kind,), None)
462 def _ebAuth(self, ignored, *args):
464 Generic callback for a failed authentication attempt. Respond by
465 asking for the list of accepted methods (the 'none' method)
467 self.askForAuth('none', '')
470 def ssh_USERAUTH_SUCCESS(self, packet):
472 We received a MSG_USERAUTH_SUCCESS. The server has accepted our
473 authentication, so start the next service.
475 self.transport.setService(self.instance)
478 def ssh_USERAUTH_FAILURE(self, packet):
480 We received a MSG_USERAUTH_FAILURE. Payload::
484 If partial success is C{True}, then the previous method succeeded but is
485 not sufficent for authentication. C{methods} is a comma-separated list
486 of accepted authentication methods.
488 We sort the list of methods by their position in C{self.preferredOrder},
489 removing methods that have already succeeded. We then call
490 C{self.tryAuth} with the most preferred method.
492 @param packet: the L{MSG_USERAUTH_FAILURE} payload.
495 @return: a L{defer.Deferred} that will be callbacked with C{None} as
496 soon as all authentication methods have been tried, or C{None} if no
497 more authentication methods are available.
498 @rtype: C{defer.Deferred} or C{None}
500 canContinue, partial = getNS(packet)
501 partial = ord(partial)
503 self.authenticatedWith.append(self.lastAuth)
505 def orderByPreference(meth):
507 Invoked once per authentication method in order to extract a
508 comparison key which is then used for sorting.
510 @param meth: the authentication method.
513 @return: the comparison key for C{meth}.
516 if meth in self.preferredOrder:
517 return self.preferredOrder.index(meth)
519 # put the element at the end of the list.
520 return len(self.preferredOrder)
522 canContinue = sorted([meth for meth in canContinue.split(',')
523 if meth not in self.authenticatedWith],
524 key=orderByPreference)
526 log.msg('can continue with: %s' % canContinue)
527 return self._cbUserauthFailure(None, iter(canContinue))
530 def _cbUserauthFailure(self, result, iterator):
534 method = iterator.next()
535 except StopIteration:
536 self.transport.sendDisconnect(
537 transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
538 'no more authentication methods available')
540 d = defer.maybeDeferred(self.tryAuth, method)
541 d.addCallback(self._cbUserauthFailure, iterator)
545 def ssh_USERAUTH_PK_OK(self, packet):
547 This message (number 60) can mean several different messages depending
548 on the current authentication type. We dispatch to individual methods
549 in order to handle this request.
551 func = getattr(self, 'ssh_USERAUTH_PK_OK_%s' %
552 self.lastAuth.replace('-', '_'), None)
556 self.askForAuth('none', '')
559 def ssh_USERAUTH_PK_OK_publickey(self, packet):
561 This is MSG_USERAUTH_PK. Our public key is valid, so we create a
562 signature and try to authenticate with it.
564 publicKey = self.lastPublicKey
565 b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
566 NS(self.user) + NS(self.instance.name) + NS('publickey') +
567 '\x01' + NS(publicKey.sshType()) + NS(publicKey.blob()))
568 d = self.signData(publicKey, b)
570 self.askForAuth('none', '')
571 # this will fail, we'll move on
573 d.addCallback(self._cbSignedData)
574 d.addErrback(self._ebAuth)
577 def ssh_USERAUTH_PK_OK_password(self, packet):
579 This is MSG_USERAUTH_PASSWD_CHANGEREQ. The password given has expired.
580 We ask for an old password and a new password, then send both back to
583 prompt, language, rest = getNS(packet, 2)
584 self._oldPass = self._newPass = None
585 d = self.getPassword('Old Password: ')
586 d = d.addCallbacks(self._setOldPass, self._ebAuth)
587 d.addCallback(lambda ignored: self.getPassword(prompt))
588 d.addCallbacks(self._setNewPass, self._ebAuth)
591 def ssh_USERAUTH_PK_OK_keyboard_interactive(self, packet):
593 This is MSG_USERAUTH_INFO_RESPONSE. The server has sent us the
594 questions it wants us to answer, so we ask the user and sent the
597 name, instruction, lang, data = getNS(packet, 3)
598 numPrompts = struct.unpack('!L', data[:4])[0]
601 for i in range(numPrompts):
602 prompt, data = getNS(data)
603 echo = bool(ord(data[0]))
605 prompts.append((prompt, echo))
606 d = self.getGenericAnswers(name, instruction, prompts)
607 d.addCallback(self._cbGenericAnswers)
608 d.addErrback(self._ebAuth)
611 def _cbSignedData(self, signedData):
613 Called back out of self.signData with the signed data. Send the
614 authentication request with the signature.
616 @param signedData: the data signed by the user's private key.
617 @type signedData: C{str}
619 publicKey = self.lastPublicKey
620 self.askForAuth('publickey', '\x01' + NS(publicKey.sshType()) +
621 NS(publicKey.blob()) + NS(signedData))
624 def _setOldPass(self, op):
626 Called back when we are choosing a new password. Simply store the old
629 @param op: the old password as entered by the user
635 def _setNewPass(self, np):
637 Called back when we are choosing a new password. Get the old password
638 and send the authentication message with both.
640 @param np: the new password as entered by the user
645 self.askForAuth('password', '\xff' + NS(op) + NS(np))
648 def _cbGenericAnswers(self, responses):
650 Called back when we are finished answering keyboard-interactive
651 questions. Send the info back to the server in a
652 MSG_USERAUTH_INFO_RESPONSE.
654 @param responses: a list of C{str} responses
655 @type responses: C{list}
657 data = struct.pack('!L', len(responses))
659 data += NS(r.encode('UTF8'))
660 self.transport.sendPacket(MSG_USERAUTH_INFO_RESPONSE, data)
663 def auth_publickey(self):
665 Try to authenticate with a public key. Ask the user for a public key;
666 if the user has one, send the request to the server and return True.
667 Otherwise, return False.
671 d = defer.maybeDeferred(self.getPublicKey)
672 d.addBoth(self._cbGetPublicKey)
676 def _cbGetPublicKey(self, publicKey):
677 if isinstance(publicKey, str):
678 warnings.warn("Returning a string from "
679 "SSHUserAuthClient.getPublicKey() is deprecated "
680 "since Twisted 9.0. Return a keys.Key() instead.",
682 publicKey = keys.Key.fromString(publicKey)
683 if not isinstance(publicKey, keys.Key): # failure or None
685 if publicKey is not None:
686 self.lastPublicKey = publicKey
687 self.triedPublicKeys.append(publicKey)
688 log.msg('using key of type %s' % publicKey.type())
689 self.askForAuth('publickey', '\x00' + NS(publicKey.sshType()) +
690 NS(publicKey.blob()))
696 def auth_password(self):
698 Try to authenticate with a password. Ask the user for a password.
699 If the user will return a password, return True. Otherwise, return
704 d = self.getPassword()
706 d.addCallbacks(self._cbPassword, self._ebAuth)
708 else: # returned None, don't do password auth
712 def auth_keyboard_interactive(self):
714 Try to authenticate with keyboard-interactive authentication. Send
715 the request to the server and return True.
719 log.msg('authing with keyboard-interactive')
720 self.askForAuth('keyboard-interactive', NS('') + NS(''))
724 def _cbPassword(self, password):
726 Called back when the user gives a password. Send the request to the
729 @param password: the password the user entered
730 @type password: C{str}
732 self.askForAuth('password', '\x00' + NS(password))
735 def signData(self, publicKey, signData):
737 Sign the given data with the given public key.
739 By default, this will call getPrivateKey to get the private key,
740 then sign the data using Key.sign().
742 This method is factored out so that it can be overridden to use
743 alternate methods, such as a key agent.
745 @param publicKey: The public key object returned from L{getPublicKey}
746 @type publicKey: L{keys.Key}
748 @param signData: the data to be signed by the private key.
749 @type signData: C{str}
750 @return: a Deferred that's called back with the signature
751 @rtype: L{defer.Deferred}
753 key = self.getPrivateKey()
756 return key.addCallback(self._cbSignData, signData)
759 def _cbSignData(self, privateKey, signData):
761 Called back when the private key is returned. Sign the data and
762 return the signature.
764 @param privateKey: the private key object
765 @type publicKey: L{keys.Key}
766 @param signData: the data to be signed by the private key.
767 @type signData: C{str}
768 @return: the signature
771 if not isinstance(privateKey, keys.Key):
772 warnings.warn("Returning a PyCrypto key object from "
773 "SSHUserAuthClient.getPrivateKey() is deprecated "
774 "since Twisted 9.0. Return a keys.Key() instead.",
776 privateKey = keys.Key(privateKey)
777 return privateKey.sign(signData)
780 def getPublicKey(self):
782 Return a public key for the user. If no more public keys are
783 available, return C{None}.
785 This implementation always returns C{None}. Override it in a
786 subclass to actually find and return a public key object.
788 @rtype: L{Key} or L{NoneType}
793 def getPrivateKey(self):
795 Return a L{Deferred} that will be called back with the private key
796 object corresponding to the last public key from getPublicKey().
797 If the private key is not available, errback on the Deferred.
799 @rtype: L{Deferred} called back with L{Key}
801 return defer.fail(NotImplementedError())
804 def getPassword(self, prompt = None):
806 Return a L{Deferred} that will be called back with a password.
807 prompt is a string to display for the password, or None for a generic
808 'user@hostname's password: '.
810 @type prompt: C{str}/C{None}
811 @rtype: L{defer.Deferred}
813 return defer.fail(NotImplementedError())
816 def getGenericAnswers(self, name, instruction, prompts):
818 Returns a L{Deferred} with the responses to the promopts.
820 @param name: The name of the authentication currently in progress.
821 @param instruction: Describes what the authentication wants.
822 @param prompts: A list of (prompt, echo) pairs, where prompt is a
823 string to display and echo is a boolean indicating whether the
824 user's response should be echoed as they type it.
826 return defer.fail(NotImplementedError())
829 MSG_USERAUTH_REQUEST = 50
830 MSG_USERAUTH_FAILURE = 51
831 MSG_USERAUTH_SUCCESS = 52
832 MSG_USERAUTH_BANNER = 53
833 MSG_USERAUTH_PASSWD_CHANGEREQ = 60
834 MSG_USERAUTH_INFO_REQUEST = 60
835 MSG_USERAUTH_INFO_RESPONSE = 61
836 MSG_USERAUTH_PK_OK = 60
839 for k, v in locals().items():
841 messages[v] = k # doesn't handle doubles
843 SSHUserAuthServer.protocolMessages = messages
844 SSHUserAuthClient.protocolMessages = messages