├── .gitignore ├── IncMgmt ├── fe-alert-mon.py ├── fe-report.py ├── feapi.py ├── malware-tickets.py ├── rogueSSID_check.py ├── ticketing.py └── uniqify.py ├── LICENSE ├── Metrics ├── .#Readme.org ├── Readme.md ├── Training │ └── secmentor-stats.py ├── incident_totals_by_category.py ├── redmine_collect-issues.py └── ticket_totals.py ├── README.org ├── Research ├── cif-lookup.sh ├── hybrid-analysis_URL-hash.sh ├── ioc-intel.sh ├── reverselook.sh ├── twitter-checkmydump.py └── twitter-leakedcreds.py └── VulnMgmt ├── README.org ├── Vuln-tickets.py ├── ip_expand.py ├── ov_host-metrics.py ├── prefs.sample └── reconcile_tickets.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | ####################################### 3 | __pycache__/ 4 | *.py[cod] 5 | 6 | # Preferences files 7 | ################### 8 | prefs.cfg 9 | 10 | # OS generated files # 11 | ###################### 12 | .DS_Store 13 | .DS_Store? 14 | ._* 15 | *~ 16 | .Spotlight-V100 17 | .Trashes 18 | ehthumbs.db 19 | Thumbs.db 20 | 21 | 22 | -------------------------------------------------------------------------------- /IncMgmt/fe-alert-mon.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # This monitors the FireEye CMS for new malware alerts and then 4 | # creates tickets in the ServiceNow and Redmine systems 5 | 6 | import os 7 | from feapi import cmsauth 8 | from feapi import cmsalerts 9 | from feapi import genIndex 10 | from feapi import ExtractFEAlerts 11 | import ticketing as tkt 12 | 13 | # Set wd 14 | os.chdir(os.path.expanduser("~") + "/.incmgmt/") 15 | 16 | 17 | # import preferences from file and 18 | # Extract the credentials from the relevant lines 19 | prefs = [] 20 | for line in open('mw-prefs.txt'): 21 | prefs.append(line) 22 | rm_server = prefs[1].rstrip() # redmine server URL 23 | user = prefs[9].rstrip() # Fireeye API user 24 | pwd = prefs[10].rstrip() # Fireee API password 25 | 26 | # Set the proper redmine tracker and category for malware-related alerts. 27 | category = 61 # In my installation, 61 is "Malicious Code" 28 | tracker = 18 # In my installation, 18 is the incident management tracker 29 | 30 | # retrieve an API token from the CMS 31 | print("Authenticating against the CMS as " + user) 32 | token = cmsauth(user, pwd) 33 | 34 | # retrieve alerts from the past hour 35 | data = cmsalerts(token, "1_hour") 36 | 37 | index = genIndex("src", data) 38 | for host in index: 39 | print("\n \n processing: " + host) 40 | dst, hostname, malware, severity, activity, time, alertUrl = \ 41 | ExtractFEAlerts(host, "src", data) 42 | print(host + " was observed communicating with " + dst + " criticality: " + severity + " And type: " + activity + " with malware: " + malware) 43 | # construct the subject/short description. Do this even if a 44 | # ticket is not going to be generated, because lazy 45 | subject = "Malicious code activity detected on " + host 46 | # determine criticality for ticketing systems based on sev 47 | impact, urgency, priority = tkt.criticality(severity) 48 | # construct the body of the ticket from the alert information 49 | body = "Information Security network monintoring devices \ 50 | have identified a potential compromise on the network. \n \ 51 | Please check the following system for the following: \n" \ 52 | "* Affected Host: " + host + "\n" \ 53 | "* Last identified hostname: " + hostname + " (please verify)\n" \ 54 | "* Destination: " + dst + "\n" \ 55 | "* Malware family: [[" + malware + "]] \n" \ 56 | "* Activity Observed: " + activity + "\n" \ 57 | "* Detection Occurred at: " + time + "\n" \ 58 | "* FireEye alert URL: " + alertUrl + " \n \n" 59 | # TODO: add some OS-INT lookups into the ticket 60 | # "Open Source Intel: \n" + intel + "\n" 61 | 62 | old = tkt.CheckRMTickets("Malicious code activity detected on " + host) 63 | if old is not None: 64 | # If there is an active ticket, update it with new info 65 | print("A Redmine ticket exists for this host: " + str(old)) 66 | tkt.UpdateRedmineTicket(old, body) 67 | elif (old is None and (severity.lower() == 'majr' )): 68 | # If there is no existing ticket, create one 69 | print("No ticket exists, generating tickets now\n") 70 | rm_url, rm_issue = tkt.CreateRedmineTicket(subject, priority,\ 71 | body, category, tracker) 72 | # URL for the Wiki page related to the detected malware family 73 | wikipage = rm_server + "/projects/incident_management/wiki/" \ 74 | + malware.translate({ord(i):None for i in '.'}) 75 | sn_ticket, sys_id = tkt.sn_issue(subject, rm_url, impact, \ 76 | urgency, wikipage) 77 | tkt.log(rm_issue, sn_ticket, sys_id) # log the ticket info 78 | elif (old is None and (severity.lower() == 'crit')): 79 | # If there is no existing ticket, create one 80 | print("No ticket exists, generating tickets now\n") 81 | rm_url, rm_issue = tkt.CreateRedmineTicket(subject, priority,\ 82 | body, category, tracker) 83 | # URL for the Wiki page related to the detected malware family 84 | wikipage = rm_server + "/projects/incident_management/wiki/" \ 85 | + malware.translate({ord(i):None for i in '.'}) 86 | sn_ticket, sys_id = tkt.sn_issue(subject, rm_url, impact, \ 87 | urgency, wikipage) 88 | tkt.log(rm_issue, sn_ticket, sys_id) # log the ticket info 89 | else: print("Alert severity below threshold") 90 | -------------------------------------------------------------------------------- /IncMgmt/fe-report.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import os 4 | from feapi import cmsauth 5 | from feapi import cmsreport 6 | 7 | # Set wd 8 | os.chdir(os.path.expanduser("~") + "/.incmgmt/") 9 | 10 | # import preferences from file and 11 | # Extract the credentials from the relevant lines 12 | prefs = [] 13 | for line in open('mw-prefs.txt'): 14 | prefs.append(line) 15 | user = prefs[9].rstrip() 16 | pwd = prefs[10].rstrip() 17 | 18 | # retrieve an API token from the CMS 19 | print("Authenticating against the CMS as " + user) 20 | token = cmsauth(user, pwd) 21 | 22 | # Generate and retrive the report 23 | data = cmsreport(token) 24 | print(data) 25 | -------------------------------------------------------------------------------- /IncMgmt/feapi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # FireEye CMS API interaction modules. These are some commonly used 4 | # functions for interacting with the FireEye CMS system. API access 5 | # must be enabled on the CMS system and you must have created some 6 | # credentials with at least the api_monitor role. Some functions may 7 | # require the api_analyst role 8 | # 9 | # Results are in JSON format. If you want XML, fork this and remove 10 | # the 'Accept' : 'application/json' header from the calls; the API 11 | # will use XML as the default 12 | 13 | # Required modules 14 | import requests 15 | import json 16 | from uniqify import uniqify 17 | 18 | # Global variables TODO: move hard requirements out of this script 19 | baseurl = 'https://sjccms01/wsapis/v1.0.0/' 20 | 21 | 22 | # The FireEye API works by generating a limited API token. This must 23 | # be retrieved by authenticating with the server with valid 24 | # credentials, and then using the token for subsequent requests 25 | 26 | # Authenticate against the CMS server, skipping SSL checking 27 | def cmsauth(user, pwd): 28 | # Authenticate with the CMS and return a temporary API token 29 | authurl = baseurl + 'auth/login' 30 | cms = requests.post(authurl, auth=(user, pwd), verify=False) 31 | if cms.status_code is 200: 32 | print("Authentication successful") 33 | else: 34 | print("Authentication Failure") 35 | token = cms.headers['x-feapi-token'] 36 | return token 37 | 38 | def cmsalerts(token, duration): 39 | import sys 40 | # Query the system for alerts in the specified duration 41 | queryurl = baseurl + 'alerts?info_level=concise&duration=' + duration 42 | alerts = requests.get(queryurl, verify=False, \ 43 | headers = {'X-FeApi-Token' : token, \ 44 | 'Accept' : 'application/json'}) 45 | # Decode the response to text, parse the json and return it 46 | data = json.loads(alerts.content.decode('utf-8')) 47 | # Check to see if there are alerts in the data, exit if not 48 | if data["alertsCount"] == 0: 49 | sys.exit() 50 | else: 51 | return data 52 | 53 | def cmsreport(token): # report_type, report_format, start, end): 54 | # Pulls a report from the CMS, based on time parameters 55 | import datetime as dt 56 | queryurl = baseurl + 'reports/report?report_type=mpsMalwareActivity&type=csv&frame=pastThreeMonth' 57 | data = requests.get(queryurl, verify=False, headers = \ 58 | {'X-FeApi-Token' : token}) 59 | return data.content 60 | # TODO - not finished 61 | 62 | def md5search(token, md5): 63 | # Queries the CMS for previously-seen files matching a md5 sum 64 | queryurl = baseurl + 'alerts?md5=' + md5 65 | data = requests.get(queryurl, verify=False, headers = \ 66 | {'X-FeApi-Token' : token, 'Accept' : 'application/json'}) 67 | return json.loads(datalcontent.decode('utf-8')) 68 | 69 | 70 | # The following functions are not specifically a part of the FireEye 71 | #API, rather, they are used in conjunction with the information 72 | #collectd from the API calls 73 | 74 | # Generate an index of alerted-upon hosts based on their IP 75 | #extrated from JSON-formatted alert information. It takes 'host' as 76 | #an argument, so the call can specify 'src' (usually internal) or 77 | #'dst' (usually external C2 or infection vector) as the index key. 78 | def genIndex(host, data): 79 | hosts = [] 80 | i = 0 81 | while i < len(data["alert"]): 82 | hosts.append(data["alert"][i][host]["ip"]) 83 | i += 1 84 | index = uniqify(hosts) 85 | return index 86 | 87 | 88 | # Extract all relevant information for a particular host by iterating 89 | # through the extracted JSON data. This takes three arguments: the 90 | # host of interest, the system type upon which we are pivoting 91 | # (usually the source IP) and the extracted JSON data blob 92 | # 93 | # TODO: extract ALL information if a particular host appears 94 | # more than once in the data 95 | def ExtractFEAlerts(host, sys_type, data): 96 | import datetime as dt 97 | i = 0 98 | # iterate through the alerts to find the interesting host 99 | while i < len(data["alert"]): 100 | #print(data["alert"][i][sys_type]) #DEBUG, pls remove 101 | # if match, collect the relevant alert data 102 | if str(data["alert"][i][sys_type]["ip"]) == str(host): 103 | try: 104 | hostname = data["alert"][i]["src"]["host"] 105 | except KeyError: 106 | hostname = "reverse lookup failed" 107 | try: 108 | dst = data["alert"][i]["dst"]["ip"] 109 | except KeyError: 110 | dst = "none" 111 | try: 112 | severity = data["alert"][i]["severity"] 113 | except KeyError: 114 | break # no need to continue severity = "none" 115 | try: 116 | malware = data["alert"][i]["explanation"]\ 117 | ["malwareDetected"]["malware"][0]["name"] 118 | except TypeError: 119 | malware = "unknown_malware" 120 | try: 121 | activity = data["alert"][i]["name"] 122 | except TypeError: 123 | activity = "No Data" 124 | except KeyError: 125 | activity = "No Data" 126 | alertUrl = data["alert"][i]["alertUrl"] 127 | # Time extracted from the CMS is in miliseconds, so we 128 | # need to divide by 1000 and then convert fromtimestamp. 129 | # Finally, format the time in an easy-to-read way 130 | alerttime = dt.datetime.fromtimestamp(data["alert"][i]["occurred"] / 1000) 131 | time = alerttime.strftime('%Y-%m-%d %H:%M:%s') 132 | return dst, hostname, malware, severity, activity, \ 133 | time, alertUrl 134 | i += 1 135 | -------------------------------------------------------------------------------- /IncMgmt/malware-tickets.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # This will take information from various malware, intrusion detection, 4 | # and other blinky light systems, and create a corresponding 5 | # incident ticket on the tracking appliance blinky lights so work can 6 | # be performed by operational teams 7 | # 8 | # version 0.2 Working, but needs some serious cleanup 9 | 10 | import os 11 | import json 12 | from uniqify import uniqify 13 | import requests 14 | 15 | from redmine import Redmine 16 | 17 | os.chdir(os.path.expanduser("~") + "/.incmgmt/") 18 | 19 | ## Standard prefs for these scripts. Move to prefs file TODO 20 | prefs = open('mw-prefs.txt','r') 21 | redmine_project = prefs.readline().rstrip() 22 | redmine_server = prefs.readline().rstrip() 23 | redmine_key = prefs.readline().rstrip() 24 | sn_server = prefs.readline().rstrip() 25 | user = prefs.readline().rstrip() 26 | pwd = prefs.readline().rstrip() 27 | severity_filter = prefs.readline().rstrip() 28 | ov_report = prefs.readline().rstrip() 29 | preamble = prefs.readline().rstrip() 30 | prefs.close() 31 | 32 | 33 | ## Here are things that need to be placed in a preferences file TODO 34 | # For now, this should point directly to a JSON report downloaded from 35 | # the FireEye device 36 | reportfile = '/home/infosec/Downloads/Alert_Details_sjccms01_20150414_123551790577768000.json' 37 | 38 | sub_base = "Malicious code activity detected on " 39 | sys_type = "src" # global identifier of the interesting system type 40 | redmine = Redmine(redmine_server, requests={'verify': False}, \ 41 | key=redmine_key, version='2.5.1') 42 | project = redmine.project.get(redmine_project) 43 | tracker_id = 18 # TODO add to prefs file # 2 on dev, 18 on prod 44 | 45 | 46 | # Generates an unique index of the specified systems. 47 | # System type "sys_type" takes a JSON key 48 | def genIndex(): 49 | hosts = [] 50 | i = 0 51 | while i < len(data["alert"]): 52 | hosts.append(data["alert"][i][sys_type]["ip"]) 53 | i += 1 54 | index = uniqify(hosts) 55 | return index 56 | 57 | # Extract all relevant information on a per-host basis 58 | def ExtractFEAlerts(host): 59 | i = 0 60 | # print("Reviewing JSON data") 61 | while i < len(data["alert"]): # page through the data 62 | #print(data["alert"][i][sys_type]) 63 | if str(data["alert"][i][sys_type]["ip"]) == str(host): # if match, collect the relevant alert data 64 | try: 65 | hostname = data["alert"][i]["src"]["host"] 66 | except KeyError: 67 | hostname = "reverse lookup failed" 68 | try: 69 | dst = data["alert"][i]["dst"]["ip"] 70 | except KeyError: 71 | dst = "none" 72 | try: 73 | severity = data["alert"][i]["severity"] 74 | except KeyError: 75 | break # no need to continue severity = "none" 76 | try: 77 | malware = data["alert"][i]["explanation"]\ 78 | ["malware-detected"]["malware"]["name"] 79 | except TypeError: 80 | malware = "unknown" 81 | try: 82 | activity = data["alert"][i]["explanation"]\ 83 | ["malware-detected"]["malware"]["stype"] 84 | except TypeError: 85 | activity = "No Data" 86 | except KeyError: 87 | activity = "No Data" 88 | alert_url = data["alert"][i]["alert-url"] 89 | time = data["alert"][i]["occurred"] 90 | return dst, hostname, malware, severity, activity, \ 91 | time, alert_url 92 | i += 1 93 | 94 | ## determine criticality factors 95 | # impact and urgency are used for Service Now 96 | # priority is used for Redmine 97 | def criticality(severity): 98 | if severity == "crit": 99 | impact = 2 100 | urgency = 1 101 | priority = 5 102 | elif severity == "majr": 103 | impact = 2 104 | urgency = 2 105 | priority = 4 106 | else: 107 | impact = 3 108 | urgency = 3 109 | priority = 3 110 | return impact, urgency, priority 111 | 112 | def sn_issue(host, redmine_url, impact, urgency, wikipage): 113 | ## Create the incident in ServiceNow 114 | # Create the headers 115 | headers = {"Content-Type":"application/json","Accept":"application/json"} 116 | # Construct the incident JSON object 117 | incident_data = '{' + \ 118 | '"short_description":' + '"Malware detected on: ' + host + '",' + \ 119 | '"description":' + '"For full information, see: ' + \ 120 | redmine_url + ' and for cleaning instructions, see: ' + \ 121 | wikipage + '",'\ 122 | '"u_category":' + '"Information Security",' + \ 123 | '"u_subcategory":' + '"Malware",' + \ 124 | '"impact":' + '"' + str(impact) + '",' + \ 125 | '"urgency":' + '"' + str(urgency) + '",' + \ 126 | '"contact_type":"Alert"' + '}' 127 | # Create the incident on the Service Now system 128 | response = requests.post(sn_server, auth=(user, pwd), \ 129 | headers=headers, data=incident_data) 130 | # Capture the ticket number and unique identifier 131 | if response.status_code != 201: 132 | print('Status:', response.status_code, 'Headers:', \ 133 | response.headers, 'Error Response:',response.json()) 134 | exit() 135 | sn_ticket = response.json()['result']['number'] 136 | sys_id = response.json()['result']['sys_id'] 137 | print("service now ticket created") 138 | return sn_ticket, sys_id 139 | 140 | def CheckTickets(host): 141 | # checks for an active ticket for identified host, based on the 142 | # short description 143 | short_desc = sub_base + host 144 | i = 0 145 | while i < len(project.issues): 146 | if str(project.issues[i]) == short_desc: 147 | incident_id = project.issues[i].id 148 | print("Found a matching ticket in Redmine") 149 | return incident_id 150 | i += 1 151 | return None 152 | 153 | 154 | def CreateRedmineTicket(host, priority, body): 155 | subject = sub_base + host 156 | new_issue = redmine.issue.create(project_id = redmine_project, \ 157 | subject = subject, tracker_id = tracker_id, \ 158 | priority_id = priority, description = body) 159 | redmine_issue_id = str(new_issue.id) 160 | redmine_url = redmine_server + "/issues/" + redmine_issue_id 161 | print("Created ticket " + str(new_issue)) 162 | return redmine_url, redmine_issue_id 163 | 164 | def UpdateRedmineTicket(ticket, notes): 165 | redmine.issue.update(ticket, notes = notes) 166 | print("Updated ticket" + str(ticket)) 167 | return None 168 | 169 | 170 | # Log to ticketlog & opentix 171 | def log(redmine_issue_id, sn_ticket, sys_id, redmine_url): 172 | # Write log file of tickets created 173 | ticket_log = open('ticketlog.csv','a') 174 | opentix_log = open('opentix.csv','a') 175 | ticket_log.write(redmine_issue_id + ',' + sn_ticket + ',' + \ 176 | sys_id + ',' + redmine_url + ',' + '\n') 177 | opentix_log.write(redmine_issue_id + ',' + sn_ticket + ',' + \ 178 | sys_id + '\n') 179 | ticket_log.close() 180 | opentix_log.close() 181 | 182 | # Perform OSINT Lookups 183 | def GatherIntel(target): 184 | # Use Automater http://www.tekdefense.com/automater/ 185 | # GitHub download: https://github.com/1aN0rmus/TekDefense-Automater 186 | os.chdir(os.path.expanduser("~") + "/bin/Automater") # set WD 187 | command = "/home/infosec/bin/Automater/Automater.py " + target 188 | output = os.popen(command) 189 | text = output.read() 190 | print(text) #DEBUG to see what's going on. 191 | os.chdir(os.path.expanduser("~") + "/.incmgmt/") # reset the WD 192 | return text 193 | 194 | # Perform lookups against Vectra 195 | # https://monza.arubanetworks.com/api/hosts/?last_source=10.11.8.183&page=last 196 | 197 | 198 | # main 199 | json_data=open(reportfile) # open the data file 200 | data=json.load(json_data) # parse the JSON in the file 201 | index = genIndex() 202 | for host in index: 203 | print("\n \n processing: " + host) 204 | dst, hostname, malware, severity, activity, time, alert_url = \ 205 | ExtractFEAlerts(host) 206 | print(dst) 207 | check = CheckTickets(host) # check for existing redmine ticket 208 | print("Redmine ticket info: " + str(check), severity) #DEBUG 209 | impact, urgency, priority = criticality(severity) 210 | # create a link to a wiki page with more info on specific malware 211 | wikipage = redmine_server + "/projects/incident_management/wiki/" + \ 212 | malware.translate({ord(i):None for i in '.'}) #remove dots 213 | # Perform OS-INT lookups 214 | intel = GatherIntel(dst) 215 | content = "Information Security network monintoring devices \ 216 | have identified a potential compromise on the network. \n \ 217 | Please check the following system for the following: \n \ 218 | * Affected Host: " + host + "\n" \ 219 | "* Last identified hostname: " + hostname + " (please verify)\n" \ 220 | "* Destination: " + dst + "\n" \ 221 | "* Malware family: [[" + malware + "]] \n" \ 222 | "* Activity Observed: " + activity + "\n" \ 223 | "* Detection Occurred at: " + time + "\n" \ 224 | "* FireEye alert URL: " + alert_url + "\n \n" \ 225 | "Open Source Intel: \n" + intel + "\n" 226 | if check is not None: 227 | # update existing tickets with additional info 228 | UpdateRedmineTicket(check, content) 229 | elif (check is None and (severity == "majr" )): 230 | # Create a ticket on the redmine server and return its ID 231 | redmine_url, redmine_issue_id = CreateRedmineTicket(host, priority, content) 232 | sn_ticket, sys_id = sn_issue(host, redmine_url, impact, urgency, wikipage) 233 | log(redmine_issue_id, sn_ticket, sys_id, redmine_url) # log the tix 234 | elif (check is None and (severity == "crit")): 235 | # Create a ticket on the redmine server and return its ID 236 | redmine_url, redmine_issue_id = CreateRedmineTicket(host, priority, content) 237 | sn_ticket, sys_id = sn_issue(host, redmine_url, impact, urgency, wikipage) 238 | log(redmine_issue_id, sn_ticket, sys_id, redmine_url) # log the tix 239 | elif severity == ("crit" or "majr"): 240 | UpdateRedmineTicket(check, content) 241 | # TODO perform a lookup in opentix and UpdateSNTicket(sn_ticket) 242 | else: print("Alert severity below threshold") 243 | 244 | json_data.close() 245 | 246 | -------------------------------------------------------------------------------- /IncMgmt/rogueSSID_check.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import os 4 | from redmine import Redmine 5 | import datetime as dt 6 | import requests 7 | import json 8 | 9 | # Set variables 10 | os.chdir(os.path.expanduser("~") + "/.incmgmt/") 11 | prefs = [] 12 | for line in open('mw-prefs.txt'): 13 | prefs.append(line) 14 | redmine_project = prefs[0].rstrip() 15 | redmine_server = prefs[1].rstrip() 16 | redmine_key = prefs[2].rstrip() 17 | sn_server = prefs[3].rstrip() 18 | sn_user = prefs[4].rstrip() 19 | sn_pass = prefs[5].rstrip() 20 | wikipage = "https://io.arubanetworks.com/projects/incident_management/wiki/Open_SSID_access_point" # description of how to handle this issue 21 | 22 | requests.packages.urllib3.disable_warnings() # turn off SSL warnings 23 | 24 | # Connect to redmine 25 | redmine = Redmine(redmine_server, requests={'verify': False}, \ 26 | key=redmine_key, version='2.5.1') 27 | project = redmine.project.get(redmine_project) 28 | 29 | 30 | ## Begin functions 31 | 32 | # Create an issue in Service Now 33 | def sn_issue(subject, redmine_url, impact, urgency, wikipage): 34 | # Define the headers 35 | headers = {"Content-Type":"application/json", \ 36 | "Accept":"application/json"} 37 | # Construct JSON object containing the incident data 38 | incident_data = '{' + \ 39 | '"short_description":"' + subject + '",' + \ 40 | '"description":' + '"A rogue access point has been discovered on the network. For full information, see: ' + \ 41 | redmine_url + ' and for instructions, see: ' + \ 42 | wikipage + '",'\ 43 | '"u_category":' + '"Intranet",' + \ 44 | '"u_subcategory":' + '"Access Issues",' + \ 45 | '"impact":' + '"' + str(impact) + '",' + \ 46 | '"urgency":' + '"' + str(urgency) + '",' + \ 47 | '"contact_type":"Alert"' + '}' 48 | # Create the incident on the Service Now system 49 | response = requests.post(sn_server, auth=(sn_user, sn_pass), \ 50 | headers=headers, data=incident_data) 51 | # Capture the ticket number and unique identifier 52 | if response.status_code != 201: 53 | print('Status:', response.status_code, 'Headers:', \ 54 | response.headers, 'Error Response:',response.json()) 55 | exit() 56 | sn_ticket = response.json()['result']['number'] 57 | sys_id = response.json()['result']['sys_id'] 58 | print("service now ticket created") 59 | return sn_ticket, sys_id 60 | 61 | # Log the created tickets to a file 62 | def log(redmine_issue_id, sn_ticket, sys_id, redmine_url): 63 | # Write log file of tickets created 64 | ticket_log = open('ticketlog.csv','a') 65 | opentix_log = open('opentix.csv','a') 66 | ticket_log.write(redmine_issue_id + ',' + sn_ticket + ',' + \ 67 | sys_id + ',' + redmine_url + ',' + '\n') 68 | opentix_log.write(redmine_issue_id + ',' + sn_ticket + ',' + \ 69 | sys_id + '\n') 70 | ticket_log.close() 71 | opentix_log.close() 72 | 73 | 74 | # Calculate interval for checking tickets 75 | def timeRange(interval): 76 | now = dt.datetime.today() # capture the current time 77 | delta = dt.timedelta(minutes=interval) # set the interval 78 | diff = now - delta # calculate the filter start time 79 | return diff 80 | 81 | # Determine if the issue is in the relevant interval and create a 82 | # service now ticket if it is 83 | def CheckInterval(created_filter, issue): 84 | issue_time = issue.created_on - dt.timedelta(hours=7) #adjust for UTC 85 | 86 | if issue_time - created_filter == abs(issue_time - \ 87 | created_filter): 88 | print("issue " + str(issue.id) + " is in the interval") 89 | redmine_url = redmine_server + "/issues/" + str(issue.id) 90 | subject = issue.subject 91 | sn_ticket, sys_id = sn_issue(subject, redmine_url, 2, 2, wikipage) 92 | log(str(issue.id), sn_ticket, sys_id, redmine_url) 93 | else: 94 | return None 95 | 96 | ## Begin script 97 | # set a time filter for finding newly active tickets. 98 | # Interval in minutes 99 | created_filter = timeRange(30) 100 | # Retrieve all newly-created tickets that relate to a Rogue SSID 101 | for i in project.issues: 102 | try: 103 | if str(i.category).rstrip() == "Rogue SSID": 104 | print("found matching ticket: " + str(i.id)) 105 | CheckInterval(created_filter, i) # check if new 106 | except: 107 | pass # ignore errors 108 | 109 | -------------------------------------------------------------------------------- /IncMgmt/ticketing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # A set of Python3 modules for interacting with various ticketing 4 | # systems such as Redmine and ServiceNow 5 | 6 | import os 7 | import requests 8 | from redmine import Redmine 9 | 10 | # Set wd 11 | os.chdir(os.path.expanduser("~") + "/.incmgmt/") 12 | 13 | # Turn off the SSL certificate warnings. This is a less-than-stellar 14 | # idea. TODO: implement using the certifi package to verify the SSL 15 | # certificate 16 | requests.packages.urllib3.disable_warnings() 17 | 18 | # import ticketing system info and credentials from prefs file 19 | prefs = [] 20 | for line in open('mw-prefs.txt'): 21 | prefs.append(line) 22 | rm_project = prefs[0].rstrip() # redmine project name 23 | rm_server = prefs[1].rstrip() # redmine server URL 24 | rm_key = prefs[2].rstrip() # redmine API key 25 | sn_server = prefs[3].rstrip() # ServiceNow URL 26 | sn_user = prefs[4].rstrip() # ServiceNow username 27 | sn_pass = prefs[5].rstrip() # ServiceNow password 28 | 29 | # binds to the redmine server with the API key and also retrieves the 30 | # project for use in interacting with the system 31 | def bindRedmine(): 32 | redmine = Redmine(rm_server, requests={'verify': False}, \ 33 | key=rm_key, version='2.5.1') 34 | project = redmine.project.get(rm_project) 35 | return redmine, project 36 | 37 | ## Create the incident in ServiceNow with relevant information. This 38 | ## takes four arguments: 39 | ### subject: the short description or incident subject line 40 | ### info_url: a URL containing further information for the responder 41 | def sn_issue(host, redmine_url, impact, urgency, wikipage): 42 | # Define the headers 43 | headers = {"Content-Type":"application/json", \ 44 | "Accept":"application/json"} 45 | # Construct JSON object containing the incident data 46 | incident_data = '{' + \ 47 | '"short_description":' + '"Malware detected on: ' + host + '",' + \ 48 | '"description":' + '"For full information, see: ' + \ 49 | redmine_url + ' and for cleaning instructions, see: ' + \ 50 | wikipage + '",'\ 51 | '"u_category":' + '"Information Security",' + \ 52 | '"u_subcategory":' + '"Malware",' + \ 53 | '"impact":' + '"' + str(impact) + '",' + \ 54 | '"urgency":' + '"' + str(urgency) + '",' + \ 55 | '"contact_type":"Alert"' + '}' 56 | # Create the incident on the Service Now system 57 | response = requests.post(sn_server, auth=(sn_user, sn_pass), \ 58 | headers=headers, data=incident_data) 59 | # Capture the ticket number and unique identifier 60 | if response.status_code != 201: 61 | print('Status:', response.status_code, 'Headers:', \ 62 | response.headers, 'Error Response:',response.json()) 63 | exit() 64 | sn_ticket = response.json()['result']['number'] 65 | sys_id = response.json()['result']['sys_id'] 66 | print("service now ticket created") 67 | return sn_ticket, sys_id 68 | 69 | def CheckRMTickets(short_desc): 70 | # checks for an existing and active Redmine ticket, based on the 71 | # provided short description 72 | redmine, project = bindRedmine() 73 | i = 0 74 | while i < len(project.issues): 75 | if str(project.issues[i]) == short_desc: 76 | incident_id = project.issues[i].id 77 | print("Found a matching ticket in Redmine") 78 | return incident_id 79 | i += 1 80 | return None 81 | 82 | 83 | def CreateRedmineTicket(subject, priority, body, category, tracker): 84 | redmine, project = bindRedmine() 85 | new_issue = redmine.issue.create(project_id = rm_project, \ 86 | subject = subject, tracker_id = tracker, priority_id = \ 87 | priority, description = body, category_id = category) 88 | redmine_issue_id = str(new_issue.id) 89 | redmine_url = rm_server + "/issues/" + redmine_issue_id 90 | print("Created ticket " + str(new_issue)) 91 | return redmine_url, redmine_issue_id 92 | 93 | 94 | def UpdateRedmineTicket(ticket, notes): 95 | redmine.issue.update(ticket, notes = notes) 96 | print("Updated ticket" + str(ticket)) 97 | return None 98 | 99 | # Logs the ticket reference information so it can be used for 100 | # subsequent updates. The log files should reside in the .incmgmt 101 | # dir. The ticket_log is a running log of all tickets created, opentix 102 | # is the currently active tickets 103 | def log(redmine_issue_id, sn_ticket, sys_id): 104 | # Write log file of tickets created 105 | ticket_log = open('ticketlog.csv','a') 106 | opentix_log = open('opentix.csv','a') 107 | ticket_log.write(redmine_issue_id + ',' + sn_ticket + ',' + \ 108 | sys_id + '\n') 109 | opentix_log.write(redmine_issue_id + ',' + sn_ticket + ',' + \ 110 | sys_id + '\n') 111 | ticket_log.close() 112 | opentix_log.close() 113 | 114 | 115 | ## determine criticality factors 116 | # impact and urgency are used for Service Now 117 | # priority is used for Redmine 118 | def criticality(severity): 119 | if severity.lower() == "crit": 120 | impact = 2 121 | urgency = 1 122 | priority = 5 123 | elif severity.lower() == "majr": 124 | impact = 2 125 | urgency = 2 126 | priority = 4 127 | else: 128 | impact = 3 129 | urgency = 3 130 | priority = 3 131 | return impact, urgency, priority 132 | 133 | -------------------------------------------------------------------------------- /IncMgmt/uniqify.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | def uniqify(things): 4 | return list(set(things)) 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Metrics/.#Readme.org: -------------------------------------------------------------------------------- 1 | ktneely@theanalyzer.27343:1430754572 -------------------------------------------------------------------------------- /Metrics/Readme.md: -------------------------------------------------------------------------------- 1 | This directory contains various scripts and code snippets to aid in analyzing the volume, trends, etc. of any data collected as a part of the incident management process. 2 | 3 | Most of these are very specific to my environment and probably will not help you directly. They're here for reference only. 4 | 5 | 6 | These are pretty raw, use at own risk. 7 | -------------------------------------------------------------------------------- /Metrics/Training/secmentor-stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # This script reads a directory of "completed" and "not started" 4 | # training reports exported from the online Security Mentor web-based 5 | # training service. It then calculates a number of metrics and graphs 6 | # based on those reports. 7 | 8 | 9 | import os 10 | import re 11 | import glob 12 | import datetime as dt 13 | import pandas as pd 14 | import numpy as np 15 | import matplotlib as mpl 16 | import matplotlib.pyplot as plt 17 | from matplotlib.colors import LinearSegmentedColormap 18 | from matplotlib.lines import Line2D 19 | 20 | 21 | # General Options and settings 22 | # Make Pandas plots prettier 23 | pd.options.display.mpl_style = 'default' 24 | a = 0.7 # transparency for figures 25 | today = dt.date.today() 26 | 27 | # For diplay when running in iPython3 Notebook 28 | # %matplotlib inline 29 | 30 | # Ingest the data 31 | data_dir = '/path/to/data/dir' 32 | os.chdir(data_dir) 33 | 34 | t_files = glob.glob('trainees-completed*.csv') # identify complete logs 35 | u_files = glob.glob('trainees-not-started*.csv') # identify not started logs 36 | 37 | # Take all the files in the directory and combine into one pd.DataFrame 38 | def merge_logs(data_files, index): 39 | df_master = pd.DataFrame() # empty "master" dataframe 40 | data_list = [] # empty list for all dataframes 41 | if index is not None: 42 | for files in data_files: 43 | df = pd.read_csv(files, header=0, encoding='latin-1', index_col=[index], parse_dates=True) 44 | data_list.append(df) 45 | df_master = pd.concat(data_list) #merge the data into the master dataframe 46 | return df_master 47 | else: 48 | for files in data_files: 49 | df = pd.read_csv(files, header=0, encoding='latin-1', parse_dates = True) 50 | data_list.append(df) 51 | df_master = pd.concat(data_list) #merge the data into the master dataframe 52 | return df_master 53 | 54 | 55 | 56 | # return a list of all unique values in a given series 57 | def active_lessons(df, category): 58 | topics = [] # initialize an empty list to store the topics 59 | for i in df[category]: 60 | topics.append(i) 61 | return list(set(topics))# return only the unique values 62 | 63 | 64 | t_data = merge_logs(t_files, 'Completed') # combine all log files 65 | u_data = merge_logs(u_files, None) 66 | topics = active_lessons(t_data, 'Lesson Topic') # extract topics 67 | 68 | fig_tots = plt.figure(figsize=(14,10)) 69 | # Add a subplot 70 | ax_tots = fig_tots.add_subplot(111) 71 | xlab_tots = "Awareness Lesson" # Set X-axis label 72 | 73 | 74 | # Calculate the total completed and incomplete per lesson 75 | totals = pd.DataFrame({ 'Completed': t_data.groupby(t_data['Lesson Topic']).count()['Email'],\ 76 | 'Incomplete': u_data.groupby(u_data['Lesson Topic']).count()['Email']}) 77 | 78 | plot_tots = totals.plot(kind='bar', title="Complete vs. Incomplete by\ 79 | Lesson", figsize=(12,10), ax=ax_tots) 80 | ax_tots.set_xlabel(xlab_tots, fontsize=20, alpha=a, ha='left') 81 | 82 | # Customize title 83 | ax_tots.set_title(ax_tots.get_title(), fontsize=26, ha='left') 84 | plt.subplots_adjust(top=0.9) 85 | ax_tots.title.set_position((0,1.08)) 86 | 87 | fig_tots = plot_tots.get_figure() 88 | fig_tots.savefig("/tmp/lesson_totals" + str(today) + ".png") 89 | 90 | # Calculate completions by topic on a monthly basis 91 | 92 | def lesson_complete(df, topic): 93 | series = df['Lesson Topic'] 94 | lesson = series.str.contains(topic) 95 | lesson_data = lesson.astype(float).resample('M', how=np.sum) 96 | return lesson_data 97 | 98 | # Convert the qualitative data to quantitative 99 | # create a new dataframe to hold the monthly totals 100 | df_progress = pd.DataFrame() 101 | for topic in topics: 102 | print("Processing " + topic) #feedback for debug 103 | df_progress[topic] = lesson_complete(t_data, topic) 104 | 105 | #topic_order = ['Intro to Security Awareness', 'Mobile Security', 'Passwords'] 106 | #mapping = {topics: i for i, topics in ennumerate(topic_order)} 107 | #key = df_progress[df_progress.index().map(mapping) 108 | #df_progress.iloc(topic_order.argsort()) 109 | # calculate cumulative sums of the lessons completed and plot 110 | #df_progress 111 | 112 | # Title 113 | ttl_coms = "Monthly Total Completions by Topic" 114 | fig_coms = plt.figure(figsize=(14,10)) 115 | # Add a subplot 116 | ax = fig_coms.add_subplot(111) 117 | 118 | plot_coms = df_progress.cumsum().plot(kind='bar', title=ttl_coms,\ 119 | figsize=(12,10), ax=ax, alpha=a)#,\ 120 | #xlim=(0,max(df_progress))) 121 | 122 | fig_coms = plot_coms.get_figure() 123 | 124 | 125 | # Customize the figure 126 | 127 | # Create a horizontal bar plot 128 | ax.grid(axis='y') # remove X gridline 129 | ax.set_frame_on(False) # no plot frame 130 | # Customize title, set position, allow space on top of plot for title 131 | ax.set_title(ax.get_title(), fontsize=26, alpha=a, ha='left') 132 | plt.subplots_adjust(top=0.9) 133 | ax.title.set_position((0,1.08)) 134 | 135 | #dates = pd.date_range('2014-10-10', '2015-02-01') 136 | #xticks = [dates] 137 | #ax_coms.xaxis.set_ticks(xticks) 138 | #ax_coms.set_xticklabels(xticks, fontsize=16, alpha=a) 139 | 140 | #ax.set_xlabel(xlab, fontsize=20, alpha=a, ha='left') 141 | #ax.xaxis.set_label_coords(0, 1.04) 142 | 143 | # Position x tick labels on top 144 | ax.xaxis.tick_top() 145 | # Remove tick lines in x and y axes 146 | ax.yaxis.set_ticks_position('none') 147 | ax.xaxis.set_ticks_position('bottom') 148 | 149 | ax.grid(axis='x') 150 | 151 | # Customize x tick lables 152 | #xticks = [item.get_xticklabels for item in ax.get_xticklabels()] 153 | #ax.xaxis.set_ticks(xticks) 154 | #ax.set_xticklabels(xticks, fontsize=16, alpha=a) 155 | 156 | 157 | # Customize y tick labels 158 | #yticks = [item.get_text() for item in ax.get_yticklabels()] 159 | yticks = [50, 100, 150, 200, 250, 300, 350, 400, 450, 500] 160 | ax.set_yticklabels(yticks, fontsize=16, alpha=a) 161 | ax.yaxis.set_tick_params(pad=12) 162 | 163 | fig_coms.savefig("/tmp/completions-by-month" + str(today) + ".png") 164 | 165 | 166 | # Add a new series for Department name and populate by performing 167 | # partial matches against a lookup dictionary 168 | 169 | group_to_OU = {'Eng':'Engineering', 'ales':'Sales', 'IT':'IT', 'TAC':'TAC', \ 170 | 'arketing':'Marketing', 'SME':'SME', 'Product Mana':'Engineering',\ 171 | 'Ops':'Operations', 'ACE':'Pro Services', 'IA':\ 172 | 'Finance', 'essional Ser':'Pro Services','HR':'HR',\ 173 | 'Accounting':'Finance', 'FP&A':'Finance','Accounting':'Finance',\ 174 | 'Tax':'Finance','CEO':'CEO/ CTO/ Biz Ops','CTO':'CEO/ CTO/ Biz Ops',\ 175 | 'QA':'QA','acilit':'Facilities','Bus Dev':'Biz Dev','Training':\ 176 | 'Training','Allocation':'Facilities', 'Legal':'Legal','RMA':'Operations',\ 177 | 'Purchasing':'Finance','Public Re':'Marketing', 'CMO':'Marketing',\ 178 | 'PMO':'CEO/ CTO/ Biz Ops','EBC':'Marketing'} 179 | 180 | 181 | t_data['Department'] = np.NaN 182 | u_data['Department'] = np.NaN 183 | #while i <= len(t_data['Group']): 184 | def check_group(row): 185 | for key in group_to_OU: 186 | if re.search(str(key), str(row['Group'])): 187 | return group_to_OU[key] 188 | 189 | 190 | ''' 191 | if group_to_OU'ales' in str(row['Group']): 192 | return 'Sales' 193 | elif 'TAC' t_data['Group'].str.contains('TAC') is True: 194 | return 'TAC' 195 | else: 196 | return 'Not Found' 197 | ''' 198 | # Check the listed group and place into a generic Department 199 | t_data['Department'] = t_data.apply(check_group, axis=1) 200 | u_data['Department'] = u_data.apply(check_group, axis=1) 201 | 202 | # Create a new 'Department Totals' dataframe with columns for 203 | # complete, incomplete, total users, and percentage complete 204 | dep_tots = pd.DataFrame({'Completed': \ 205 | t_data.groupby(t_data['Department']).count()['Email'],\ 206 | 'Incomplete': u_data.groupby(u_data['Department']).count()['Email']}) 207 | 208 | # A dirty way to calculate total number of users per department by 209 | # summing the total training modules that have been distributed to 210 | # users and then dividing by the number of unique modules. Inaccurate 211 | # if the org is experiencing rapid growth or decline 212 | dep_tots['Total Users'] = (dep_tots['Completed'] + \ 213 | dep_tots['Incomplete']) / len(topics) 214 | 215 | # Calculate the percentage complete per department 216 | dep_tots['Percentage'] = dep_tots['Completed'] / (dep_tots['Completed'] + \ 217 | dep_tots['Incomplete']) *100 218 | 219 | # Sort the DataFrame by total users in 220 | dep_tots = dep_tots.sort('Total Users') 221 | 222 | # A quick plot, replaced by the more advanced one below 223 | ''' 224 | plot_tots = dep_tots['Percentage'].plot(kind='bar', \ 225 | title="Awareness Training by Completion Percentage") 226 | fig_tots = plot_tots.get_figure() 227 | fig_tots.savefig("/tmp/dept-totals" + str(today) + ".png") 228 | ''' 229 | 230 | # Create a custom figure representing mutli-dimensional data 231 | # idea and code from: 232 | # https://datasciencelab.wordpress.com/2013/12/21/beautiful-plots-with-pandas-and-matplotlib/ 233 | fig = plt.figure(figsize=(14,10)) 234 | # Add a subplot 235 | ax = fig.add_subplot(111) 236 | # Title 237 | ttl = "Departmental Awareness Training Metrics" 238 | 239 | a = 0.7 # transparency 240 | customcmap = [(x/24.0, x/48.0, 0.05) for x in range(len(dep_tots))] 241 | # Create a horizontal bar plot 242 | plot_tots = dep_tots['Percentage'].plot(kind='barh', ax=ax, alpha=a, legend=False, color=customcmap,\ 243 | edgecolor='w', xlim=(0,max(dep_tots['Percentage'])), title=ttl) 244 | ax.grid(axis='y') # remove X gridline 245 | ax.set_frame_on(False) # no plot frame 246 | # Customize title, set position, allow space on top of plot for title 247 | ax.set_title(ax.get_title(), fontsize=26, alpha=a, ha='left') 248 | plt.subplots_adjust(top=0.9) 249 | ax.title.set_position((0,1.08)) 250 | # Set x axis label on top of plot, set label text 251 | ax.xaxis.set_label_position('top') 252 | xlab = 'Percent of Employees Completing Awareness Training' 253 | ax.set_xlabel(xlab, fontsize=20, alpha=a, ha='left') 254 | ax.xaxis.set_label_coords(0, 1.04) 255 | 256 | # Position x tick labels on top 257 | ax.xaxis.tick_top() 258 | # Remove tick lines in x and y axes 259 | ax.yaxis.set_ticks_position('none') 260 | ax.xaxis.set_ticks_position('bottom') 261 | 262 | # Customize x tick lables 263 | xticks = [10,20,30,40,50,60] 264 | ax.xaxis.set_ticks(xticks) 265 | ax.set_xticklabels(xticks, fontsize=16, alpha=a) 266 | 267 | # Customize y tick labels 268 | yticks = [item.get_text() for item in ax.get_yticklabels()] 269 | ax.set_yticklabels(yticks, fontsize=16, alpha=a) 270 | ax.yaxis.set_tick_params(pad=12) 271 | 272 | # Create a fake colorbar to express department population 273 | ctb = LinearSegmentedColormap.from_list('custombar', customcmap, N=2048) 274 | # Trick from http://stackoverflow.com/questions/8342549/ 275 | # matplotlib-add-colorbar-to-a-sequence-of-line-plots 276 | sm = plt.cm.ScalarMappable(cmap=ctb, norm=plt.normalize(vmin=20, vmax=800)) 277 | # Fake up the array of the scalar mappable 278 | sm._A = [] 279 | 280 | # Set colorbar, aspect ratio 281 | cbar = plt.colorbar(sm, alpha=0.05, aspect=16, shrink=0.4) 282 | cbar.solids.set_edgecolor("face") 283 | # Remove colorbar container frame 284 | cbar.outline.set_visible(False) 285 | # Fontsize for colorbar ticklabels 286 | cbar.ax.tick_params(labelsize=16) 287 | # Customize colorbar tick labels 288 | mytks = range(0,800,100) 289 | cbar.set_ticks(mytks) 290 | cbar.ax.set_yticklabels([str(a) for a in mytks], alpha=a) 291 | 292 | # Colorbar label, customize fontsize and distance to colorbar 293 | cbar.set_label('Department Population', alpha=a, 294 | rotation=270, fontsize=20, labelpad=20) 295 | # Remove color bar tick lines, while keeping the tick labels 296 | cbarytks = plt.getp(cbar.ax.axes, 'yticklines') 297 | plt.setp(cbarytks, visible=False) 298 | 299 | 300 | fig_tots = plot_tots.get_figure() 301 | fig_tots.savefig("/tmp/dept-totals" + str(today) + ".png") 302 | -------------------------------------------------------------------------------- /Metrics/incident_totals_by_category.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import os 4 | import pandas as pd 5 | import datetime as dt 6 | import matplotlib.dates as dates 7 | 8 | # Specify the source data 9 | ticket_data = 'path/to/data.file' 10 | 11 | tickets = pd.read_csv(ticket_Data, index_col = 'created_on', parse_dates=True) 12 | vuln_cats = ['Networking', 'Server - UNIX', 'Server - Windows', \ 13 | 'Virtual Infrastructure', 'Database', 'Web Application'] 14 | inc_cats = ['Denial of Service', 'Inappropriate Usage', \ 15 | 'Lost Equipment', 'Malicious Code', 'Uncategorized'] 16 | 17 | pd.options.display.mpl_style = 'default' 18 | inc_totals = pd.DataFrame() 19 | monthly_totals = pd.DataFrame() 20 | for category in vuln_cats: 21 | cat_match = tickets['category'] == category 22 | print("Processing Vulnerabilty data for: " + category) 23 | monthly_totals[category] = cat_match.astype(int).resample('M', how=np.sum).fillna('0') 24 | 25 | for category in inc_cats: 26 | cat_match = tickets['category'] == category 27 | inc_totals[category] = cat_match.astype(int).resample('M', how=np.sum).fillna('0') 28 | 29 | 30 | def create_barplot(data): 31 | fig = plt.figure(figsize=(14,10)) 32 | ax = fig.add_subplot(111) 33 | data.plot(kind='bar', figsize=(12,10), ax=ax) 34 | #ax.set_xticklabels([dt.strftime('%m-%Y') for dt in tickets.index.to_pydatetime()]) 35 | fig, ax = plt.subplots() 36 | #ax.plot_date(tickets.index.to_pydatetime(), [10,20,30,40,50,60,70,80,90], ydate=False) 37 | ax.xaxis.set_minor_formatter(dates.DateFormatter('%m-%Y')) 38 | ax.xaxis.grid(True, which="minor") 39 | ax.xaxis.set_major_locator(dates.MonthLocator()) 40 | ax.xaxis.set_major_formatter(dates.DateFormatter('%m-%Y')) 41 | 42 | create_barplot(monthly_totals) 43 | create_barplot(inc_totals) 44 | 45 | # TODO: save those pretty pictures to a file 46 | -------------------------------------------------------------------------------- /Metrics/redmine_collect-issues.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import os 4 | import datetime as dt 5 | from redmine import Redmine 6 | 7 | # Queries a redmine server for issues created in a specific project 8 | # and generates some basic data around those tickets for further 9 | # analysis. 10 | # Hard-coded to ignore issues in subprojects, so this needs 11 | # to be run against each project to collect the information. 12 | 13 | ## Configure your environment through preferences file 14 | ## 15 | # load prefs from ~/.incmgmt/ov_prefs.txt 16 | # The parameters should be in the following format 17 | # DO NOT use comments or blank lines. 18 | # Redmine Project 19 | # Redmine URL 20 | # Redmine API key 21 | 22 | # Read prefs from the preferences file 23 | os.chdir(os.path.expanduser("~") + "/.incmgmt/") 24 | prefs = [] 25 | for line in open('mw-prefs.txt'): 26 | prefs.append(line) 27 | redmine_server = prefs[1].rstrip() 28 | redmine_key = prefs[2].rstrip() 29 | redmine_project = 'incident_management' 30 | 31 | ''' 32 | prefs = open('ov_prefs.txt','r') 33 | redmine_project = 'incident_management' #prefs.readline().rstrip() 34 | redmine_server = prefs.readline().rstrip() 35 | redmine_key = prefs.readline().rstrip() 36 | prefs.close() 37 | ''' 38 | 39 | # The script will collect all incidents created between 'startdate' 40 | # and 'enddate'. Default setting below is for all the data in my 41 | # system, YMMV 42 | startdate = dt.date(2014, 6, 1) 43 | enddate = dt.date.today() 44 | 45 | 46 | # Extract data on redmine tickets, on a per-project basis. This will 47 | # extract the number of opened tickets, closed tickets, on a per 48 | # category basis. 49 | def CalculateTickets(project, startdate, enddate): 50 | begyear = startdate.year() 51 | endyear = enddate.year() 52 | begmonth = startdate.month() 53 | endmonth = enddate.month() 54 | 55 | def SetRMParams(project): 56 | redmine = Redmine(redmine_server, requests={'verify': False}, \ 57 | key=redmine_key) 58 | return redmine 59 | 60 | def InitializeLogFile(project): 61 | # Create a new CSV file for storing the ticket information and 62 | # create the headers. A previously-created log file will be 63 | # destroyed, but this will persist after execution for manual 64 | # inspection. It is stored in the ~/.incmgmt directory 65 | logfilename = project + '-' + str(dt.date.today()) + '.csv' 66 | logfile = open(logfilename, 'w') 67 | logfile.write("id,category,tracker,project,priority,created_on,\ 68 | updated_on,start_date,status,subject\n") 69 | return logfile 70 | 71 | 72 | def CreateRedmineIssueLog(project, logfile): 73 | # create the file, based on project name 74 | # write the headers 75 | # pull the incident issues and write as CSV 76 | for issue in redmine.issue.filter(project_id = project, \ 77 | status_id = '*'): #, subproject_id = '!*'): 78 | logfile.write(\ 79 | str(issue.id) + ',' \ 80 | + str(getattr(issue, 'category', 'Uncategorized')) + ',' \ 81 | + str(issue.tracker) + ',' \ 82 | + str(issue.project) + ',' \ 83 | + str(issue.priority) + ',' \ 84 | + str(issue.created_on) + ',' \ 85 | + str(issue.updated_on) + ',' \ 86 | + str(issue.start_date) + ',' \ 87 | + str(issue.status) + ',' \ 88 | + '"' + getattr(issue, 'subject', 'No Subject') + '"'\ 89 | + '\n') 90 | 91 | logfile = InitializeLogFile(redmine_project) # create empty log file 92 | redmine = SetRMParams(redmine_project) # access the redmine server 93 | CreateRedmineIssueLog(redmine_project, logfile) # create the data 94 | logfile.close() # close the logfile 95 | -------------------------------------------------------------------------------- /Metrics/ticket_totals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import os 4 | import re 5 | import pandas as pd 6 | import numpy as np 7 | import matplotlib.pyplot as plt 8 | import datetime as dt 9 | import matplotlib.dates as dates 10 | 11 | 12 | # Specify the data files and create a pandas dataframe for each 13 | vulns_file = '/path/to/some.file' 14 | incs_file = '/path/to/some.file' 15 | vulns = pd.read_csv(vulns_file, index_col='created_on', parse_dates=True) 16 | incs = pd.read_csv(incs_file, index_col='created_on', parse_dates=True) 17 | 18 | # Create a list of interesting attributes in the dataframe 19 | data_points = ['tracker', 'priority', 'status'] 20 | 21 | # Simple function for creating sums 22 | def sums(df, cat): 23 | series = df[cat] 24 | 25 | 26 | ''' 27 | # Function to determine the frequent internal offenders TODO 28 | def offenders(): 29 | use re to extract the host IPs 30 | calculate totals of tickets with specific IP 31 | perform reverse lookup 32 | output a table with data 33 | ''' 34 | 35 | ''' 36 | # function to calculate the sume of various categories TODO 37 | for cat in data_points: 38 | calculate sum 39 | append to df 40 | ''' 41 | 42 | # identify the categories of interest 43 | web_apps = v_categories.str.contains('Web Application') 44 | networking = v_categories.str.contains('Networking') 45 | database = v_categories.str.contains('Database') 46 | windows = v_categories.str.contains('Server - Windows') 47 | unix = v_categories.str.contains('Server - UNIX') 48 | virt = v_categories.str.contains('Virtual Infrastructure') 49 | dos = i_categories.str.contains('Denial of Service') 50 | docs = i_categories.str.contains('Documentation') # administrative 51 | in_usage = i_categories.str.contains('Inappropriate Usage') 52 | lost = i_categories.str.contains('Lost Equipment') 53 | malware = i_categories.str.contains('Malicious Code') 54 | 55 | # sum up the string data on a monthly basis 56 | web_data = web_apps.astype(float).resample('M', how=np.sum).fillna('0') 57 | net_data = networking.astype(float).resample('M', how=np.sum) 58 | db_data = database.astype(float).resample('M', how=np.sum) 59 | windows_data = windows.astype(float).resample('M', how=np.sum) 60 | unix_data = unix.astype(float).resample('M', how=np.sum) 61 | virt_data = virt.astype(float).resample('M', how=np.sum) 62 | dos_data = dos.astype(float).resample('M', how=np.sum) 63 | in_usage_data = in_usage.astype(float).resample('M', how=np.sum) 64 | lost_data = lost.astype(float).resample('M', how=np.sum) 65 | malware_data = malware.astype(float).resample('M', how=np.sum) 66 | 67 | 68 | # Create the legend 69 | networking.name = "Networking" 70 | web_apps.name = "Web Apps" 71 | db_data.name = "Database" 72 | windows_data.name = "Windows Servers" 73 | unix_data.name = "UNIX Servers" 74 | virt_data.name = "Virtual Infrastructure" 75 | 76 | # Group the df by category 77 | vulns.groupby('category') 78 | -------------------------------------------------------------------------------- /README.org: -------------------------------------------------------------------------------- 1 | #+TITLE: Incident Management and Response Tools 2 | 3 | * Overview 4 | I have a large number of systems, security, operations, and otherwise with some role in the incident management process. They sit there, blinking lights at each other, but none of them communicate. The scripts in this directory aim to fix that, likely in the most superficial way possible. 5 | This repository is a set of scripts I have created and use for performing incident management activities. To me, this covers everything from vulnerability analysis to open source research to incident response activities, and as a result, this is a pretty varied toolset. 6 | 7 | However, this is fairly tailored to my own workflows and tools, so you 8 | may not be able to run it directly out-of-the-box. I hope these are 9 | of some use. 10 | 11 | ** Preparing your envionment 12 | Most things can be run straight away or with slight modification to the code itself. However, some of the scripts ahve configuration settings and they default to looking in ~/.incmgmt for relevant configuration files 13 | 14 | 15 | ** TODO Methodology 16 | In the future, I will separate the basic execution and script description documentation from the documentation around methodology. But until I get this sorted, it will be mixed in with the rest of the documentation. At the moment, it i merely disorganized snippets to remind me what I want to write about. 17 | 18 | *** Vulnerability Management 19 | 20 | **** Using Overrides 21 | 22 | **** Reporting 23 | After a task has run, I perform a quick review of the results and edit out 24 | 25 | *** Creating work tickets 26 | Once the general report information is saved to my data storage, I go back to the report in the OpenVAS web interface and create some more, usually temporary, overrrides. This is to prevent creating a number of duplicate tickets. For example, if there is vulnerability in Apache, and the server is configured to listen on multiple ports such as 80 and 443, then OpenVAS will report two discrete vulnerabilities. However, both of these will liklely be fixed at the same time by updating Apache. And on a subnetwork devoted to web servers, there will likely be a large number of these duplicates. So, I will create a temporary override for that particular task that ignores one of the two ports for all hosts on that task and modifying the detection to 'log', rather than a vuln. The override duration should be just a bit longer than your scan cycle or expected remediation. 27 | Another way to handle this would be to modify the script to create only a single ticket when the host and short description are the same. 28 | 29 | 30 | 31 | * The Scripts 32 | The scripts and toolsin this repository are organized into folders by use or purpose. 33 | 34 | ** Vulnerability Analysis and Management 35 | Located in ./VulnMgmt 36 | Scripts to help implement a vulnerability management program 37 | 38 | *** Vuln-tickets.py 39 | This creates tickets on both Redmine[fn:1] and Service Now[fn:2] ticketing systems so that operational teams can work on the issues. 40 | 41 | ** Research 42 | Located in ./Research 43 | Random scripts for log mining, intel gathering, network querying, 44 | and other incident response-ish activities. Unless otherwise 45 | indicated, all files in this project are governed by the GPLv3 46 | license. 47 | *** ioc-intel.sh 48 | This script performs some quick lookups against a list of ip 49 | address or FQDN IOCs 50 | *** reverselook.sh 51 | performs reverse lookups on a list of IP addresses 52 | *** cif-lookup.sh 53 | performs lookups on multiple cif servers and reports on hit or no 54 | hit cif servers are based on local user's .cif* files 55 | 56 | * License 57 | See the LICENSE file in this repository for the license of everything it contains 58 | 59 | * Footnotes 60 | 61 | [fn:1] [[https://www.redmine.org][Redmine]] is a Project management tool and the script uses the [[https://pypi.python.org/pypi/python-redmine/0.4.0][python-redmine library]] 62 | 63 | [fn:2] http://wiki.servicenow.com/index.php?title=Table_API_Python_Examples 64 | -------------------------------------------------------------------------------- /Research/cif-lookup.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | # a simple query against cif server(s) for matches on suspect IPs 4 | 5 | # create the work list from the specified filed and ignore RFC1918 IPs 6 | LIST=`egrep -v '(^127\.0\.0\.1)|(^192\.168)|(^10\.)|(^172\.1[6-9])|(^172\.2[0-9\ 7 | ])|(^172\.3[0-1])' $1` 8 | 9 | # query known CIF servers 10 | for ioc in $LIST; do 11 | echo "processing IOC $ioc" 12 | if [[ -n $(cif $ioc) ]]; then 13 | echo "Match found on local cif server" 14 | else 15 | echo "no match on local cif server" 16 | fi 17 | if [[ -n $(cif -C ~/.cif2 $ioc) ]]; then 18 | echo "Match found on remote cif serer" 19 | else 20 | echo "no match on remote cif server" 21 | fi 22 | done 23 | -------------------------------------------------------------------------------- /Research/hybrid-analysis_URL-hash.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Reads a list of URL Hashes from a file and looks them up on Hybrid Analysis 3 | # Returns the URL 4 | # 5 | # MUST have the VxAPI available and configured: 6 | # Depends on: https://github.com/PayloadSecurity/VxAPI 7 | # Run in same directory as VxAPI 8 | 9 | LIST=`cat $1` 10 | 11 | 12 | 13 | # move previous run, overwriting ones that occurred before 14 | #rm output.csv 15 | mv output.csv output_previous.csv 16 | 17 | for HASH in $LIST 18 | do 19 | echo "processing $HASH" 20 | ./vxapi.py search_hash $HASH > data.txt 21 | # cat $DATA 22 | URL=`grep '"url":' data.txt | awk -F'"' '{print $4}'` 23 | IPArray=(`grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' data.txt`) # create matrix of IPs 24 | IPSTRING=`for val in "${IPArray[@]}"; do echo -n "$val,"; done` # flatten IPs into comma-delimited string 25 | echo "$HASH,$URL,$IPSTRING" >> output.csv # save the data 26 | sleep 15 27 | done 28 | 29 | 30 | # Cleanup 31 | rm data.txt 32 | -------------------------------------------------------------------------------- /Research/ioc-intel.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | # This script performs some quick lookups against a list of ip address 4 | # or FQDN IOCs and prints to stdout 5 | # 6 | # Pre-requisite: 7 | # a configured CIF client with access to a CIF repository 8 | # https://code.google.com/p/collective-intelligence-framework/ 9 | # 10 | # nping (nmap.com/nping) if you want to be noisy 11 | # 12 | # Actions: 13 | # name lookup 14 | # CYMRU ASN network lookup 15 | # cif query 16 | # 17 | # Usage: ./ioc-intel.sh 18 | # 19 | # TODO: 20 | # - better output handling, rather than just stdout 21 | # - add command-line options for more advanced functions 22 | # - filter out home domains 23 | # - add command-line option for filtering 24 | 25 | # BEGIN SCRIPT 26 | # create the work list from the specified filed and ignore RFC1918 IPs 27 | LIST=`egrep -v '(^127\.0\.0\.1)|(^192\.168)|(^10\.)|(^172\.1[6-9])|(^172\.2[0-9])|(^172\.3[0-1])' $1` 28 | 29 | echo "start time" 30 | date 31 | # perform the lookups 32 | for ioc in $LIST; do 33 | echo " " 34 | echo "processing IOC $ioc" 35 | echo "--------------------------------" 36 | # name lookup 37 | echo "host resolution" 38 | nslookup $ioc 8.8.8.8 |egrep -i 'Name|Address' 39 | # CYMRU lookup 40 | echo "CYMRU ASN lookup" 41 | whois -h whois.cymru.com $ioc 42 | # CIF lookup 43 | echo "query CIF database for indications of compromise" 44 | cif -q $ioc 45 | echo "check for host availability on port 80" 46 | #this test is very noisy and should only be used when stealth is not required 47 | nping --tcp-connect -p 80 --flags rst -c 1 $ioc 48 | echo " " 49 | done 50 | 51 | echo "finish time" 52 | date 53 | 54 | # fin 55 | -------------------------------------------------------------------------------- /Research/reverselook.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # reads a list specified on the command line and looks up 3 | # each hostname or IP address 4 | LIST=`grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' $1` 5 | for i in $LIST 6 | do nslookup $i 7 | done -------------------------------------------------------------------------------- /Research/twitter-checkmydump.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import os, sys 4 | import tweepy 5 | # import configparser #todo 6 | import requests 7 | import datetime as dt 8 | 9 | # How-to 10 | usage = "./twitter-checkmydump.py retrieves recent posts by the CheckMyDump twitter account \ 11 | and drops them into a directory, creating a directory based on the date the script \ 12 | is executed. \n \n \ 13 | ./twitter-checkmydump.py /path/to/destination" 14 | 15 | 16 | 17 | # Twitter keys 18 | consumer_key = "HXZSTg9yesNCmO5GdIUNLw" 19 | consumer_secret = "jz2ElWSProgXIR7Rqot23UPKACbiLOQ26tMwMO8mP44" 20 | access_token = "15318975-L84zQeUMsKITMPp6drn4fTh5ygFuopTwb8BTZQcU" 21 | access_token_secret = "dHLQkpfOa2vaDW6SMkw1obr2oFMpVVelseLi9H4Ods" 22 | 23 | # Check for required 24 | 25 | # Import the data directory from the command line 26 | datadir = sys.argv[1] 27 | 28 | # Get today's date for file naming reasons 29 | def date(): 30 | today = dt.datetime.today() 31 | return today.strftime("%Y%m%d") 32 | 33 | def createdir(date): 34 | if not os.path.exists(date): 35 | os.makedirs( 36 | 37 | # Function to extract tweets 38 | def get_tweets(username): 39 | 40 | # Authorization to consumer key and consumer secret 41 | auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 42 | # Access to user's access key and access secret 43 | auth.set_access_token(access_token, access_token_secret) 44 | # Calling api 45 | api = tweepy.API(auth) 46 | 47 | # How many tweets to extract 48 | number_of_tweets=20 49 | tweets = api.user_timeline(screen_name=username) 50 | 51 | # Create a list to store the tweets 52 | tmp=[] 53 | 54 | # create array of tweet information: username, 55 | # tweet id, date/time, text 56 | tweets_for_csv = [tweet.text for tweet in tweets] # CSV file created 57 | for j in tweets_for_csv: 58 | tmp.append(j) # append tweets to the list 59 | i = 1 60 | for t in tmp: 61 | # print(t) # debug 62 | x,y = t.split(':', 1) 63 | r = requests.get(y) 64 | filename = str(i) + '.txt' 65 | dump_file = open(filename, 'w') 66 | dump_file.write(r.text) 67 | i += 1 68 | 69 | 70 | 71 | 72 | # Driver code 73 | if __name__ == '__main__': 74 | 75 | # Here goes the twitter handle for the user 76 | # whose tweets are to be extracted. 77 | get_tweets("checkmydump") 78 | -------------------------------------------------------------------------------- /Research/twitter-leakedcreds.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import time 4 | from getpass import getpass 5 | from textwrap import TextWrapper 6 | 7 | import tweepy 8 | 9 | 10 | class StreamWatcherListener(tweepy.StreamListener): 11 | 12 | status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ') 13 | 14 | def on_status(self, status): 15 | try: 16 | print self.status_wrapper.fill(status.text) 17 | print '\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source) 18 | except: 19 | # Catch any unicode errors while printing to console 20 | # and just ignore them to avoid breaking application. 21 | pass 22 | 23 | def on_error(self, status_code): 24 | print 'An error has occured! Status code = %s' % status_code 25 | return True # keep stream alive 26 | 27 | def on_timeout(self): 28 | print 'Snoozing Zzzzzz' 29 | 30 | 31 | def main(): 32 | # Prompt for login credentials and setup stream object 33 | # consumer_key = raw_input('Consumer Key: ') 34 | # consumer_secret = getpass('Consumer Secret: ') 35 | # access_token = raw_input('Access Token: ') 36 | # access_token_secret = getpass('Access Token Secret: ') 37 | 38 | consumer_key = "HXZSTg9yesNCmO5GdIUNLw" 39 | consumer_secret = "jz2ElWSProgXIR7Rqot23UPKACbiLOQ26tMwMO8mP44" 40 | access_token = "15318975-L84zQeUMsKITMPp6drn4fTh5ygFuopTwb8BTZQcU" 41 | access_token_secret = "dHLQkpfOa2vaDW6SMkw1obr2oFMpVVelseLi9H4Ods" 42 | 43 | 44 | 45 | auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret) 46 | auth.set_access_token(access_token, access_token_secret) 47 | stream = tweepy.Stream(auth, StreamWatcherListener(), timeout=None) 48 | 49 | # Prompt for mode of streaming 50 | valid_modes = ['sample', 'filter'] 51 | while True: 52 | mode = raw_input('Mode? [sample/filter] ') 53 | if mode in valid_modes: 54 | break 55 | print 'Invalid mode! Try again.' 56 | 57 | if mode == 'sample': 58 | stream.sample() 59 | 60 | elif mode == 'filter': 61 | # follow_list = raw_input('Users to follow (comma separated): ').strip() 62 | follow_list = "checkmydump" 63 | # track_list = raw_input('Keywords to track (comma seperated): ').strip() 64 | if follow_list: 65 | follow_list = [u for u in follow_list.split(',')] 66 | userid_list = [] 67 | username_list = [] 68 | 69 | for user in follow_list: 70 | if user.isdigit(): 71 | userid_list.append(user) 72 | else: 73 | username_list.append(user) 74 | 75 | for username in username_list: 76 | user = tweepy.API().get_user(username) 77 | userid_list.append(user.id) 78 | 79 | follow_list = userid_list 80 | else: 81 | follow_list = None 82 | if track_list: 83 | track_list = [k for k in track_list.split(',')] 84 | else: 85 | track_list = None 86 | print follow_list 87 | stream.filter(follow_list, track_list) 88 | 89 | 90 | if __name__ == '__main__': 91 | try: 92 | main() 93 | except KeyboardInterrupt: 94 | print '\nGoodbye!' 95 | 96 | -------------------------------------------------------------------------------- /VulnMgmt/README.org: -------------------------------------------------------------------------------- 1 | #+TITLE: Description of the tools in this directory 2 | 3 | * Requirements 4 | You will need to have the following modules installed: 5 | 6 | ** Python 7 | The scripts are being converted from 2.7 to 3.x (tested on 3.4), so you will need to have both installed 8 | 9 | ** Python modules 10 | - python-redmine 11 | - json 12 | - socket 13 | 14 | * General Information 15 | 16 | ** Preferences File 17 | The scripts use a preferences file to store site-specific information such as server and user parameters. 18 | 19 | *** Format 20 | ## Configure your environment through preferences file 21 | # load prefs from ~/.incmgmt/prefs.txt 22 | # The parameters should be in the following format 23 | # DO NOT use comments or blank lines. 24 | # Redmine Project 25 | # Redmine URL 26 | # Redmine API key 27 | # ServiceNow URL 28 | # ServiceNow username 29 | # Servicenow password 30 | # severity level 31 | # OpenVAS XML report file 32 | # Preamble: general info you want included in every ticket created 33 | 34 | 35 | *** TODO Make the prefs file a "real" Config file 36 | Use Configparser to handle a "real" preferences file 37 | https://docs.python.org/3.4/library/configparser.html 38 | 39 | 40 | ** Other files 41 | - ticketlog.csv: A log of all tickets created in both systems 42 | - opentix.csv: A log of active (read: open) tickets. Generated from ticketlog.csv if it does not already exist 43 | ** TODO General workflow 44 | For the scripts in this repository to make sense, I believe it would be helpful to provide a description of my workflow for vulnerability analysis and management. However, that will have to wait a bit before I can type all that out. :-/ 45 | 46 | *** TODO use a "real" preferences file 47 | The current preferences file is a simple text file that is very sensitive to parameters being on the correct line. This needs to be changed into a key:value pairing style of preferences that are read and used across the various scripts. 48 | 49 | * Vuln-tickets.py 50 | ** General working of the script 51 | This is an ugly script, so just bear with me on this. In my environment, I have a need to create ticket for identified vulnerabilies on two different systems. The Redmine is for tracking as well as change control, so it gets more information, and the Service Now is for the operational teams to perform the work. 52 | 53 | The script will create tickets for all issues in the exported report that are scored at or above the CVSS score specified on line 7 of the preferences file. To avoid creating duplicate tickets for the same issue, teh analyst can create overrides in OpenVAS to adjust the resultant CVSS scoring or "hide" the detections for a temporary time duration. The script checks for the existence of the "new_severity" tag in the XML report, which is created if the identification has been adjusted through the use of an override. 54 | 55 | ** Redmine specifics 56 | ** ServiceNow specifics 57 | In my implementation, we have a high-level category for vulnerability management, and then subcategories for the type of system identified with the vulnerabilty. As such, the Vulnerability Management category is hard-coded in the script 58 | * TODO ov_host-metrics.py 59 | This script analyzes a directory of exported XML reports from OpenVAS tasks and extracts data relevant to perform some metrics analysis. 60 | 61 | Also, because the Vuln-tickets.py script is "live" and creates work tickets on production systems, I use this to perform a quick sanity check on a report prior to creating the tickets. 62 | 63 | 64 | * TODO redmine_collect-issues.py 65 | Queries a redmine server for issues created in a specific project and generates some basic data around those tickets for analysis. 66 | * TODO reconcile_tickets.py 67 | Since I am in the unenviable position of having to support multiple ticketing systems, this script checks the status of the ticket in the system most used by the operational teams and closes it in the security tracking system if it has been marked complete in the other system. 68 | ** Getting Started 69 | This script relies upon the 'ticketlog.csv' file that is placed in your ~/.incmgmt directory when running Vuln-tickets.py. Before running the first time, make a copy of ticketlog.csv to opentix.csv with the following command: 70 | 71 | cp ~/.incmgmt/ticketlog.csv ~/.incmgmt/opentix.csv 72 | 73 | To preserve processing time, the script will destroy opentix.csv each time the script is run and then recreate it with only tickets that remain open in Service Now. Do not worry if this gets lost, as it can always be re-created by copying ticketlog.csv. The first time it runs, however, will be longer as the script eliminates the closed tickets from the open list. 74 | 75 | In the future, the script will create this file automatically. If it does not find opentix.csv, it will create the file based on information pulled from ticketlog.csv. (if it can't find that, it will error out. I can't do everything for you!) This file is a subset of ticketlog. 76 | 77 | -------------------------------------------------------------------------------- /VulnMgmt/Vuln-tickets.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # This takes an XML report extracted from an OpenVAS VA scanner and 4 | # creates issue tickets on ServiceNow and Redmine systems for tracking 5 | # purposes. 6 | # 7 | # Most parameters are specified in the 'ov_prefs.txt' file, however, 8 | # the XML report file may be specified on the command line. If 9 | # specified this way, the script will ignore that line in the 10 | # preferences file, however, the line must still exist! 11 | 12 | # version 0.5 13 | 14 | #modules 15 | import os 16 | import sys 17 | import csv 18 | import json 19 | import socket 20 | import requests 21 | from redmine import Redmine 22 | import xml.etree.ElementTree as ET 23 | 24 | ## Configure your environment through preferences file 25 | # load prefs from ~/.incmgmt/prefs.txt 26 | # The parameters should be in the following format 27 | # DO NOT use comments or blank lines. 28 | # Redmine Project 29 | # Redmine URL 30 | # Redmine API key 31 | # ServiceNow URL 32 | # ServiceNow username 33 | # Servicenow password 34 | # severity level 35 | # OpenVAS XML report file 36 | # Preamble: general info you want included in every ticket created 37 | 38 | os.chdir(os.path.expanduser("~") + "/.incmgmt/") 39 | prefs = [] 40 | for line in open('ov_prefs.txt'): 41 | prefs.append(line) 42 | redmine_project = prefs[0].rstrip() 43 | redmine_server = prefs[1].rstrip() 44 | redmine_key = prefs[2].rstrip() 45 | sn_server = prefs[3].rstrip() 46 | user = prefs[4].rstrip() 47 | pwd = prefs[5].rstrip() 48 | severity_filter = prefs[6].rstrip() 49 | if len(sys.argv) == 1: # test for command line arguments 50 | ov_report = prefs[7].rstrip() 51 | else: 52 | ov_report = sys.argv[1] 53 | preamble = prefs[8].rstrip() 54 | 55 | # Define service now headers 56 | headers = {"Content-Type":"application/json","Accept":"application/json"} 57 | 58 | 59 | # Input the vulnerability report and parse the XML 60 | root = ET.parse(ov_report) 61 | 62 | ## determine criticality factors 63 | # impact and urgency are used for Service Now 64 | # priority is used for Redmine 65 | def criticality(cvss): 66 | global impact 67 | global urgency 68 | global priority 69 | if float(cvss) > 7: 70 | impact = 2 71 | urgency = 1 72 | priority = 5 73 | elif float(cvss) < 4: 74 | impact = 3 75 | urgency = 3 76 | priority = 3 77 | else: 78 | impact = 2 79 | urgency = 2 80 | priority = 4 81 | return impact, urgency, priority 82 | 83 | def reverse_lookup(ip): 84 | try: 85 | hostname = socket.gethostbyaddr(ip)[0] 86 | except socket.herror: 87 | hostname = " " 88 | return hostname 89 | 90 | 91 | ## determine category 92 | """ Redmine reference 93 | 0 nothing 94 | 53 Database 95 | 54 Networking 96 | 56 Server - Unix 97 | 55 Server - Windows 98 | 57 Web Application """ 99 | 100 | ## Function to categorize the issue for all ticketing systems 101 | # categoy is used for redmine, and subcategory is used for 102 | # ServiceNow because it has a default high-level category for vulns 103 | def categorize(family): 104 | if family == "Web application abuses" or "Web Servers": 105 | category = 57 106 | subcategory = "Internal Application" 107 | elif family == "Databases": 108 | category = 53 109 | subcategory = "Internal Application" 110 | elif family == "General": 111 | category = 56 112 | subcategory = "UNIX" 113 | elif "CentOS" in family: 114 | category = 56 115 | subcategory = "UNIX" 116 | elif "Windows" in family: 117 | category = 55 118 | subcategory = "Windows" 119 | else: 120 | category = 0 121 | subcategory = " " 122 | return category, subcategory 123 | 124 | #Specify Redmine server params 125 | redmine = Redmine(redmine_server, requests={'verify': False}, key=redmine_key, version='2.5.1') 126 | 127 | def redmine_issue(priority, subject, body, category): 128 | ## Create an issue in Redmine to track the vulnerability 129 | # and return information regarding the created ticket 130 | new_issue = redmine.issue.create(project_id = redmine_project, \ 131 | priority_id = priority, subject = subject, description = body,\ 132 | tracker_id=19, category_id = category) 133 | redmine_issue_id = str(new_issue.id) 134 | redmine_url = redmine_server + "/issues/" + redmine_issue_id 135 | print("redmine ticket created") 136 | return redmine_url, redmine_issue_id 137 | 138 | def sn_issue(subject, redmine_url, subcategory, impact, urgency): 139 | ## Create the incident in ServiceNow 140 | # Construct the incident JSON object 141 | incident_data = '{' + \ 142 | '"short_description":' + '"' + subject + '",' + \ 143 | '"description":' + '"For more information, see: ' + redmine_url + '",' + \ 144 | '"u_category":' + '"Vulnerability Management",' + \ 145 | '"u_subcategory":' + '"' + subcategory + '",' + \ 146 | '"impact":' + '"' + str(impact) + '",' + \ 147 | '"urgency":' + '"' + str(urgency) + '",' + \ 148 | '"contact_type":"Alert"' + '}' 149 | # Create the incident on the Service Now system 150 | response = requests.post(sn_server, auth=(user, pwd), \ 151 | headers=headers, data=incident_data) 152 | # Capture the ticket number and unique identifier 153 | sn_ticket = response.json()['result']['number'] 154 | sys_id = response.json()['result']['sys_id'] 155 | print("service now ticket created") 156 | return sn_ticket, sys_id 157 | 158 | # Update the Service Now ticket with a comment 159 | def sn_update(sys_id, comment): 160 | sn_url = sn_server + '/' + sys_id # REST URL for the ticket 161 | update = requests.patch(sn_url, auth=(user, pwd), headers=headers,\ 162 | data='{"comments":"' + comment +'"}') 163 | if update.status_code != 200: 164 | print('Status:', response.status_code, 'Headers:',\ 165 | response.headers, 'Error Response:',response.json()) 166 | exit() 167 | print("Updated Service Now ticket" + " " + sys_id) # user output 168 | 169 | 170 | # checks for a ticket with the exact same "subject" or "short 171 | # description" on the Redmine system. 172 | def CheckTickets(subject): 173 | i = 0 174 | project = redmine.project.get(redmine_project) 175 | while i < len(project.issues): 176 | # print("Checking: " + str(project.issues[i])) 177 | if str(project.issues[i]) == subject: 178 | incident_id = project.issues[i].id 179 | opentix_log = csv.reader(open('opentix.csv')) 180 | # Generate a dictionary of the known open tickets. This 181 | # should really be performed at the beginning so it 182 | # doesn't run everytime, but meh! 183 | tix_dict = {} 184 | for row in opentix_log: 185 | tix_dict[row[0]]=row[2] 186 | sn_sysid = tix_dict[str(incident_id)] 187 | print("Found match: " + tix_dict[str(incident_id)] + " " + str(project.issues[i])) # debug 188 | return sn_sysid # return a value for test 189 | i += 1 190 | return None # if the test fails, return nothing 191 | 192 | 193 | def log(redmine_issue_id, sn_ticket, sys_id, redmine_url): 194 | # Write log file of tickets created 195 | ticket_log = open('ticketlog.csv','a') 196 | opentix_log = open('opentix.csv','a') 197 | ticket_log.write(redmine_issue_id + ',' + sn_ticket + ',' + \ 198 | sys_id + ',' + redmine_url + ',' + '\n') 199 | opentix_log.write(redmine_issue_id + ',' + sn_ticket + ',' + \ 200 | sys_id + '\n') 201 | ticket_log.close() 202 | opentix_log.close() 203 | 204 | ## Main program. Extract the data, then call functions 205 | # Extract elements from the XML for use in creating the ticket 206 | for result in root.findall("./report/results/result"): 207 | # only process vulnerabilities of a certain severity or higher 208 | if result.find('overrides/override/new_severity') is not None: 209 | cvss = result.find('overrides/override/new_severity').text 210 | else: 211 | cvss = result.find('severity').text 212 | if float(cvss) >= float(severity_filter): 213 | # Extract the elements from the XML 214 | host_ip = result.find('host').text 215 | severity = result.find('severity').text 216 | if result.find('description').text is not None: 217 | description = result.find('description').text 218 | else: 219 | description = "no extended description available" 220 | short_desc = result.find('nvt/name').text 221 | cvss = result.find('nvt/cvss_base').text 222 | cve = result.find('nvt/cve').text 223 | system_type = result.find('nvt/family') 224 | # get some additional info based on extracted values 225 | hostname = reverse_lookup(host_ip) # perform name lookup 226 | impact, urgency, priority = criticality(severity) 227 | category, subcategory = categorize(system_type) 228 | full_desc = result.find('nvt/tags').text 229 | criticality(cvss) # calc criticality levels 230 | subject = short_desc + " detected on " + hostname + " " + host_ip 231 | # Create the body of the ticket by combining multiple elements from 232 | # the report file. 233 | body = preamble + "\n \n" + full_desc + "\n \n CVEs:" + cve +\ 234 | "\n \n Description: \n" + description 235 | # Check for currently active ticket for same issue. This 236 | previous = CheckTickets(subject) 237 | # Create a new ticket if one does not exist. 238 | if previous is not None: 239 | sn_update(previous, "Please provide an update for this ticket") 240 | else: 241 | # create the issues in redmine and return info 242 | redmine_url, redmine_issue_id = redmine_issue(priority, \ 243 | subject, body, category) 244 | # create the issues in ServiceNow and return info 245 | sn_ticket, sys_id = sn_issue(subject, redmine_url, \ 246 | subcategory, impact, urgency) 247 | log (redmine_issue_id, sn_ticket, sys_id, redmine_url) 248 | 249 | -------------------------------------------------------------------------------- /VulnMgmt/ip_expand.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python2.7 2 | 3 | # Takes a list of CIDR blocks (from the file 'cidr_list.txt' in /tmp), 4 | # calculates every IP address contained within those blocks, saves 5 | # each individual IP to a file (for use in other programs) and also 6 | # spits out the total number of blocks and total number of addresses 7 | # to STDOUT 8 | 9 | 10 | #import os 11 | import ipcalc # requires Python 2.x 12 | 13 | # specify resources 14 | cidr_list = open('/tmp/cidr_list.txt', 'r') # list of blocks 15 | ip_list = open('/tmp/ip_list.txt', 'w') # all the IPs 16 | ip_count = 0 # tally the IPs 17 | cidr_count = 0 # tally the blocks 18 | 19 | 20 | def listIPs(cidr): 21 | block_ips = 0 22 | for ip in ipcalc.Network(cidr): 23 | block_ips += 1 24 | ip_list.write(str(ip) + '\n') 25 | return block_ips 26 | 27 | for block in cidr_list: 28 | print("Processing " + block) # some output for the user 29 | cidr_count += 1 30 | block_ips = listIPs(block.strip()) 31 | ip_count = ip_count + block_ips 32 | 33 | ip_list.close() 34 | cidr_list.close() 35 | 36 | print("\n \n") 37 | print("Evaluated CIDR blocks: " + str(cidr_count) + '\n') 38 | print("Total number of addresses: " + str(ip_count)) 39 | print("List of addresses saved to /tmp/ip_list.txt") 40 | 41 | -------------------------------------------------------------------------------- /VulnMgmt/ov_host-metrics.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # Reads from a dir of OpenVAS XML reports and extracts summary information 4 | # Version 0.0.0.0.1 i.e. work in progress 5 | 6 | #modules 7 | import os 8 | import glob 9 | import socket 10 | import xml.etree.ElementTree as ET 11 | 12 | #data_dir = 'Directory where Data exists' 13 | data_dir = '/media/sf_Aruba/InfoSec/Metrics/Data/OpenVAS/External' 14 | # 15 | months = ['2014-09', '2014-10', '2014-11', '2015-01', '2015-02', '2015-03'] 16 | #severity_filter = 2 # filter the data; 0 = all 17 | severities = {'All':0, 'Low':2, 'Medium':4, 'High':7 } 18 | # Read the reports 19 | os.chdir(data_dir) 20 | 21 | # Function to address the reports on a monthly basis. Reports must be 22 | # named "report-YYYY-MM" until I stop being lazy and fix that issue 23 | def get_reports(month): 24 | period = 'report-' + month + '-*.xml' 25 | return glob.glob(period) 26 | 27 | # In the future, I need to construct a pd.Dataframe from the data. 28 | #But that is hard and I don't have the time to do that right now, so 29 | #brute force, it is!! 30 | # columns = ['cvss', 'host_ip', 'system_type', 'cve'] #pandas.df cols 31 | 32 | def reverse_lookup(ip): 33 | try: 34 | hostname = socket.gethostbyaddr(ip)[0] 35 | except socket.herror: 36 | hostname = " " 37 | return hostname 38 | 39 | # Process an XML-formatted report 40 | def parse_report(report, severity_filter): 41 | vulns = 0 42 | root = ET.parse(report) 43 | for result in root.findall("./report/results/result"): 44 | # only process vulnerabilities of a certain severity or higher 45 | if result.find('overrides/override/new_severity') is not None: 46 | cvss = result.find('overrides/override/new_severity').text 47 | else: 48 | cvss = result.find('nvt/cvss_base').text 49 | if float(cvss) >= severity_filter: 50 | # Extract the elements from the XML 51 | host_ip = result.find('host').text 52 | severity = result.find('severity').text # not used? 53 | short_desc = result.find('nvt/name').text 54 | cvss = result.find('nvt/cvss_base').text 55 | cve = result.find('nvt/cve').text 56 | system_type = result.find('nvt/family') 57 | full_desc = result.find('nvt/tags').text 58 | vulns += 1 59 | hosts.append(host_ip) 60 | # print(host_ip, short_desc) # debug 61 | return vulns, hosts 62 | 63 | 64 | def uniqify(things): 65 | return list(set(things)) 66 | 67 | for month in months: 68 | reports = get_reports(month) 69 | print("Reporting period: " + month) 70 | for i in severities: 71 | total = 0 72 | hosts = [] 73 | print("Severity: " + i) 74 | for report in reports: 75 | total_add, hosts_add = parse_report(report, severities[i]) 76 | total += total_add 77 | hosts = hosts + hosts_add 78 | print("total identified vulns: " + str(total)) 79 | print("total unique hosts: " + str(len(uniqify(hosts)))) 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /VulnMgmt/prefs.sample: -------------------------------------------------------------------------------- 1 | incident_management 2 | https://redmine.company.com 3 | abcdef1234567890abcdef1234567890fedcba91 4 | https://company.service-now.com/api/now/table/incident 5 | ServiceNowWorkerBee 6 | SN_Password123 7 | 7.5 8 | /home/username/Documents/ov_reports 9 | This issue has been created pursuant to regular security and system scanning. 10 | -------------------------------------------------------------------------------- /VulnMgmt/reconcile_tickets.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # This script checks the status of the tickets in Redmine and 4 | # ServiceNow, closing the Redmine ticket if the ServiceNow ticket has 5 | # been fully closed. 6 | # Version 0.5 7 | 8 | #modules 9 | import requests 10 | import os 11 | import csv 12 | import json 13 | from redmine import Redmine 14 | 15 | # set working directory for prefs and log files 16 | os.chdir(os.path.expanduser("~") + "/.incmgmt/") 17 | 18 | # See Readme for the preferences file parameters 19 | prefs = open('ov_prefs.txt','r') 20 | redmine_project = prefs.readline().rstrip() 21 | redmine_server = prefs.readline().rstrip() 22 | redmine_key = prefs.readline().rstrip() 23 | sn_server = prefs.readline().rstrip() 24 | user = prefs.readline().rstrip() 25 | pwd = prefs.readline().rstrip() 26 | severity_filter = prefs.readline().rstrip() 27 | ov_report = prefs.readline().rstrip() 28 | preamble = prefs.readline().rstrip() 29 | prefs.close() 30 | 31 | # Turn off the SSL certificate warnings. This is a less-than-stellar 32 | # idea. TODO: implement using the certifi package to verify the SSL 33 | # certificate 34 | requests.packages.urllib3.disable_warnings() 35 | 36 | ## More prefs. Man, I need to create a proper prefs file 37 | # identify the Redmine server parameters as an object 38 | redmine = Redmine(redmine_server, requests={'verify': False}, \ 39 | key=redmine_key, version='2.5.1') 40 | 41 | ticketlogfile = 'ticketlog.csv' #log file from Vuln-tickets.py 42 | ticketlogtmp = open('ticketlogtmp.csv','w') # temp file for open tix 43 | 44 | # CheckLogFile looks for a file called opentix.csv containing the 45 | # current list of open tickets needed for processing. See the README 46 | 47 | def CheckLogFile(): 48 | if os.path.isfile(ticketlogfile): # check for ticketlog 49 | if os.path.isfile('opentix.csv'): # check for the file 50 | print("opentix file exists: checking tickets...") 51 | return None 52 | else: 53 | CreateLogFile() 54 | else: 55 | print("You need to run Vuln-tickets.py prior to running this") 56 | exit() 57 | 58 | def CreateLogFile(): 59 | print("Creating opentix.csv for tracking open tickets!") 60 | with open(ticketlogfile) as ticketlog: 61 | fields = ['rm_ticket', 'sn_ticket', 'sys_id', 'rm_url'] 62 | reader = csv.DictReader(ticketlog, fieldnames=fields) 63 | opentixfile = open('opentix.csv','w') 64 | for row in reader: # read in the ticket information 65 | rm_ticket = row['rm_ticket'] 66 | sn_ticket = row['sn_ticket'] 67 | sys_id = row['sys_id'] 68 | opentixfile.write(rm_ticket + ',' + sn_ticket + \ 69 | ',' + sys_id + '\n') 70 | ticketlog.close() 71 | opentixfile.close() 72 | 73 | def WriteActive(rm_ticket, sn_ticket, sys_id): #maintains active tickets 74 | ticketlogtmp.write(rm_ticket + "," + sn_ticket + "," \ 75 | + sys_id + "\n") 76 | 77 | def CheckSNStatus(rm_ticket, sn_ticket, sys_id): 78 | headers = {"Content-Type":"application/json", \ 79 | "Accept":"application/json"} 80 | sn_url = sn_server + '/' + sys_id 81 | incident = requests.get(sn_url, auth=(user, pwd), \ 82 | headers = headers) 83 | if incident.status_code != 200: # error handling for bad response 84 | print('Status:', incident.status_code, 'Headers:', incident.headers, 'Error Response:',incident.json()) 85 | print("Error in retrieving ServiceNow ticket. See above") 86 | exit() 87 | else: 88 | print("ServiceNow status is: " + \ 89 | str(incident.json()['result']['u_status'])) 90 | if incident.json()['result']['u_status'] != 'Closed': 91 | print("Ticket still open, writing to opentix") 92 | WriteActive(rm_ticket, sn_ticket, sys_id) 93 | return None 94 | else: 95 | CheckRMStatus(rm_ticket, sn_ticket, sys_id) 96 | return None 97 | 98 | # CheckRMStatus is only called if the ServiceNow ticket is closed. 99 | # If it is, then this runs to also close the ticket in Redmine. 100 | def CheckRMStatus(rm_ticket, sn_ticket, sys_id): 101 | incident = redmine.issue.get(rm_ticket) # get ticket info 102 | status = incident.status # capture the status 103 | print("Redmine status is: " + str(status)) # output for user 104 | if str(status) != 'Closed': 105 | # Check the status of the ticket and close if still open 106 | print("The Redmine Ticket is still open. Closing now.") 107 | UpdateRedmineTicket(rm_ticket, sn_ticket) 108 | print("Writing to opentix for a double-check next run") 109 | WriteActive(rm_ticket, sn_ticket, sys_id) 110 | return None 111 | else: 112 | print("Ticket already closed in Redmine. Removing.") 113 | return None 114 | 115 | def UpdateRedmineTicket(ticket, sn_ticket): 116 | updatemsg = "ServiceNow ticket " + sn_ticket + " has been marked done" 117 | redmine.issue.update(ticket, status_id = 5, \ 118 | notes = updatemsg) 119 | return None 120 | 121 | 122 | # Main 123 | CheckLogFile() # Check/Create ACTIVE tickets logfile 124 | with open('opentix.csv') as ticketlog: 125 | fields = ['rm_ticket', 'sn_ticket', 'sys_id', 'rm_url'] 126 | ticketdata = csv.DictReader(ticketlog, fieldnames=fields) 127 | # for each ServiceNow Ticket Number, check the status 128 | for row in ticketdata: # read in the ticket information 129 | rm_ticket = row['rm_ticket'] 130 | sn_ticket = row['sn_ticket'] 131 | sys_id = row['sys_id'] 132 | print(rm_ticket, sn_ticket) # output current work for user 133 | CheckSNStatus(rm_ticket, sn_ticket, sys_id) 134 | 135 | ticketlogtmp.close() 136 | os.rename('ticketlogtmp.csv','opentix.csv') 137 | --------------------------------------------------------------------------------