Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from twisted.conch import avatar, recvline
- from twisted.conch.interfaces import IConchUser, ISession
- from twisted.conch.ssh import factory, keys, session
- from twisted.conch.insults import insults
- from twisted.cred import portal, checkers
- from twisted.internet import reactor
- from zope.interface import implements
- import subprocess
- import sys
- class SysUser():
- def __init__(self):
- self.tunnel_route = []
- self.aps = []
- self.aps.append(ProEntity(0,b'100.20.20.8',8009,'root','thisispass'))
- self.aps.append(ProEntity(1,b'55.20.10.8',1080,'mama','123456'))
- self.aps.append(ProEntity(2,b'22.22.22.22',5665,'toko','lydsas232'))
- self.id_val = 10
- class ProEntity():
- def __init__(self,pid,ip_address,port,user,password):
- self.pid = pid
- self.ip_address = ip_address
- self.port = port
- self.user = user
- self.password = password
- def __repr__(self):
- #return(b'ID:'+self.pid +b'| IP:'+self.ip_address + b'| PORT:'+self.port)
- return('ID:%d| IP:%s| PORT:%d|USER:%s |PASS:%s\n' %
- (self.pid,self.ip_address,self.port,self.user,self.password))
- class SSHDemoProtocol(recvline.HistoricRecvLine):
- def __init__(self, user):
- self.user = user
- self.data = SysUser()
- clist = {
- b'add': b'Add a new proxy to database. format - add [ip_address]:[port]:[user]:[pass]',
- b'remove': b'Removes a proxy from database. format - remove [proxy_id] ',
- b'ctunnel': b'Specifies the current listed. format - ctunnel',
- b'tunnel': b'Allows to set the tunnel to a new route. use - tunnel [proxy_id]:...:[proxy_id]',
- b'list': b'Lists the existing proxy database. format - list',
- b'help': b'lists all commands. format - help',
- None: b" is an unknown command. type 'help' to get command list"
- }
- def connectionMade(self):
- global all_users
- all_users[self.user.username] = SysUser()
- recvline.HistoricRecvLine.connectionMade(self)
- self.terminal.write(b'Hey %s. This is setup interface for the proxy. type help to view available commands\n' % (self.user.username))
- self.terminal.nextLine()
- def lineReceived(self, line):
- global all_users
- user_data = all_users[self.user.username]
- command = line.split(b' ', 1)[0]
- if command in self.clist:
- #try:
- if command == b'add':
- self.add_p(line)
- if command == b'remove':
- self.remove(line)
- if command == b'ctunnel':
- self.ctunnel(line)
- if command == b'tunnel':
- self.tunnel(line)
- if command == b'list':
- self.list(line)
- if command == b'help':
- self.help(line)
- #except:
- # self.terminal.write(b"An error has accourd during the handling of your command. try again")
- # self.terminal.nextLine()
- elif command == b'':
- pass
- else:
- self.terminal.write(command + self.clist[None])
- self.terminal.nextLine()
- def add_p(self,line):
- try:
- indata = line.split(b' ', 1)[1]
- ip_address = indata.split(b':')[0]
- port = int(indata.split(b':')[1])
- user = indata.split(b':')[2]
- password = indata.split(b':')[3]
- except:
- self.terminal.write(b"command was incorrect - either port/ip/user/pass were wrong, or format was wrong")
- self.terminal.nextLine()
- return()
- self.data.aps.append(ProEntity(self.data.id_val,ip_address,port,user,password))
- self.terminal.write(b"proxy was added with id %d" % (self.data.id_val))
- self.terminal.nextLine()
- self.data.id_val+=1
- def remove(self,line):
- indata = line.split(b' ', 1)
- if len(indata) != 2:
- self.terminal.write(b"An incorrect amount of arguments has been specified")
- self.terminal.nextLine()
- return()
- try:
- pro_id = int(indata[1])
- except:
- self.terminal.write(indata[1] + b" isn't a recognized proxy server id in the system. try 'list'.")
- self.terminal.nextLine()
- return()
- for pro in self.data.aps:
- if pro.pid == pro_id:
- self.data.aps.remove(pro)
- return()
- self.terminal.write(indata[1] + b" isn't a recognized proxy server id in the system. try 'list'.")
- self.terminal.nextLine()
- return()
- def ctunnel(self,line):
- self.terminal.write(str.encode(str(self.data.tunnel_route)))
- self.terminal.nextLine()
- def tunnel(self,line):
- self.data.tunnel_route = []
- id_arr = line.split(b' ', 1)
- if len(id_arr) != 2:
- self.terminal.write(b"An incorrect amount of arguments has been specified")
- self.terminal.nextLine()
- return()
- id_arr = id_arr[1].split(b':')
- for pro_id in id_arr:
- pro_id = int(pro_id)
- for pro in self.data.aps:
- if pro.pid == pro_id:
- self.data.tunnel_route.append(pro)
- if len(id_arr)>len(self.data.tunnel_route):
- self.terminal.write(b"An unknown proxy ID has been specified")
- self.terminal.nextLine()
- self.data.tunnel_route = []
- return()
- self.terminal.write(b"Tunnel is being created")
- self.terminal.nextLine()
- self.do_connections(self.data.tunnel_route)
- self.terminal.write(b"Tunnel is done! proxy in to %s to use the tunnel" %(self.data.tunnel_route[0].ip_address))
- self.terminal.nextLine()
- def do_connections(self,tunnel_route):
- HOST="www.example.org"
- # Ports are handled in ~/.ssh/config since we use OpenSSH
- COMMAND="uname -a"
- ssh = subprocess.Popen(["ssh", "admin@reyysport.com", "-D 55557"],
- shell=False,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE)
- result = ssh.stdout.readlines()
- if result == []:
- error = ssh.stderr.readlines()
- print >>sys.stderr, "ERROR: %s" % error
- else:
- print result
- #ssh -v -2 -C -D 55557 -L 55556:127.0.0.1:55556 -L 55555:127.0.0.1:55555 admin@reyysport.com
- #subprocess.call('ssh user1@middle.example.org -L 8001:localhost:8002 -t ssh -D 8002 user2@server.example.org')
- return()
- def list(self,line):
- self.terminal.write(str.encode(str(self.data.aps)))
- self.terminal.nextLine()
- def help(self,line):
- for command in self.clist:
- if command is not None:
- self.terminal.write(command + b' : ' + self.clist[command])
- self.terminal.nextLine()
- class SSHDemoAvatar(avatar.ConchUser):
- implements(ISession)
- def __init__(self, username):
- avatar.ConchUser.__init__(self)
- self.username = username
- self.channelLookup.update({'session': session.SSHSession})
- def openShell(self, protocol):
- serverProtocol = insults.ServerProtocol(SSHDemoProtocol, self)
- serverProtocol.makeConnection(protocol)
- protocol.makeConnection(session.wrapProtocol(serverProtocol))
- def getPty(self, terminal, windowSize, attrs):
- return None
- def execCommand(self, protocol, cmd):
- raise NotImplementedError()
- def closed(self):
- pass
- def __repr__(self):
- return(self.username)
- class SSHDemoRealm(object):
- implements(portal.IRealm)
- def requestAvatar(self, avatarId, mind, *interfaces):
- if IConchUser in interfaces:
- return interfaces[0], SSHDemoAvatar(avatarId), lambda: None
- else:
- raise NotImplementedError("No supported interfaces found.")
- def getRSAKeys():
- with open('/home/idan/.ssh/id_rsa') as privateBlobFile:
- privateBlob = privateBlobFile.read()
- privateKey = keys.Key.fromString(data=privateBlob)
- with open('/home/idan/.ssh/id_rsa.pub') as publicBlobFile:
- publicBlob = publicBlobFile.read()
- publicKey = keys.Key.fromString(data=publicBlob)
- return publicKey, privateKey
- class ProxFactory(factory.SSHFactory):
- portal = portal.Portal(SSHDemoRealm())
- if __name__ == "__main__":
- sshFactory = ProxFactory()
- all_users = {}
- users = {'admin': 'aaa', 'guest': 'bbb'}
- sshFactory.portal.registerChecker(
- checkers.InMemoryUsernamePasswordDatabaseDontUse(**users))
- pubKey, privKey = getRSAKeys()
- sshFactory.publicKeys = {'ssh-rsa': pubKey}
- sshFactory.privateKeys = {'ssh-rsa': privKey}
- reactor.listenTCP(22222, sshFactory)
- reactor.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement