Python
  Home arrow Python arrow Page 3 - SSH with Twisted
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PYTHON

SSH with Twisted
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 6
    2008-03-06


    Table of Contents:
  • SSH with Twisted
  • Setting Up a Custom SSH Server continued
  • Using Public Keys for Authentication
  • Providing an Administrative Python Shell
  • Running Commands on a Remote Server

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    SSH with Twisted - Using Public Keys for Authentication
    ( Page 3 of 5 )

    The SSH server in Example 10-1 used usernames and passwords for authentication. But heavy SSH users will tell you that one of the nicest features of SSH is its support for key-based authentication. With key-based authentication, the server is given a copy of a user’s private key. When the user tries to log in, the server asks her to prove her identity by signing some data with her private key. The server then checks the signed data against its copy of the user’s public key.

    In practice, using public keys for authentication is nice, because it saves the user from having to manage a lot of passwords. A user can use the same key for multiple servers. She can choose to password-protect her key for extra security, or she can use a key with no password for a completely transparent login process.

    This lab shows you how to set up a Twisted SSH server to use public key authentication. It uses the same server code as Example 10-1, but with a new authentication backend.

    How Do I Do That?

    Store a public key for each user. Write a credentials checker that accepts credentials implementing twisted.conch.credentials.ISSHPrivateKey. Verify the user’s credentials by checking to make sure that his public key matches the key you have stored, and that his signature proves that the user possesses the matching private key. Example 10-2 shows how to do this.

    Example 10-2. pubkeyssh.py

    from sshserver import SSHDemoRealm, getRSAKeys
    from twisted.conch import credentials, error from twisted.conch.ssh import keys, factory from twisted.cred import checkers, portal from twisted.python import failure
    from zope.interface import implements
    import base64

    class PublicKeyCredentialsChecker:
        implements(checkers.ICredentialsChecker)
        credentialInterfaces = (credentials.ISSHPrivateKey,)

        def __init__(self, authorizedKeys) :
            self.authorizedKeys = authorizedKeys

        def requestAvatarId(self, credentials):
           
    if self.authorizedKeys.has_key(credentials.username):
                userKey = self.authorizedKeys[credentials.username]
                if not credentials.blob == base64.decodestring(userKey):
                   
    raise failure.failure(
                       error.ConchError("I don't recognize that key"))
                if not credentials.signature:
                   
    return failure.Failure(error.ValidPublicKey())
                pubKey = keys.getPublicKeyObject(data=credentials.blob)
                if keys.verifySignature(pubKey, credentials.signature,
                          
    credentials.sigData):
                    return credentials.username
                else:
                    return failure.Failure(
                        error.ConchError("Incorrect signature"))
            else:
                return failure.Failure(error.ConchError("No such user"))

    if __name__ == "__main__":
        sshFactory = factory.SSHFactory()
        sshFactory.portal = portal.Portal(SSHDemoRealm())
        authorizedKeys = {
        "admin":

    "AAAAB3NzaC1yc2EAAAABIwAAAIEAxIfv4ICpuKFaGA/ r2cJsQjUZsZ4VAsA1c9TXPYEc2Ue1lp78lq0rm/ nQTlK9lg+YEbRxCPcgymaz60cjGspqqoQ35qPiwJ4xg VUeYKfxs+ZSl3YGIODVfsqLYxLl33b6yCnE0bfBjEPmb9P OkL2TA1owlBfTL2+t+Hbx+clDCwE="
       
    }
        sshFactory.portal.registerChecker(
            PublicKeyCredentialsChecker(authorizedKeys))

        pubKeyString, privKeyString = getRSAKeys()
        sshFactory.publicKeys = {
            'ssh-rsa': keys.getPublicKeyString(data=pubKeyString)}
        sshFactory.privateKeys = {
            'ssh-rsa': keys.getPrivateKeyObject(data=privKeyString)}

    from twisted.internet import reactor reactor.listenTCP(2222, sshFactory) reactor.run()

    To test this example, you’ll need to generate a public key, if you don’t have one already. The OpenSSH SSH implementation that comes with most Linux
    distribu tions (and also with Mac OS X) includes a command-line utility named ssh-keygen that you can use to generate a new private/public key pair:

      $ ssh-keygen -t rsa
      Generating public/private rsa key pair.
      Enter file in which to save the key (/home/abe/.ssh/id_rsa):
      Enter passphrase (empty for no passphrase):
      Enter same passphrase again:
      Your identification has been saved in /home/abe/.ssh/id_rsa.
      Your public key has been saved in /home/abe/.ssh/id_rsa.pub.
      The key fingerprint is: 
     6b:13:3a:6e:c3:76:50:c7:39:c2:e0:8b:06:68:b4:11 abe@sparky

    Windows users can generate keys with PuTTYgen, which is distrib uted along with the popular free PuTTY SSH client (http://www. chiark.greenend.org.uk/~sgtatham/putty/download.html).

    Once you’ve generated a key, you can get the public key from the file ~/.ssh/id_rsa.pub. Edit Example 10-2 to use your public key for the admin user in the authorizedKeys dictionary. Then run pubkeyssh.py to start the server on port 2222. You should log right in without being prompted for a password:

      $ ssh admin@localhost -p 2222

      >>> Welcome to my test SSH server.
      Commands: clear echo help quit whoami
      $

    If you try to log in as a user who doesn’t possess the matching private key, you’ll be denied access:

      $ ssh admin@localhost -p 2222
      Permission denied (publickey).

    How Does That Work?

    Example 10-2 reuses most of the SSH server classes from Example 10-1. To support public key authentication, it uses a new credentials checker class named PublicKeyCredentialsChecker. PublicKeyCredentialsChecker accepts credentials imple menting ISSHPrivateKey , which have the attributes username , blob , signature , and sigData . To verify the key, PublicKeyCredentialsChecker goes through three tests. First, it makes sure it has a public key on file for the user username . Next, it verifies that the public key provided in blob matches the public key it has on file for that user.

    It’s possible that the user may have provided just the public key at this point, but not a signed token. If the public key was valid, but no signature was provided, PublicKeyCredentialsChecker.requestAvatar raises the special exception twisted.conch.error. ValidPublicKey . The SSH server will understand the meaning of this exception and ask the client for the missing signature.

    Finally, the PublicKeyCredentialsChecker uses the function twisted.conch.ssh.keys.verifySignature to check whether the data in signature really is the data in sigData signed with the user’s private key. If verifySignature returns a true value, authentication is successful, and requestAvatarId returns username as the avatar ID.

    You can support both username/password and key-based authentication in an SSH server. Just register both credentials checkers with your portal.



     
     
    >>> More Python Articles          >>> More By O'Reilly Media
     

       

    PYTHON ARTICLES

    - Tuples and Other Python Object Types
    - The Dictionary Python Object Type
    - String and List Python Object Types
    - Introducing Python Object Types
    - Mobile Programming using PyS60: Advanced UI ...
    - Nested Functions in Python
    - Python Parameters, Functions and Arguments
    - Python Statements and Functions
    - Statements and Iterators in Python
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek