1# -*- test-case-name: twisted.conch.test.test_userauth -*-
2# Copyright (c) Twisted Matrix Laboratories.
3# See LICENSE for details.
4
5"""
6Implementation of the ssh-userauth service.
7Currently implemented authentication types are public-key and password.
8
9Maintainer: Paul Swartz
10"""
11
12import struct
13from twisted.conch import error, interfaces
14from twisted.conch.ssh import keys, transport, service
15from twisted.conch.ssh.common import NS, getNS
16from twisted.cred import credentials
17from twisted.cred.error import UnauthorizedLogin
18from twisted.internet import defer, reactor
19from twisted.python import failure, log
20
21
22
23class SSHUserAuthServer(service.SSHService):
24    """
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
27    this server.
28
29    @ivar name: the name of this service: 'ssh-userauth'
30    @type name: C{str}
31    @ivar authenticatedWith: a list of authentication methods that have
32        already been used.
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
43        an incorrect password
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
51        methods.
52    @type supportedAuthentications: C{list} of C{str}
53    @ivar user: the last username the client tried to authenticate with
54    @type user: C{str}
55    @ivar method: the current authentication method
56    @type method: C{str}
57    @ivar nextService: the service the user wants started after authentication
58        has been completed.
59    @type nextService: C{str}
60    @ivar portal: the L{twisted.cred.portal.Portal} we are using for
61        authentication
62    @type portal: L{twisted.cred.portal.Portal}
63    @ivar clock: an object with a callLater method.  Stubbed out for testing.
64    """
65
66
67    name = 'ssh-userauth'
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
73    clock = reactor
74    interfaceToMethod = {
75        credentials.ISSHPrivateKey : 'publickey',
76        credentials.IUsernamePassword : 'password',
77        credentials.IPluggableAuthenticationModules : 'keyboard-interactive',
78    }
79
80
81    def serviceStarted(self):
82        """
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.
87        """
88        self.authenticatedWith = []
89        self.loginAttempts = 0
90        self.user = None
91        self.nextService = None
92        self._pamDeferred = None
93        self.portal = self.transport.factory.portal
94
95        self.supportedAuthentications = []
96        for i in self.portal.listCredentialsInterfaces():
97            if i in self.interfaceToMethod:
98                self.supportedAuthentications.append(self.interfaceToMethod[i])
99
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(
107            self.loginTimeout,
108            self.timeoutAuthentication)
109
110
111    def serviceStopped(self):
112        """
113        Called when the userauth service is stopped.  Cancel the login timeout
114        if it's still going.
115        """
116        if self._cancelLoginTimeout:
117            self._cancelLoginTimeout.cancel()
118            self._cancelLoginTimeout = None
119
120
121    def timeoutAuthentication(self):
122        """
123        Called when the user has timed out on authentication.  Disconnect
124        with a DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE message.
125        """
126        self._cancelLoginTimeout = None
127        self.transport.sendDisconnect(
128            transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
129            'you took too long')
130
131
132    def tryAuth(self, kind, user, data):
133        """
134        Try to authenticate the user with the given method.  Dispatches to a
135        auth_* method.
136
137        @param kind: the authentication method to try.
138        @type kind: C{str}
139        @param user: the username the client is authenticating with.
140        @type user: C{str}
141        @param data: authentication specific data sent by the client.
142        @type data: C{str}
143        @return: A Deferred called back if the method succeeded, or erred back
144            if it failed.
145        @rtype: C{defer.Deferred}
146        """
147        log.msg('%s trying auth %s' % (user, kind))
148        if kind not in self.supportedAuthentications:
149            return defer.fail(
150                    error.ConchError('unsupported authentication, failing'))
151        kind = kind.replace('-', '_')
152        f = getattr(self,'auth_%s'%kind, None)
153        if f:
154            ret = f(data)
155            if not ret:
156                return defer.fail(
157                        error.ConchError('%s return None instead of a Deferred'
158                            % kind))
159            else:
160                return ret
161        return defer.fail(error.ConchError('bad auth type: %s' % kind))
162
163
164    def ssh_USERAUTH_REQUEST(self, packet):
165        """
166        The client has requested authentication.  Payload::
167            string user
168            string next service
169            string method
170            <authentication specific data>
171
172        @type packet: C{str}
173        """
174        user, nextService, method, rest = getNS(packet, 3)
175        if user != self.user or nextService != self.nextService:
176            self.authenticatedWith = [] # clear auth state
177        self.user = user
178        self.nextService = nextService
179        self.method = method
180        d = self.tryAuth(method, user, rest)
181        if not d:
182            self._ebBadAuth(
183                failure.Failure(error.ConchError('auth returned none')))
184            return
185        d.addCallback(self._cbFinishedAuth)
186        d.addErrback(self._ebMaybeBadAuth)
187        d.addErrback(self._ebBadAuth)
188        return d
189
190
191    def _cbFinishedAuth(self, (interface, avatar, logout)):
192        """
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.
196        """
197        self.transport.avatar = avatar
198        self.transport.logoutFunction = logout
199        service = self.transport.factory.getService(self.transport,
200                self.nextService)
201        if not service:
202            raise error.ConchError('could not get next service: %s'
203                                  % self.nextService)
204        log.msg('%s authenticated with %s' % (self.user, self.method))
205        self.transport.sendPacket(MSG_USERAUTH_SUCCESS, '')
206        self.transport.setService(service())
207
208
209    def _ebMaybeBadAuth(self, reason):
210        """
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.
214
215        @type reason: L{twisted.python.failure.Failure}
216        """
217        reason.trap(error.NotEnoughAuthentication)
218        self.transport.sendPacket(MSG_USERAUTH_FAILURE,
219                NS(','.join(self.supportedAuthentications)) + '\xff')
220
221
222    def _ebBadAuth(self, reason):
223        """
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
228        attempts.
229
230        @type reason: L{twisted.python.failure.Failure}
231        """
232        if reason.check(error.IgnoreAuthentication):
233            return
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())
240            else:
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')
247                return
248        self.transport.sendPacket(
249                MSG_USERAUTH_FAILURE,
250                NS(','.join(self.supportedAuthentications)) + '\x00')
251
252
253    def auth_publickey(self, packet):
254        """
255        Public key authentication.  Payload::
256            byte has signature
257            string algorithm name
258            string key blob
259            [string signature] (if has signature is True)
260
261        Create a SSHPublicKey credential and verify it using our portal.
262        """
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
267        if hasSig:
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,
272                    signature)
273            return self.portal.login(c, None, interfaces.IConchUser)
274        else:
275            c = credentials.SSHPrivateKey(self.user, algName, blob, None, None)
276            return self.portal.login(c, None,
277                    interfaces.IConchUser).addErrback(self._ebCheckKey,
278                            packet[1:])
279
280
281    def _ebCheckKey(self, reason, packet):
282        """
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.
286        """
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())
291
292
293    def auth_password(self, packet):
294        """
295        Password authentication.  Payload::
296            string password
297
298        Make a UsernamePassword credential and verify it with our portal.
299        """
300        password = getNS(packet[1:])[0]
301        c = credentials.UsernamePassword(self.user, password)
302        return self.portal.login(c, None, interfaces.IConchUser).addErrback(
303                                                        self._ebPassword)
304
305
306    def _ebPassword(self, f):
307        """
308        If the password is invalid, wait before sending the failure in order
309        to delay brute-force password guessing.
310        """
311        d = defer.Deferred()
312        self.clock.callLater(self.passwordDelay, d.callback, f)
313        return d
314
315
316    def auth_keyboard_interactive(self, packet):
317        """
318        Keyboard interactive authentication.  No payload.  We create a
319        PluggableAuthenticationModules credential and authenticate with our
320        portal.
321        """
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,
328                self._pamConv)
329        return self.portal.login(c, None, interfaces.IConchUser)
330
331
332    def _pamConv(self, items):
333        """
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.
337
338        @param items: a list of 2-tuples (message, kind).  We only care about
339            kinds 1 (password) and 2 (text).
340        @type items: C{list}
341        @rtype: L{defer.Deferred}
342        """
343        resp = []
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))
349            elif kind in (3, 4):
350                return defer.fail(error.ConchError(
351                    'cannot handle PAM 3 or 4 messages'))
352            else:
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:
358            packet += NS(prompt)
359            packet += chr(echo)
360        self.transport.sendPacket(MSG_USERAUTH_INFO_REQUEST, packet)
361        self._pamDeferred = defer.Deferred()
362        return self._pamDeferred
363
364
365    def ssh_USERAUTH_INFO_RESPONSE(self, packet):
366        """
367        The user has responded with answers to PAMs authentication questions.
368        Parse the packet into a PAM response and callback self._pamDeferred.
369        Payload::
370            uint32 numer of responses
371            string response 1
372            ...
373            string response n
374        """
375        d, self._pamDeferred = self._pamDeferred, None
376
377        try:
378            resp = []
379            numResps = struct.unpack('>L', packet[:4])[0]
380            packet = packet[4:]
381            while len(resp) < numResps:
382                response, packet = getNS(packet)
383                resp.append((response, 0))
384            if packet:
385                raise error.ConchError("%i bytes of extra data" % len(packet))
386        except:
387            d.errback(failure.Failure())
388        else:
389            d.callback(resp)
390
391
392
393class SSHUserAuthClient(service.SSHService):
394    """
395    A service implementing the client side of 'ssh-userauth'.
396
397    This service will try all authentication methods provided by the server,
398    making callbacks for more information when necessary.
399
400    @ivar name: the name of this service: 'ssh-userauth'
401    @type name: C{str}
402    @ivar preferredOrder: a list of authentication methods that should be used
403        first, in order of preference, if supported by the server
404    @type preferredOrder: C{list}
405    @ivar user: the name of the user to authenticate as
406    @type user: C{str}
407    @ivar instance: the service to start after authentication has finished
408    @type instance: L{service.SSHService}
409    @ivar authenticatedWith: a list of strings of authentication methods we've tried
410    @type authenticatedWith: C{list} of C{str}
411    @ivar triedPublicKeys: a list of public key objects that we've tried to
412        authenticate with
413    @type triedPublicKeys: C{list} of L{Key}
414    @ivar lastPublicKey: the last public key object we've tried to authenticate
415        with
416    @type lastPublicKey: L{Key}
417    """
418
419
420    name = 'ssh-userauth'
421    preferredOrder = ['publickey', 'password', 'keyboard-interactive']
422
423
424    def __init__(self, user, instance):
425        self.user = user
426        self.instance = instance
427
428
429    def serviceStarted(self):
430        self.authenticatedWith = []
431        self.triedPublicKeys = []
432        self.lastPublicKey = None
433        self.askForAuth('none', '')
434
435
436    def askForAuth(self, kind, extraData):
437        """
438        Send a MSG_USERAUTH_REQUEST.
439
440        @param kind: the authentication method to try.
441        @type kind: C{str}
442        @param extraData: method-specific data to go in the packet
443        @type extraData: C{str}
444        """
445        self.lastAuth = kind
446        self.transport.sendPacket(MSG_USERAUTH_REQUEST, NS(self.user) +
447                NS(self.instance.name) + NS(kind) + extraData)
448
449
450    def tryAuth(self, kind):
451        """
452        Dispatch to an authentication method.
453
454        @param kind: the authentication method
455        @type kind: C{str}
456        """
457        kind = kind.replace('-', '_')
458        log.msg('trying to auth with %s' % (kind,))
459        f = getattr(self,'auth_%s' % (kind,), None)
460        if f:
461            return f()
462
463
464    def _ebAuth(self, ignored, *args):
465        """
466        Generic callback for a failed authentication attempt.  Respond by
467        asking for the list of accepted methods (the 'none' method)
468        """
469        self.askForAuth('none', '')
470
471
472    def ssh_USERAUTH_SUCCESS(self, packet):
473        """
474        We received a MSG_USERAUTH_SUCCESS.  The server has accepted our
475        authentication, so start the next service.
476        """
477        self.transport.setService(self.instance)
478
479
480    def ssh_USERAUTH_FAILURE(self, packet):
481        """
482        We received a MSG_USERAUTH_FAILURE.  Payload::
483            string methods
484            byte partial success
485
486        If partial success is C{True}, then the previous method succeeded but is
487        not sufficent for authentication. C{methods} is a comma-separated list
488        of accepted authentication methods.
489
490        We sort the list of methods by their position in C{self.preferredOrder},
491        removing methods that have already succeeded. We then call
492        C{self.tryAuth} with the most preferred method.
493
494        @param packet: the L{MSG_USERAUTH_FAILURE} payload.
495        @type packet: C{str}
496
497        @return: a L{defer.Deferred} that will be callbacked with C{None} as
498            soon as all authentication methods have been tried, or C{None} if no
499            more authentication methods are available.
500        @rtype: C{defer.Deferred} or C{None}
501        """
502        canContinue, partial = getNS(packet)
503        partial = ord(partial)
504        if partial:
505            self.authenticatedWith.append(self.lastAuth)
506
507        def orderByPreference(meth):
508            """
509            Invoked once per authentication method in order to extract a
510            comparison key which is then used for sorting.
511
512            @param meth: the authentication method.
513            @type meth: C{str}
514
515            @return: the comparison key for C{meth}.
516            @rtype: C{int}
517            """
518            if meth in self.preferredOrder:
519                return self.preferredOrder.index(meth)
520            else:
521                # put the element at the end of the list.
522                return len(self.preferredOrder)
523
524        canContinue = sorted([meth for meth in canContinue.split(',')
525                              if meth not in self.authenticatedWith],
526                             key=orderByPreference)
527
528        log.msg('can continue with: %s' % canContinue)
529        return self._cbUserauthFailure(None, iter(canContinue))
530
531
532    def _cbUserauthFailure(self, result, iterator):
533        if result:
534            return
535        try:
536            method = iterator.next()
537        except StopIteration:
538            self.transport.sendDisconnect(
539                transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
540                'no more authentication methods available')
541        else:
542            d = defer.maybeDeferred(self.tryAuth, method)
543            d.addCallback(self._cbUserauthFailure, iterator)
544            return d
545
546
547    def ssh_USERAUTH_PK_OK(self, packet):
548        """
549        This message (number 60) can mean several different messages depending
550        on the current authentication type.  We dispatch to individual methods
551        in order to handle this request.
552        """
553        func = getattr(self, 'ssh_USERAUTH_PK_OK_%s' %
554                       self.lastAuth.replace('-', '_'), None)
555        if func is not None:
556            return func(packet)
557        else:
558            self.askForAuth('none', '')
559
560
561    def ssh_USERAUTH_PK_OK_publickey(self, packet):
562        """
563        This is MSG_USERAUTH_PK.  Our public key is valid, so we create a
564        signature and try to authenticate with it.
565        """
566        publicKey = self.lastPublicKey
567        b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
568             NS(self.user) + NS(self.instance.name) + NS('publickey') +
569             '\x01' + NS(publicKey.sshType()) + NS(publicKey.blob()))
570        d  = self.signData(publicKey, b)
571        if not d:
572            self.askForAuth('none', '')
573            # this will fail, we'll move on
574            return
575        d.addCallback(self._cbSignedData)
576        d.addErrback(self._ebAuth)
577
578
579    def ssh_USERAUTH_PK_OK_password(self, packet):
580        """
581        This is MSG_USERAUTH_PASSWD_CHANGEREQ.  The password given has expired.
582        We ask for an old password and a new password, then send both back to
583        the server.
584        """
585        prompt, language, rest = getNS(packet, 2)
586        self._oldPass = self._newPass = None
587        d = self.getPassword('Old Password: ')
588        d = d.addCallbacks(self._setOldPass, self._ebAuth)
589        d.addCallback(lambda ignored: self.getPassword(prompt))
590        d.addCallbacks(self._setNewPass, self._ebAuth)
591
592
593    def ssh_USERAUTH_PK_OK_keyboard_interactive(self, packet):
594        """
595        This is MSG_USERAUTH_INFO_RESPONSE.  The server has sent us the
596        questions it wants us to answer, so we ask the user and sent the
597        responses.
598        """
599        name, instruction, lang, data = getNS(packet, 3)
600        numPrompts = struct.unpack('!L', data[:4])[0]
601        data = data[4:]
602        prompts = []
603        for i in range(numPrompts):
604            prompt, data = getNS(data)
605            echo = bool(ord(data[0]))
606            data = data[1:]
607            prompts.append((prompt, echo))
608        d = self.getGenericAnswers(name, instruction, prompts)
609        d.addCallback(self._cbGenericAnswers)
610        d.addErrback(self._ebAuth)
611
612
613    def _cbSignedData(self, signedData):
614        """
615        Called back out of self.signData with the signed data.  Send the
616        authentication request with the signature.
617
618        @param signedData: the data signed by the user's private key.
619        @type signedData: C{str}
620        """
621        publicKey = self.lastPublicKey
622        self.askForAuth('publickey', '\x01' + NS(publicKey.sshType()) +
623                NS(publicKey.blob()) + NS(signedData))
624
625
626    def _setOldPass(self, op):
627        """
628        Called back when we are choosing a new password.  Simply store the old
629        password for now.
630
631        @param op: the old password as entered by the user
632        @type op: C{str}
633        """
634        self._oldPass = op
635
636
637    def _setNewPass(self, np):
638        """
639        Called back when we are choosing a new password.  Get the old password
640        and send the authentication message with both.
641
642        @param np: the new password as entered by the user
643        @type np: C{str}
644        """
645        op = self._oldPass
646        self._oldPass = None
647        self.askForAuth('password', '\xff' + NS(op) + NS(np))
648
649
650    def _cbGenericAnswers(self, responses):
651        """
652        Called back when we are finished answering keyboard-interactive
653        questions.  Send the info back to the server in a
654        MSG_USERAUTH_INFO_RESPONSE.
655
656        @param responses: a list of C{str} responses
657        @type responses: C{list}
658        """
659        data = struct.pack('!L', len(responses))
660        for r in responses:
661            data += NS(r.encode('UTF8'))
662        self.transport.sendPacket(MSG_USERAUTH_INFO_RESPONSE, data)
663
664
665    def auth_publickey(self):
666        """
667        Try to authenticate with a public key.  Ask the user for a public key;
668        if the user has one, send the request to the server and return True.
669        Otherwise, return False.
670
671        @rtype: C{bool}
672        """
673        d = defer.maybeDeferred(self.getPublicKey)
674        d.addBoth(self._cbGetPublicKey)
675        return d
676
677
678    def _cbGetPublicKey(self, publicKey):
679        if not isinstance(publicKey, keys.Key): # failure or None
680            publicKey = None
681        if publicKey is not None:
682            self.lastPublicKey = publicKey
683            self.triedPublicKeys.append(publicKey)
684            log.msg('using key of type %s' % publicKey.type())
685            self.askForAuth('publickey', '\x00' + NS(publicKey.sshType()) +
686                            NS(publicKey.blob()))
687            return True
688        else:
689            return False
690
691
692    def auth_password(self):
693        """
694        Try to authenticate with a password.  Ask the user for a password.
695        If the user will return a password, return True.  Otherwise, return
696        False.
697
698        @rtype: C{bool}
699        """
700        d = self.getPassword()
701        if d:
702            d.addCallbacks(self._cbPassword, self._ebAuth)
703            return True
704        else: # returned None, don't do password auth
705            return False
706
707
708    def auth_keyboard_interactive(self):
709        """
710        Try to authenticate with keyboard-interactive authentication.  Send
711        the request to the server and return True.
712
713        @rtype: C{bool}
714        """
715        log.msg('authing with keyboard-interactive')
716        self.askForAuth('keyboard-interactive', NS('') + NS(''))
717        return True
718
719
720    def _cbPassword(self, password):
721        """
722        Called back when the user gives a password.  Send the request to the
723        server.
724
725        @param password: the password the user entered
726        @type password: C{str}
727        """
728        self.askForAuth('password', '\x00' + NS(password))
729
730
731    def signData(self, publicKey, signData):
732        """
733        Sign the given data with the given public key.
734
735        By default, this will call getPrivateKey to get the private key,
736        then sign the data using Key.sign().
737
738        This method is factored out so that it can be overridden to use
739        alternate methods, such as a key agent.
740
741        @param publicKey: The public key object returned from L{getPublicKey}
742        @type publicKey: L{keys.Key}
743
744        @param signData: the data to be signed by the private key.
745        @type signData: C{str}
746        @return: a Deferred that's called back with the signature
747        @rtype: L{defer.Deferred}
748        """
749        key = self.getPrivateKey()
750        if not key:
751            return
752        return key.addCallback(self._cbSignData, signData)
753
754
755    def _cbSignData(self, privateKey, signData):
756        """
757        Called back when the private key is returned.  Sign the data and
758        return the signature.
759
760        @param privateKey: the private key object
761        @type publicKey: L{keys.Key}
762        @param signData: the data to be signed by the private key.
763        @type signData: C{str}
764        @return: the signature
765        @rtype: C{str}
766        """
767        return privateKey.sign(signData)
768
769
770    def getPublicKey(self):
771        """
772        Return a public key for the user.  If no more public keys are
773        available, return C{None}.
774
775        This implementation always returns C{None}.  Override it in a
776        subclass to actually find and return a public key object.
777
778        @rtype: L{Key} or L{NoneType}
779        """
780        return None
781
782
783    def getPrivateKey(self):
784        """
785        Return a L{Deferred} that will be called back with the private key
786        object corresponding to the last public key from getPublicKey().
787        If the private key is not available, errback on the Deferred.
788
789        @rtype: L{Deferred} called back with L{Key}
790        """
791        return defer.fail(NotImplementedError())
792
793
794    def getPassword(self, prompt = None):
795        """
796        Return a L{Deferred} that will be called back with a password.
797        prompt is a string to display for the password, or None for a generic
798        'user@hostname's password: '.
799
800        @type prompt: C{str}/C{None}
801        @rtype: L{defer.Deferred}
802        """
803        return defer.fail(NotImplementedError())
804
805
806    def getGenericAnswers(self, name, instruction, prompts):
807        """
808        Returns a L{Deferred} with the responses to the promopts.
809
810        @param name: The name of the authentication currently in progress.
811        @param instruction: Describes what the authentication wants.
812        @param prompts: A list of (prompt, echo) pairs, where prompt is a
813        string to display and echo is a boolean indicating whether the
814        user's response should be echoed as they type it.
815        """
816        return defer.fail(NotImplementedError())
817
818
819MSG_USERAUTH_REQUEST          = 50
820MSG_USERAUTH_FAILURE          = 51
821MSG_USERAUTH_SUCCESS          = 52
822MSG_USERAUTH_BANNER           = 53
823MSG_USERAUTH_INFO_RESPONSE    = 61
824MSG_USERAUTH_PK_OK            = 60
825
826messages = {}
827for k, v in locals().items():
828    if k[:4]=='MSG_':
829        messages[v] = k
830
831SSHUserAuthServer.protocolMessages = messages
832SSHUserAuthClient.protocolMessages = messages
833del messages
834del v
835
836# Doubles, not included in the protocols' mappings
837MSG_USERAUTH_PASSWD_CHANGEREQ = 60
838MSG_USERAUTH_INFO_REQUEST     = 60
839