o bSl@sdZddlZddlmZmZddlmZmZmZddl m Z m Z ddl m Z ddlmZddlmZmZdd lmZdd lmZdd lmZGd d d ejZGdddejZdZdZdZdZdZ dZ!iZ"e#e$%D]\Z&Z'e&dddkr}e&e"e'<qme"e_(e"e_(["['dZ)dZ*dS)z Implementation of the ssh-userauth service. Currently implemented authentication types are public-key and password. Maintainer: Paul Swartz N)error interfaces)keysservice transport)NSgetNS) credentials)UnauthorizedLogin)deferreactor)Logger)failure) nativeStringc@seZdZdZdZdZdZdZeZ e j de j diZ eZdd Zd d Zd d ZddZddZddZddZddZddZddZddZddZd S)!SSHUserAuthServera A service implementing the server side of the 'ssh-userauth' service. It is used to authenticate the user on the other side as being able to access this server. @ivar name: the name of this service: 'ssh-userauth' @type name: L{bytes} @ivar authenticatedWith: a list of authentication methods that have already been used. @type authenticatedWith: L{list} @ivar loginTimeout: the number of seconds we wait before disconnecting the user for taking too long to authenticate @type loginTimeout: L{int} @ivar attemptsBeforeDisconnect: the number of failed login attempts we allow before disconnecting. @type attemptsBeforeDisconnect: L{int} @ivar loginAttempts: the number of login attempts that have been made @type loginAttempts: L{int} @ivar passwordDelay: the number of seconds to delay when the user gives an incorrect password @type passwordDelay: L{int} @ivar interfaceToMethod: a L{dict} mapping credential interfaces to authentication methods. The server checks to see which of the cred interfaces have checkers and tells the client that those methods are valid for authentication. @type interfaceToMethod: L{dict} @ivar supportedAuthentications: A list of the supported authentication methods. @type supportedAuthentications: L{list} of L{bytes} @ivar user: the last username the client tried to authenticate with @type user: L{bytes} @ivar method: the current authentication method @type method: L{bytes} @ivar nextService: the service the user wants started after authentication has been completed. @type nextService: L{bytes} @ivar portal: the L{twisted.cred.portal.Portal} we are using for authentication @type portal: L{twisted.cred.portal.Portal} @ivar clock: an object with a callLater method. Stubbed out for testing. ssh-userauthi publickeypasswordcCsg|_d|_d|_d|_|jjj|_g|_|jD]}||j vr*|j |j |q|j ds @type packet: L{bytes} zauth returned noneN)rrrrmethodr? _ebBadAuthrFailurerr9 addCallback_cbFinishedAuth addErrback_ebMaybeBadAuth)r(packetrrrArestdr*r*r+ssh_USERAUTH_REQUESTs    z&SSHUserAuthServer.ssh_USERAUTH_REQUESTcCsz|\}}}||j_||j_|jj|j|j}|s"td|j|jj d|j |j d|j t d|j|dS)z The callback when user has successfully been authenticated. For a description of the arguments, see L{twisted.cred.portal.Portal.login}. We start the service requested by the user. zcould not get next service: z&{user!r} authenticated with {method!r}rrAN)ravatarlogoutFunctionr getServicerrr9r6r7rrA sendPacketMSG_USERAUTH_SUCCESS setService)r(result interfacerNlogoutrr*r*r+rEs  z!SSHUserAuthServer._cbFinishedAuthcCs.|tj|jttd|jddS)z An intermediate errback. If the reason is error.NotEnoughAuthentication, we send a MSG_USERAUTH_FAILURE, but with the partial success indicator set. @type reason: L{twisted.python.failure.Failure} ,N) traprNotEnoughAuthenticationrrQMSG_USERAUTH_FAILURErjoinrr(reasonr*r*r+rGs z!SSHUserAuthServer._ebMaybeBadAuthcCs|tjrdS|jdkrZ|jjd|j|jd|tr(|jjd|dn|tj r9|jjd|dn |jj d ||jd |j d 7_ |j |j krZ|j t jd dS|j ttd |jddS)a{ The final errback in the authentication chain. If the reason is error.IgnoreAuthentication, we simply return; the authentication method has sent its own response. Otherwise, send a failure message and (if the method is not 'none') increment the number of login attempts. @type reason: L{twisted.python.failure.Failure} Nnonez{user!r} failed auth {method!r}rLzunauthorized login: {message})messagezreason: {reason})r^z#Error checking auth for user {user})rrrstoo many bad authsrW)checkrIgnoreAuthenticationrAr6r7rr getErrorMessager9rrattemptsBeforeDisconnectrr0r1rQr[rr\rr]r*r*r+rBs6      zSSHUserAuthServer._ebBadAuthc Cs>t|dd}t|ddd\}}}ztj|}Wntjy;d|d}|j |t t |YSw|rDt|dpEd}|rt |jjttft |jt |jt dt|ft |t |} t|j||| |} |j| dtjSt|j||dd} |j| dtj|j|ddS)a Public key authentication. Payload:: byte has signature string algorithm name string key blob [string signature] (if has signature is True) Create a SSHPublicKey credential and verify it using our portal. rrNz"Unsupported key type {} or bad keyasciir)ordrrKey fromString BadKeyErrorformatdecoder6rr r8r rr sessionIDbytesMSG_USERAUTH_REQUESTrrsshTyper SSHPrivateKeyrloginr IConchUserrF _ebCheckKey) r(rHhasSigalgNameblobrIpubKeyr signaturebcr*r*r+auth_publickeysB     z SSHUserAuthServer.auth_publickeycCs(|tj|jt|ttS)z Called back if the user did not sent a signature. If reason is error.ValidPublicKey then this key is valid for the user to authenticate with. Send MSG_USERAUTH_PK_OK. ) rYrValidPublicKeyrrQMSG_USERAUTH_PK_OKrrCrc)r(r^rHr*r*r+ru$s zSSHUserAuthServer._ebCheckKeycCs<t|ddd}t|j|}|j|dtj|j S)z Password authentication. Payload:: string password Make a UsernamePassword credential and verify it with our portal. rNr) rr UsernamePasswordrrrsrrtrF _ebPassword)r(rHpasswordr|r*r*r+ auth_password/s zSSHUserAuthServer.auth_passwordcCs t}|j|j|j||S)z If the password is invalid, wait before sending the failure in order to delay brute-force password guessing. )r Deferredr#r$ passwordDelaycallback)r(r=rJr*r*r+r<szSSHUserAuthServer._ebPasswordN)__name__ __module__ __qualname____doc__namer%rerr r#r ISSHPrivateKeyIUsernamePasswordrr r6r,r/r&r?rKrErGrBr}rurrr*r*r*r+rs.*   '( rc@seZdZdZdZgdZddZddZdd Zd d Z d d Z ddZ ddZ ddZ ddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Zd;d7d8Zd9d:Z d6S)<SSHUserAuthClienta+ A service implementing the client side of 'ssh-userauth'. This service will try all authentication methods provided by the server, making callbacks for more information when necessary. @ivar name: the name of this service: 'ssh-userauth' @type name: L{str} @ivar preferredOrder: a list of authentication methods that should be used first, in order of preference, if supported by the server @type preferredOrder: L{list} @ivar user: the name of the user to authenticate as @type user: L{bytes} @ivar instance: the service to start after authentication has finished @type instance: L{service.SSHService} @ivar authenticatedWith: a list of strings of authentication methods we've tried @type authenticatedWith: L{list} of L{bytes} @ivar triedPublicKeys: a list of public key objects that we've tried to authenticate with @type triedPublicKeys: L{list} of L{Key} @ivar lastPublicKey: the last public key object we've tried to authenticate with @type lastPublicKey: L{Key} r)rrkeyboard-interactivecCs||_||_dSN)rinstance)r(rrr*r*r+__init__cs zSSHUserAuthClient.__init__cCs"g|_g|_d|_|dddS)Nr_rM)rtriedPublicKeys lastPublicKey askForAuthr.r*r*r+r,gsz SSHUserAuthClient.serviceStartedcCs6||_|jtt|jt|jjt||dS)z Send a MSG_USERAUTH_REQUEST. @param kind: the authentication method to try. @type kind: L{bytes} @param extraData: method-specific data to go in the packet @type extraData: L{bytes} N)lastAuthrrQrprrrr)r(r2 extraDatar*r*r+rms   zSSHUserAuthClient.askForAuthcCs>t|dd}|jjd|dt|d|d}|r|SdS)z Dispatch to an authentication method. @param kind: the authentication method @type kind: L{bytes} r3r4ztrying to auth with {kind})r2r5N)rr:r6r7r;)r(r2r=r*r*r+r?|s zSSHUserAuthClient.tryAuthcGs|dddS)z Generic callback for a failed authentication attempt. Respond by asking for the list of accepted methods (the 'none' method) r_rMN)r)r(ignoredargsr*r*r+_ebAuthszSSHUserAuthClient._ebAuthcCs|j|jdS)z We received a MSG_USERAUTH_SUCCESS. The server has accepted our authentication, so start the next service. N)rrSr)r(rHr*r*r+ssh_USERAUTH_SUCCESSsz&SSHUserAuthClient.ssh_USERAUTH_SUCCESScsrt|\}}t|}|rjjfdd}tfdd|dD|d}jjd|d d t |S) av We received a MSG_USERAUTH_FAILURE. Payload:: string methods byte partial success If partial success is C{True}, then the previous method succeeded but is not sufficient for authentication. C{methods} is a comma-separated list of accepted authentication methods. We sort the list of methods by their position in C{self.preferredOrder}, removing methods that have already succeeded. We then call C{self.tryAuth} with the most preferred method. @param packet: the C{MSG_USERAUTH_FAILURE} payload. @type packet: L{bytes} @return: a L{defer.Deferred} that will be callbacked with L{None} as soon as all authentication methods have been tried, or L{None} if no more authentication methods are available. @rtype: C{defer.Deferred} or L{None} cs |jvr j|StjS)a8 Invoked once per authentication method in order to extract a comparison key which is then used for sorting. @param meth: the authentication method. @type meth: L{bytes} @return: the comparison key for C{meth}. @rtype: L{int} )preferredOrderindexlen)methr.r*r+orderByPreferences  zASSHUserAuthClient.ssh_USERAUTH_FAILURE..orderByPreferencec3s|] }|jvr|VqdSr)r).0rr.r*r+ s z9SSHUserAuthClient.ssh_USERAUTH_FAILURE..rW)keyzcan continue with: {methods})methodsN) rrhrr rsortedsplitr6r7_cbUserauthFailureiter)r(rH canContinuepartialrr*r.r+ssh_USERAUTH_FAILUREs    z&SSHUserAuthClient.ssh_USERAUTH_FAILUREcCsZ|rdSzt|}Wnty|jtjdYdSwt|j|}||j ||S)Ns(no more authentication methods available) next StopIterationrr0r1r maybeDeferredr?rDr)r(rTiteratorrArJr*r*r+rs   z$SSHUserAuthClient._cbUserauthFailurecCs>t|dt|jddd}|dur||S|dddS)z This message (number 60) can mean several different messages depending on the current authentication type. We dispatch to individual methods in order to handle this request. zssh_USERAUTH_PK_OK_%sr3r4Nr_rM)r;rrr:r)r(rHfuncr*r*r+ssh_USERAUTH_PK_OKsz$SSHUserAuthClient.ssh_USERAUTH_PK_OKcCs|j}t|jjttft|jt|jjtddt| t| }| ||}|s;| dddS| |j||jdS)z This is MSG_USERAUTH_PK. Our public key is valid, so we create a signature and try to authenticate with it. rr_rMN)rrrrnrorprrrrqrxsignDatarrD _cbSignedDatarFr)r(rH publicKeyr{rJr*r*r+ssh_USERAUTH_PK_OK_publickeys.       z.SSHUserAuthClient.ssh_USERAUTH_PK_OK_publickeycs^t|d\}}d__d}|jj}|fdd|jjdS)z This is MSG_USERAUTH_PASSWD_CHANGEREQ. The password given has expired. We ask for an old password and a new password, then send both back to the server. rfNsOld Password: cs Sr) getPassword)rpromptr(r*r+s z?SSHUserAuthClient.ssh_USERAUTH_PK_OK_password..) r_oldPass_newPassr addCallbacks _setOldPassrrD _setNewPass)r(rHlanguagerIrJr*rr+ssh_USERAUTH_PK_OK_passwords   z-SSHUserAuthClient.ssh_USERAUTH_PK_OK_passwordc Cst|d\}}}}td|ddd}|dd}g}t|D]}t|\} }tt|dd} |dd}|| | fq!||||} | |j | |j dS)z This is MSG_USERAUTH_INFO_RESPONSE. The server has sent us the questions it wants us to answer, so we ask the user and sent the responses. r@!LNrr) rstructunpackrangeboolrhr getGenericAnswersrD_cbGenericAnswersrFr) r(rHr instructionlangr< numPromptspromptsr)rechorJr*r*r+'ssh_USERAUTH_PK_OK_keyboard_interactives     z9SSHUserAuthClient.ssh_USERAUTH_PK_OK_keyboard_interactivecCs6|j}|ddt|t|t|dS)z Called back out of self.signData with the signed data. Send the authentication request with the signature. @param signedData: the data signed by the user's private key. @type signedData: L{bytes} rrN)rrrrqrx)r( signedDatarr*r*r+r&s "zSSHUserAuthClient._cbSignedDatacCs ||_dS)z Called back when we are choosing a new password. Simply store the old password for now. @param op: the old password as entered by the user @type op: L{bytes} N)r)r(opr*r*r+r4s zSSHUserAuthClient._setOldPasscCs,|j}d|_|ddt|t|dS)z Called back when we are choosing a new password. Get the old password and send the authentication message with both. @param np: the new password as entered by the user @type np: L{bytes} NrrX)rrr)r(nprr*r*r+r>s zSSHUserAuthClient._setNewPasscCs>tdt|}|D] }|t|d7}q |jt|dS)a Called back when we are finished answering keyboard-interactive questions. Send the info back to the server in a MSG_USERAUTH_INFO_RESPONSE. @param responses: a list of L{bytes} responses @type responses: L{list} rUTF8N)rpackrrencoderrQMSG_USERAUTH_INFO_RESPONSE)r( responsesr<rr*r*r+rJs z#SSHUserAuthClient._cbGenericAnswerscCst|j}||j|S)z Try to authenticate with a public key. Ask the user for a public key; if the user has one, send the request to the server and return True. Otherwise, return False. @rtype: L{bool} )r r getPublicKeyaddBoth_cbGetPublicKeyr(rJr*r*r+r}Xs  z SSHUserAuthClient.auth_publickeycCsjt|tjsd}|dur3||_|j||jjd|d| ddt | t | dSdS)Nzusing key of type {keyType})keyTyperraTF) isinstancerrirrr r6r7typerrrqrx)r(rr*r*r+rds  z!SSHUserAuthClient._cbGetPublicKeycCs$|}|r||j|jdSdS)z Try to authenticate with a password. Ask the user for a password. If the user will return a password, return True. Otherwise, return False. @rtype: L{bool} TF)rr _cbPasswordrrr*r*r+rrs zSSHUserAuthClient.auth_passwordcCs(|jd|dtdtddS)z Try to authenticate with keyboard-interactive authentication. Send the request to the server and return True. @rtype: L{bool} z!authing with keyboard-interactiverrMT)r6r7rrr.r*r*r+auth_keyboard_interactives z+SSHUserAuthClient.auth_keyboard_interactivecCs|ddt|dS)z Called back when the user gives a password. Send the request to the server. @param password: the password the user entered @type password: L{bytes} rraN)rr)r(rr*r*r+rszSSHUserAuthClient._cbPasswordcCs|}|sdS||j|S)am Sign the given data with the given public key. By default, this will call getPrivateKey to get the private key, then sign the data using Key.sign(). This method is factored out so that it can be overridden to use alternate methods, such as a key agent. @param publicKey: The public key object returned from L{getPublicKey} @type publicKey: L{keys.Key} @param signData: the data to be signed by the private key. @type signData: L{bytes} @return: a Deferred that's called back with the signature @rtype: L{defer.Deferred} N) getPrivateKeyrD _cbSignData)r(rrrr*r*r+rszSSHUserAuthClient.signDatacCs ||S)ae Called back when the private key is returned. Sign the data and return the signature. @param privateKey: the private key object @type privateKey: L{keys.Key} @param signData: the data to be signed by the private key. @type signData: L{bytes} @return: the signature @rtype: L{bytes} )sign)r( privateKeyrr*r*r+rs zSSHUserAuthClient._cbSignDatacCsdS)a Return a public key for the user. If no more public keys are available, return L{None}. This implementation always returns L{None}. Override it in a subclass to actually find and return a public key object. @rtype: L{Key} or L{None} Nr*r.r*r*r+rs zSSHUserAuthClient.getPublicKeycC ttS)a Return a L{Deferred} that will be called back with the private key object corresponding to the last public key from getPublicKey(). If the private key is not available, errback on the Deferred. @rtype: L{Deferred} called back with L{Key} r r8NotImplementedErrorr.r*r*r+rs zSSHUserAuthClient.getPrivateKeyNcCr)a Return a L{Deferred} that will be called back with a password. prompt is a string to display for the password, or None for a generic 'user@hostname's password: '. @type prompt: L{bytes}/L{None} @rtype: L{defer.Deferred} r)r(rr*r*r+rs zSSHUserAuthClient.getPasswordcCr)a Returns a L{Deferred} with the responses to the promopts. @param name: The name of the authentication currently in progress. @param instruction: Describes what the authentication wants. @param prompts: A list of (prompt, echo) pairs, where prompt is a string to display and echo is a boolean indicating whether the user's response should be echoed as they type it. r)r(rrrr*r*r+rs z#SSHUserAuthClient.getGenericAnswersr)!rrrrrrrr,rr?rrrrrrrrrrrrr}rrrrrrrrrrr*r*r*r+rFs> 8       r2345=<rMSG_)+rr twisted.conchrrtwisted.conch.sshrrrtwisted.conch.ssh.commonrr twisted.credr twisted.cred.errorr twisted.internetr r twisted.loggerr twisted.pythonrtwisted.python.compatr SSHServicerrrpr[rRMSG_USERAUTH_BANNERrrmessageslistlocalsitemskvprotocolMessagesMSG_USERAUTH_PASSWD_CHANGEREQMSG_USERAUTH_INFO_REQUESTr*r*r*r+sF     .&