Skip to content

Instantly share code, notes, and snippets.

@e000
Created January 30, 2011 21:56
Show Gist options
  • Select an option

  • Save e000/803292 to your computer and use it in GitHub Desktop.

Select an option

Save e000/803292 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from twisted.conch import error, manhole, manhole_ssh, ssh
from twisted.conch.ssh import keys, factory, common
from twisted.cred import checkers, portal, credentials
from twisted.python import failure, log
from zope.interface import implements
from twisted.cred.error import UnauthorizedLogin, UnhandledCredentials
import os.path
class PublicKeyCredentialsChecker:
implements(checkers.ICredentialsChecker)
credentialInterfaces = (credentials.ISSHPrivateKey,)
def __init__(self, authorizedKeys):
for key in authorizedKeys:
if not isinstance(authorizedKeys[key], keys.Key):
authorizedKeys[key] = keys.Key.fromString(authorizedKeys[key])
self.authorizedKeys = authorizedKeys
def requestAvatarId(self, credentials):
if credentials.username in self.authorizedKeys:
userKey = self.authorizedKeys[credentials.username]
if not credentials.blob == userKey.blob():
raise failure.Failure(UnauthorizedLogin("invalid key"))
if not credentials.signature:
return failure.Failure(error.ValidPublicKey())
else:
try:
pubKey = keys.Key.fromString(credentials.blob)
if pubKey.verify(credentials.signature, credentials.sigData):
return credentials.username
except:
log.err()
return failure.Failure(UnauthorizedLogin('error while verifying key'))
return failure.Failure(UnauthorizedLogin("unable to verify key"))
return failure.Failure(UnauthorizedLogin("unable to verify key"))
def generateManholeFactory(namespace, userPubKeys, privateKey):
realm = manhole_ssh.TerminalRealm()
realm.chainedProtocolFactory.protocolFactory = \
lambda _: manhole.ColoredManhole(namespace)
p = portal.Portal(realm)
p.registerChecker(
PublicKeyCredentialsChecker(userPubKeys)
)
f = manhole_ssh.ConchFactory(p)
privateKey = keys.Key.fromString(privateKey)
f.publicKeys = {
'ssh-rsa': privateKey.public()
}
f.privateKeys = {
'ssh-rsa': privateKey
}
return f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment