def getPublicKey(self): try: # For use with recent versions of Conch return self.__getKey().public().blob() except AttributeError: # For old versions return keys.getPublicKeyString(data=self.auth_data.public_key)
def _testKey(self, pubData, privData, keyType): privKey = keys.getPrivateKeyObject(data = privData) pubStr = keys.getPublicKeyString(data = pubData) pubKey = keys.getPublicKeyObject(pubStr) self._testKeySignVerify(privKey, pubKey) self._testKeyFromString(privKey, pubKey, privData, pubData) self._testGenerateKey(privKey, pubKey, privData, pubData, keyType)
def checkKey(self, credentials): unittest.assertEquals(credentials.username, 'testuser', 'bad username') unittest.assertEquals( credentials.blob, keys.getPublicKeyString(data=publicDSA_openssh)) return 1
def _saveKey(key, options): if not options['filename']: kind = keys.objectType(key) kind = {'ssh-rsa':'rsa','ssh-dss':'dsa'}[kind] filename = os.path.expanduser('~/.ssh/id_%s'%kind) options['filename'] = raw_input('Enter file in which to save the key (%s): '%filename).strip() or filename if os.path.exists(options['filename']): print '%s already exists.' % options['filename'] yn = raw_input('Overwrite (y/n)? ') if yn[0].lower() != 'y': sys.exit() if not options['pass']: while 1: p1 = getpass.getpass('Enter passphrase (empty for no passphrase): ') p2 = getpass.getpass('Enter same passphrase again: ') if p1 == p2: break print 'Passphrases do not match. Try again.' options['pass'] = p1 comment = '%s@%s' % (getpass.getuser(), socket.gethostname()) open(options['filename'], 'w').write( keys.makePrivateKeyString(key, passphrase=options['pass'])) os.chmod(options['filename'], 33152) open(options['filename']+'.pub', 'w').write( keys.makePublicKeyString(key, comment = comment)) pubKey = keys.getPublicKeyString(data=keys.makePublicKeyString(key, comment=comment)) print 'Your identification has been saved in %s' % options['filename'] print 'Your public key has been saved in %s.pub' % options['filename'] print 'The key fingerprint is:' print ':'.join(['%02x' % ord(x) for x in md5.new(pubKey).digest()])
def _testKey(self, pubData, privData, keyType): privKey = keys.getPrivateKeyObject(data=privData) pubStr = keys.getPublicKeyString(data=pubData) pubKey = keys.getPublicKeyObject(pubStr) self._testKeySignVerify(privKey, pubKey) self._testKeyFromString(privKey, pubKey, privData, pubData) self._testGenerateKey(privKey, pubKey, privData, pubData, keyType)
class ConchFactory(factory.SSHFactory): publicKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAGEArzJx8OYOnJmzf4tfBEvLi8DVPrJ3/c9k2I/Az64fxjHf9imyRJbixtQhlH9lfNjUIx+4LmrJH5QNRsFporcHDKOTwTTYLh5KmRpslkYHRivcJSkbh/C+BR3utDS555mV' publicKeys = {'ssh-rsa': keys.getPublicKeyString(data=publicKey)} del publicKey privateKey = """-----BEGIN RSA PRIVATE KEY----- MIIByAIBAAJhAK8ycfDmDpyZs3+LXwRLy4vA1T6yd/3PZNiPwM+uH8Yx3/YpskSW 4sbUIZR/ZXzY1CMfuC5qyR+UDUbBaaK3Bwyjk8E02C4eSpkabJZGB0Yr3CUpG4fw vgUd7rQ0ueeZlQIBIwJgbh+1VZfr7WftK5lu7MHtqE1S1vPWZQYE3+VUn8yJADyb Z4fsZaCrzW9lkIqXkE3GIY+ojdhZhkO1gbG0118sIgphwSWKRxK0mvh6ERxKqIt1 xJEJO74EykXZV4oNJ8sjAjEA3J9r2ZghVhGN6V8DnQrTk24Td0E8hU8AcP0FVP+8 PQm/g/aXf2QQkQT+omdHVEJrAjEAy0pL0EBH6EVS98evDCBtQw22OZT52qXlAwZ2 gyTriKFVoqjeEjt3SZKKqXHSApP/AjBLpF99zcJJZRq2abgYlf9lv1chkrWqDHUu DZttmYJeEfiFBBavVYIF1dOlZT0G8jMCMBc7sOSZodFnAiryP+Qg9otSBjJ3bQML pSTqy7c3a2AScC/YyOwkDaICHnnD3XyjMwIxALRzl0tQEKMXs6hH8ToUdlLROCrP EhQ0wahUTCk1gKA4uPD6TMTChavbh4K63OvbKg== -----END RSA PRIVATE KEY-----""" privateKeys = {'ssh-rsa': keys.getPrivateKeyObject(data=privateKey)} del privateKey def __init__(self, portal): self.portal = portal def buildProtocol(self, addr): if addr.host not in self.allowedIP: raise "Unauthorized" return factory.SSHFactory.buildProtocol(self, addr)
def getPublicKey(self): path = os.path.expanduser('~/.ssh/id_dsa') # this works with rsa too # just change the name here and in getPrivateKey if not os.path.exists(path) or self.lastPublicKey: # the file doesn't exist, or we've tried a public key return return keys.getPublicKeyString(path+'.pub')
def getPublicKeys(self): ks = {} for file in os.listdir(self.dataRoot): if file[:9] == 'ssh_host_' and file[-8:]=='_key.pub': try: k = keys.getPublicKeyString(self.dataRoot+'/'+file) t = common.getNS(k)[0] ks[t] = k except Exception, e: log.msg('bad public key file %s: %s' % (file,e))
def getPublicKeys(self): ks = {} for file in os.listdir(self.dataRoot): if file[:9] == 'ssh_host_' and file[-8:] == '_key.pub': try: k = keys.getPublicKeyString(self.dataRoot + '/' + file) t = common.getNS(k)[0] ks[t] = k except Exception, e: log.msg('bad public key file %s: %s' % (file, e))
def _testKeyFromString(self, privKey, pubKey, privData, pubData): keyType = keys.objectType(privKey) privFS = keys.getPrivateKeyObject(data = privData) pubFS = keys.getPublicKeyObject(keys.getPublicKeyString(data=pubData)) for k in privFS.keydata: if getattr(privFS, k) != getattr(privKey, k): self.fail('getting %s private key from string failed' % keyType) for k in pubFS.keydata: if hasattr(pubFS, k): if getattr(pubFS, k) != getattr(pubKey, k): self.fail('getting %s public key from string failed' % keyType)
def _testKeyFromString(self, privKey, pubKey, privData, pubData): keyType = keys.objectType(privKey) privFS = keys.getPrivateKeyObject(data=privData) pubFS = keys.getPublicKeyObject(keys.getPublicKeyString(data=pubData)) for k in privFS.keydata: if getattr(privFS, k) != getattr(privKey, k): self.fail('getting %s private key from string failed' % keyType) for k in pubFS.keydata: if hasattr(pubFS, k): if getattr(pubFS, k) != getattr(pubKey, k): self.fail('getting %s public key from string failed' % keyType)
def factoryPreinit(self): BasePlugin.factoryPreinit(self) sshdir = self.cb.datapaths['keys.ssh'] keypath = '%s%s%s' % (sshdir, os.sep, self.mainRegistryValue('keys.rsaKeyFile')) if not os.path.exists(keypath): raise Exception, 'The SSH private key is missing' pubpath = '%s.pub' % keypath if not os.path.exists(pubpath): raise Exception, 'The SSH public key is missing' self.FactoryClass.publicKeys = {'ssh-rsa':keys.getPublicKeyString(filename=pubpath)} self.FactoryClass.privateKeys = {'ssh-rsa':keys.getPrivateKeyObject(filename=keypath)}
def getPublicKey(self): files = [x for x in options.identitys if x not in self.usedFiles] if not files: return None file = files[0] log.msg(file) self.usedFiles.append(file) file = os.path.expanduser(file) file += '.pub' if not os.path.exists(file): return try: return keys.getPublicKeyString(file) except: return self.getPublicKey() # try again
def printFingerprint(options): if not options['filename']: filename = os.path.expanduser('~/.ssh/id_rsa') options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename) if os.path.exists(options['filename']+'.pub'): options['filename'] += '.pub' try: string = keys.getPublicKeyString(options['filename']) obj = keys.getPublicKeyObject(string) print '%s %s %s' % ( obj.size()+1, ':'.join(['%02x' % ord(x) for x in md5.new(string).digest()]), os.path.basename(options['filename'])) except: sys.exit('bad key')
class ExampleFactory(factory.SSHFactory): publicKeys = {'ssh-rsa': keys.getPublicKeyString(data=publicKey)} privateKeys = {'ssh-rsa': keys.getPrivateKeyObject(data=privateKey)} services = { 'ssh-userauth': userauth.SSHUserAuthServer, 'ssh-connection': connection.SSHConnection } def buildProtocol(self, addr): t = mySSHServerTransport() t.supportedPublicKeys = self.privateKeys.keys() if not self.primes: ske = t.supportedKeyExchanges[:] ske.remove('diffie-hellman-group-exchange-sha1') t.supportedKeyExchanges = ske t.factory = self return t
class CoretFactory(factory.SSHFactory): publicKeys = {'ssh-rsa': keys.getPublicKeyString(data=publicKey)} privateKeys = {'ssh-rsa': keys.getPrivateKeyObject(data=privateKey)} services = {'ssh-userauth': userauth.SSHUserAuthServer, 'ssh-connection': connection.SSHConnection} def buildProtocol(self, addr): t = transport.SSHServerTransport() # # Fix for BUG 1463701 "NMap recognizes Kojoney as a Honeypot" # t.ourVersionString = FAKE_SSH_SERVER_VERSION t.supportedPublicKeys = self.privateKeys.keys() if not self.primes: ske = t.supportedKeyExchanges[:] ske.remove('diffie-hellman-group-exchange-sha1') t.supportedKeyExchanges = ske t.factory = self return t
def factoryPreinit(self): BasePlugin.factoryPreinit(self) sshdir = self.cb.datapaths['keys.ssh'] keypath = '%s%s%s' % (sshdir, os.sep, self.mainRegistryValue('keys.rsaKeyFile')) if not os.path.exists(keypath): raise Exception, 'The SSH private key is missing' pubpath = '%s.pub' % keypath if not os.path.exists(pubpath): raise Exception, 'The SSH public key is missing' self.FactoryClass.publicKeys = { 'ssh-rsa': keys.getPublicKeyString(filename=pubpath) } self.FactoryClass.privateKeys = { 'ssh-rsa': keys.getPrivateKeyObject(filename=keypath) }
def getPublicKey(self): if self.keyAgent: blob = self.keyAgent.getPublicKey() if blob: return blob files = [x for x in self.options.identitys if x not in self.usedFiles] log.msg(str(self.options.identitys)) log.msg(str(files)) if not files: return None file = files[0] log.msg(file) self.usedFiles.append(file) file = os.path.expanduser(file) file += '.pub' if not os.path.exists(file): return self.getPublicKey() # try again try: return keys.getPublicKeyString(file) except: return self.getPublicKey() # try again
def createVFSApplication(vfsRoot): application = service.Application('FAKESFTP') p = portal.Portal(Realm(vfsRoot)) p.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(admin='admin')) p.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) # sftp # http://igloo.its.unimelb.edu.au/Webmail/tips/msg00495.html # ssh-keygen -q -b 1024 -t dsa -f ssh_host_dsa_key pubkey = keys.getPublicKeyString( '../sshkeys/ssh_host_dsa_key.pub') privkey = keys.getPrivateKeyObject( '../sshkeys/ssh_host_dsa_key') class SSHFactory(factory.SSHFactory): publicKeys = {common.getNS(pubkey)[0]: pubkey} privateKeys = {keys.objectType(privkey): privkey} sftpf = SSHFactory() sftpf.portal = p internet.TCPServer( int( 2222 ), sftpf, ).setServiceParent(application) # ftp f = twisted.protocols.ftp.FTPFactory() f.portal = p f.protocol = twisted.protocols.ftp.FTP internet.TCPServer( 2221, f ).setServiceParent(application) return application
def checkKey(self, credentials): return credentials.username == "user" and keys.getPublicKeyString(data=publicKey) == credentials.blob
rsaKey = RSA.generate(KEY_LENGTH, common.entropy.get_bytes) publicKeyString = keys.makePublicKeyString(rsaKey) privateKeyString = keys.makePrivateKeyString(rsaKey) # save keys for next time file(‘public.key’, ‘w+b’).write(publicKeyString) file(‘private.key’, ‘w+b’).write(privateKeyString) print "done." else: publicKeyString = file(‘public.key’).read() privateKeyString = file(‘private.key’).read() return publicKeyString, privateKeyString if __name__ == "__main__": sshFactory = factory.SSHFactory() sshFactory.portal = portal.Portal(SSHDemoRealm()) users = {‘admin’: ‘aaa’, ‘guest’: ‘bbb’} sshFactory.portal.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(**users)) 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() {mospagebreak title=Setting Up a Custom SSH Server continued}
def getPublicKey(self): return keys.getPublicKeyString(data=publicDSA_openssh)
def verifyHostKey(self, key, fp): unittest.assertEquals(key, keys.getPublicKeyString(data = publicRSA_openssh)) unittest.assertEquals(fp,'3d:13:5f:cb:c9:79:8a:93:06:27:65:bc:3d:0b:8f:af') return defer.succeed(1)
publicKeyString = keys.makePublicKeyString(rsaKey) privateKeyString = keys.makePrivateKeyString(rsaKey) # save keys for next time file('public.key', 'w+b').write(publicKeyString) file('private.key', 'w+b').write(privateKeyString) print "done." else: publicKeyString = file('public.key').read() privateKeyString = file('private.key').read() return publicKeyString, privateKeyString if __name__ == "__main__": sshFactory = factory.SSHFactory() sshFactory.portal = portal.Portal(SSHDemoRealm()) users = {'admin': 'aaa', 'guest': 'bbb'} sshFactory.portal.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(**users)) 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()
def verifyHostKey(self, key, fp): unittest.assertEquals( key, keys.getPublicKeyString(data=publicRSA_openssh)) unittest.assertEquals( fp, '3d:13:5f:cb:c9:79:8a:93:06:27:65:bc:3d:0b:8f:af') return defer.succeed(1)
def getPublicKeys(self): return { 'ssh-rsa': keys.getPublicKeyString(data=publicRSA_openssh), 'ssh-dss': keys.getPublicKeyString(data=publicDSA_openssh) }
def getPublicKeys(self): return { "ssh-rsa": keys.getPublicKeyString(data=publicRSA_openssh), "ssh-dss": keys.getPublicKeyString(data=publicDSA_openssh), }
def checkKey(self, credentials): return credentials.username == 'user' and \ keys.getPublicKeyString(data=publicKey) == credentials.blob
def getPublicKey(self): return keys.getPublicKeyString('dsa_test.pub')
KEY_LENGTH = 1024 rsaKey = RSA.generate(KEY_LENGTH, common.entropy.get_bytes) print rsaKey publicKeyString = keys.makePublicKeyString(rsaKey) privateKeyString = keys.makePrivateKeyString(rsaKey) # save keys for next time file('public.key', 'w+b').write(publicKeyString) file('private.key', 'w+b').write(privateKeyString) print "done." else: publicKeyString = file('public.key').read() privateKeyString = file('private.key').read() return publicKeyString, privateKeyString if __name__ == "__main__": sshFactory = factory.SSHFactory() sshFactory.portal = portal.Portal(SSHDemoRealm()) users = {'admin': 'aaa', 'guest': 'bbb'} sshFactory.portal.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(**users)) 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()
def checkKey(self, credentials): unittest.assertEquals(credentials.username, 'testuser', 'bad username') unittest.assertEquals(credentials.blob, keys.getPublicKeyString(data=publicDSA_openssh)) return 1
def checkKey(self, credentials): global theTest theTest.assertEquals(credentials.username, 'testuser', 'bad username') theTest.assertEquals(credentials.blob, keys.getPublicKeyString('dsa_test.pub'), 'bad public key') return 1
def getPublicKeys(self): return { 'ssh-rsa':keys.getPublicKeyString(data=publicRSA_openssh), 'ssh-dss':keys.getPublicKeyString(data=publicDSA_openssh) }