Home arrow Python arrow Page 3 - SSH with Twisted

Using Public Keys for Authentication - Python

Twisted is a framework for networked applications. In this article, you'll learn how to use the Secure Shell (SSH) with Twisted to accomplish a variety of useful tasks. This article is excerpted from chapter 10 of the book Twisted Network Programming Essentials, written by Abe Fettig (O'Reilly, 2007; ISBN: 0596100329). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

TABLE OF CONTENTS:
  1. SSH with Twisted
  2. Setting Up a Custom SSH Server continued
  3. Using Public Keys for Authentication
  4. Providing an Administrative Python Shell
  5. Running Commands on a Remote Server
By: O'Reilly Media
Rating: starstarstarstarstar / 7
March 06, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- 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

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: