Python
  Home arrow Python arrow Page 3 - SSH with Twisted
The Best Selling PC Migration Utility.
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
IBM Rational Software Development Conference
 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? 
PYTHON

SSH with Twisted
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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

    Virtual Tradeshows by Ziff Davis Enterprise - A Unique Opportunity to Connect with IT Experts, Access Information, and Gain Insight on today's Technology

    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
    distributions (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 distributed 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 theadmin user in theauthorizedKeysdictionary. 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. PublicKeyCredentialsCheckeraccepts credentials implementingISSHPrivateKey, which have the attributesusername,blob,signature, andsigData. To verify the key,PublicKeyCredentialsCheckergoes through three tests. First, it makes sure it has a public key on file for the userusername. Next, it verifies that the public key provided inblobmatches 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.requestAvatarraises the special exceptiontwisted.conch.error. ValidPublicKey. The SSH server will understand the meaning of this exception and ask the client for the missing signature.

    Finally, thePublicKeyCredentialsCheckeruses the functiontwisted.conch.ssh.keys.verifySignatureto check whether the data insignaturereally is the data insigDatasigned with the user’s private key. IfverifySignaturereturns a true value, authentication is successful, andrequestAvatarIdreturnsusernameas 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


       · This article is an excerpt from the book "Twisted Network Programming Essentials,"...
     

    Buy this book now. This article is excerpted from chapter 10 of the book Twisted Network Programming Essentials, written by Abe Fettig (O'Reilly, 2007; ISBN: 0596100329). Check it out today at your favorite bookstore. Buy this book now.

       

    PYTHON ARTICLES

    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along
    - Python Operators
    - Bluetooth Programming in Python: Network Pro...
    - Python Sets
    - Python Conditionals, Lists, Dictionaries, an...
    - Python: Input and Variables
    - Introduction to Python Programming
    - Mobile Programming in Python using PyS60: Ge...
    - Bluetooth Programming using Python
    - Finishing the PyMailGUI Client: User Help To...

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway