PageRenderTime 36ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/doxi_lib.py

https://bitbucket.org/lazy_dogtown/doxi
Python | 267 lines | 251 code | 9 blank | 7 comment | 7 complexity | 793346a7e557a2a1dd3b77dae9500d00 MD5 | raw file
Possible License(s): Apache-2.0
  1. #-*- coding: utf-8 -*-
  2. #
  3. #
  4. #
  5. # v 0.4.0.0.4 - 2013-07-03
  6. import os, sys, ConfigParser, time, glob, random, hashlib
  7. config = ConfigParser.RawConfigParser()
  8. if os.path.isfile("doxi.conf"):
  9. dc = "doxi.conf"
  10. else:
  11. dc = "../doxi.conf"
  12. config.read(dc)
  13. nginx_conf_path = config.get('global', 'nginx_conf_path').strip()
  14. nginx_bin = config.get('global', 'nginx_bin').strip()
  15. nginx_restart = config.get('global', 'nginx_restart').strip()
  16. doxi_rules_dir = config.get('global', 'doxi_rules_dir' ).strip()
  17. if doxi_rules_dir[0] != "/":
  18. # ncheck for relative/absolute path
  19. doxi_rules_dir = "%s/%s" % (nginx_conf_path, doxi_rules_dir)
  20. rollback_dir = config.get('global', 'rollback_dir').strip()
  21. stats_dir = config.get('global', 'stats_dir').strip()
  22. time_ranges = {
  23. #desig steps name shortcut chart_steps
  24. "h" : (3600, "1hr", "lasthour", 48 ), # hours
  25. "d" : (86400, "24hrs", "lastday", 14 ), # days 86400
  26. "w" : (604800, "7days", "lastweek", 8 ), # weeks 604800
  27. "m" : (2592000, "30days", "lastmonth", 12 ), # months 2592000
  28. "y" : (31536000, "1yr", "lastyear", 5 ), # years
  29. "a" : (3153600000, "All", "all", 0 ), #all # 2592000
  30. }
  31. try:
  32. nx_util_dir = config.get('nx_util', 'nx_util_dir').strip()
  33. nx_util_conf = "%s/nx_util.conf" % nx_util_dir.strip()
  34. except:
  35. print """
  36. ERROR
  37. you need to adjust your doxi.conf; [naxsi-ui] is obsolte,
  38. use [nx_util] instead
  39. see Changelog for v0.4 and doxi.conf.template
  40. """
  41. sys.exit(2)
  42. try:
  43. rep_list_count = int(config.get('dx_report', 'reputation_list_count').strip())
  44. except:
  45. print """
  46. [i] rep_list_count defaults to 3,
  47. see Changelog for v0.4 and doxi.conf.template
  48. """
  49. rep_list_count = 3
  50. # for dx-result
  51. tmpdb=":memory:"
  52. date_stamp = "%s.%s" % (time.strftime("%Y-%d-%m", time.localtime(time.time())), int(time.time()))
  53. date_time = "%s" % (time.strftime("%F - %H:%M", time.localtime(time.time())))
  54. tcreate = "create table if not exists tmptbl (id INTEGER PRIMARY KEY AUTOINCREMENT, count INTEGER, sid INTEGER)"
  55. def parse_new_doxi_rules():
  56. new_sigs = {}
  57. known_sigs = "%s/know_sigs" % stats_dir
  58. if not os.path.isdir(known_sigs):
  59. try:
  60. os.makedirs(known_sigs)
  61. except:
  62. return(1000)
  63. doxi_rulesets = glob.glob("doxi-rules/*.rules")
  64. global_sigs = {}
  65. for ruleset in doxi_rulesets:
  66. print "checking %s" % ruleset
  67. sigs = parse_rulesfile(ruleset)
  68. for sig in sigs:
  69. global_sigs[sig] = sigs[sig]
  70. for sid, stro in sorted(global_sigs.iteritems()):
  71. # print sid
  72. # print stro
  73. # print global_sigs[sid]
  74. sid_path = "%s/%s" % (known_sigs, sid)
  75. if not os.path.isfile(sid_path):
  76. new_sigs[sid] = stro
  77. f = open(sid_path, "a")
  78. f.write("""#
  79. # sid : %s
  80. # created : %s
  81. %s
  82. """ % (sid, date_stamp, stro[4]))
  83. f.close()
  84. else:
  85. #print "[i] %10s is know" % sid
  86. continue
  87. if len(new_sigs) == 0:
  88. return(0)
  89. print "[+] new sigs:"
  90. for sig in sorted(new_sigs):
  91. print "%10s :: %-20s :: %s" % (sig, new_sigs[sig][5], new_sigs[sig][0])
  92. def parse_doxi_rules():
  93. doxi_rulesets = glob.glob("%s/*.rules" % doxi_rules_dir)
  94. global_sigs = {}
  95. for ruleset in doxi_rulesets:
  96. #print "checking %s" % ruleset
  97. sigs = parse_rulesfile(ruleset)
  98. for sig in sigs:
  99. global_sigs[sig] = sigs[sig]
  100. return(global_sigs)
  101. def random_string(l=128):
  102. """
  103. takes l(length) of random_chars to return;
  104. min(l) = 16
  105. max(l) = 4096
  106. """
  107. ascii="""qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDGHJKLYXCVBNM,.-#+ß0987654321;:_'\ /"*?=)(/&%$§!\}][{@<>|"""
  108. w = ""
  109. for x in range(1,100):
  110. y = (random.sample(ascii, 12))
  111. random.shuffle((y))
  112. w += "".join(y)
  113. if len(w) < 1000:
  114. w = ascii
  115. for g in range(1,100):
  116. w += random.shuffle("".join(w))
  117. try:
  118. int(l)
  119. except:
  120. l = 16
  121. if l < 16:
  122. l = 16
  123. elif l > 4096:
  124. l = 1024
  125. r = hashlib.sha512(w).hexdigest()
  126. while len(r) < (10 * l):
  127. random.shuffle(r.split())
  128. r += "".join(r)
  129. return("".join(random.sample(r,l)))
  130. def parse_rulesfile(rfile):
  131. """
  132. parses a given rulefile and returns a sorted dictionary with
  133. sigs = {
  134. ...
  135. idx : (msg, searchstring, mz, score, full_line_from_file, ruleset),
  136. ...
  137. }
  138. """
  139. if not os.path.isfile(rfile):
  140. return(0)
  141. lc = 0
  142. rc = 0
  143. sigs = {}
  144. for line in open(rfile, "r").xreadlines():
  145. msg = mz = score = rid = 0
  146. line = line.strip()
  147. #print line
  148. lc += 1
  149. if len(line) < 15:
  150. continue
  151. if line[0] == "#":
  152. continue
  153. if not line.find("MainRule") > -1:
  154. continue
  155. try:
  156. rid = line.split("id:")[1].split()[0].replace("\"", "").replace(";", "").strip()
  157. except:
  158. continue
  159. try:
  160. int(rid)
  161. except:
  162. print "[-] ERROR - ID should be an integer, found: %s" % rid
  163. continue
  164. try:
  165. msg = line.split("msg:")[1].split("\"")[0].strip()
  166. except:
  167. print "[-] ERROR - no msg: - identifier found"
  168. continue
  169. if line.find("str:") > -1:
  170. srchp = "str:"
  171. elif line.find("rx:") > -1:
  172. srchp = "rx:"
  173. else:
  174. continue
  175. try:
  176. srch = "%s%s" % (srchp, line.split(srchp)[1].split("\"")[0].strip())
  177. except:
  178. print "[-] ERROR - no str:/rx: - identifier found"
  179. continue
  180. try:
  181. mz = line.split("mz:")[1].split("\"")[0].strip()
  182. except:
  183. print "[-] ERROR - no mz: - identifier found"
  184. continue
  185. try:
  186. score = line.split("s:")[1].split("\"")[0].strip()
  187. except:
  188. print "[-] ERROR - no score: - identifier found"
  189. continue
  190. sigs[rid] = (msg, srch, mz, score, line, rfile.split("/")[-1])
  191. #print rid
  192. return(sigs)
  193. #MainRule "string:/sftp-config.json" "msg:DN WEB_SERVER SFTP-config-file access" "mz:URL|BODY" "s:$ATTACK:8,$UWA:8" id:42000084 ;