File size: 16,849 Bytes
5980447
1
2
{"repo": "mlsecproject/combine", "pull_number": 103, "instance_id": "mlsecproject__combine-103", "issue_numbers": "", "base_commit": "d662493af9f6ee7bc36c5509c277f93980009bec", "patch": "diff --git a/baler.py b/baler.py\n--- a/baler.py\n+++ b/baler.py\n@@ -1,21 +1,21 @@\n import ConfigParser\n-import csv\n import datetime as dt\n import gzip\n import json\n+import logging\n import os\n-import sys\n+import re\n import requests\n+import sys\n import time\n-import re\n-from Queue import Queue\n+import unicodecsv\n import threading\n from logger import get_logger\n-import logging\n-\n+from Queue import Queue\n \n logger = get_logger('baler')\n \n+\n def tiq_output(reg_file, enr_file):\n     config = ConfigParser.SafeConfigParser()\n     cfg_success = config.read('combine.cfg')\n@@ -43,8 +43,8 @@ def tiq_output(reg_file, enr_file):\n     outbound_data = [row for row in reg_data if row[2] == 'outbound']\n \n     try:\n-        bale_reg_csvgz(inbound_data, os.path.join(tiq_dir, 'raw', 'public_inbound', today+'.csv.gz'))\n-        bale_reg_csvgz(outbound_data, os.path.join(tiq_dir, 'raw', 'public_outbound', today+'.csv.gz'))\n+        bale_reg_csvgz(inbound_data, os.path.join(tiq_dir, 'raw', 'public_inbound', today + '.csv.gz'))\n+        bale_reg_csvgz(outbound_data, os.path.join(tiq_dir, 'raw', 'public_outbound', today + '.csv.gz'))\n     except:\n         pass\n \n@@ -52,8 +52,8 @@ def tiq_output(reg_file, enr_file):\n     outbound_data = [row for row in enr_data if row[2] == 'outbound']\n \n     try:\n-        bale_enr_csvgz(inbound_data, os.path.join(tiq_dir, 'enriched', 'public_inbound', today+'.csv.gz'))\n-        bale_enr_csvgz(outbound_data, os.path.join(tiq_dir, 'enriched', 'public_outbound', today+'.csv.gz'))\n+        bale_enr_csvgz(inbound_data, os.path.join(tiq_dir, 'enriched', 'public_inbound', today + '.csv.gz'))\n+        bale_enr_csvgz(outbound_data, os.path.join(tiq_dir, 'enriched', 'public_outbound', today + '.csv.gz'))\n     except:\n         pass\n \n@@ -64,7 +64,7 @@ def bale_reg_csvgz(harvest, output_file):\n     \"\"\" bale the data as a gziped csv file\"\"\"\n     logger.info('Output regular data as GZip CSV to %s' % output_file)\n     with gzip.open(output_file, 'wb') as csv_file:\n-        bale_writer = csv.writer(csv_file, quoting=csv.QUOTE_ALL)\n+        bale_writer = unicodecsv.writer(csv_file, quoting=unicodecsv.QUOTE_ALL)\n \n         # header row\n         bale_writer.writerow(('entity', 'type', 'direction', 'source', 'notes', 'date'))\n@@ -75,7 +75,7 @@ def bale_reg_csv(harvest, output_file):\n     \"\"\" bale the data as a csv file\"\"\"\n     logger.info('Output regular data as CSV to %s' % output_file)\n     with open(output_file, 'wb') as csv_file:\n-        bale_writer = csv.writer(csv_file, quoting=csv.QUOTE_ALL)\n+        bale_writer = unicodecsv.writer(csv_file, quoting=unicodecsv.QUOTE_ALL)\n \n         # header row\n         bale_writer.writerow(('entity', 'type', 'direction', 'source', 'notes', 'date'))\n@@ -86,112 +86,117 @@ def bale_enr_csv(harvest, output_file):\n     \"\"\" output the data as an enriched csv file\"\"\"\n     logger.info('Output enriched data as CSV to %s' % output_file)\n     with open(output_file, 'wb') as csv_file:\n-        bale_writer = csv.writer(csv_file, quoting=csv.QUOTE_ALL)\n+        bale_writer = unicodecsv.writer(csv_file, quoting=unicodecsv.QUOTE_ALL)\n \n         # header row\n         bale_writer.writerow(('entity', 'type', 'direction', 'source', 'notes', 'date', 'asnumber', 'asname', 'country', 'host', 'rhost'))\n         bale_writer.writerows(harvest)\n \n+\n def bale_enr_csvgz(harvest, output_file):\n     \"\"\" output the data as an enriched gziped csv file\"\"\"\n     logger.info('Output enriched data as GZip CSV to %s' % output_file)\n     with gzip.open(output_file, 'wb') as csv_file:\n-        bale_writer = csv.writer(csv_file, quoting=csv.QUOTE_ALL)\n+        bale_writer = unicodecsv.writer(csv_file, quoting=unicodecsv.QUOTE_ALL)\n \n         # header row\n         bale_writer.writerow(('entity', 'type', 'direction', 'source', 'notes', 'date', 'asnumber', 'asname', 'country', 'host', 'rhost'))\n         bale_writer.writerows(harvest)\n \n-def bale_CRITs_indicator(base_url,data,indicator_que):\n+\n+def bale_CRITs_indicator(base_url, data, indicator_que):\n     \"\"\" One thread of adding indicators to CRITs\"\"\"\n     while not indicator_que.empty():\n-        indicator=indicator_que.get()\n+        indicator = indicator_que.get()\n         if indicator[1] == 'IPv4':\n             # using the IP API\n-            url=base_url+'ips/'\n-            data['add_indicator']=\"true\"\n-            data['ip']=indicator[0]\n-            data['ip_type']='Address - ipv4-addr'\n-            data['reference']=indicator[3]\n+            url = base_url + 'ips/'\n+            data['add_indicator'] = \"true\"\n+            data['ip'] = indicator[0]\n+            data['ip_type'] = 'Address - ipv4-addr'\n+            data['reference'] = indicator[3]\n             # getting the source automatically:\n-            source=re.findall(r'\\/\\/(.*?)\\/',data['reference'])\n+            source = re.findall(r'\\/\\/(.*?)\\/', data['reference'])\n             if source:\n-                data['source']=source[0]\n-            res = requests.post(url,data=data,verify=False)\n-            if not res.status_code in [201,200,400]:\n+                data['source'] = source[0]\n+            res = requests.post(url, data=data, verify=False)\n+            if not res.status_code in [201, 200, 400]:\n                 logger.info(\"Issues with adding: %s\" % data['ip'])\n         elif indicator[1] == \"FQDN\":\n             # using the Domain API\n-            url=base_url+'domains/'\n-            data['add_indicator']=\"true\"\n-            data['domain']=indicator[0]\n-            data['reference']=indicator[3]\n+            url = base_url + 'domains/'\n+            data['add_indicator'] = \"true\"\n+            data['domain'] = indicator[0]\n+            data['reference'] = indicator[3]\n             # getting the source automatically:\n-            source=re.findall(r'\\/\\/(.*?)\\/',data['reference'])\n+            source = re.findall(r'\\/\\/(.*?)\\/', data['reference'])\n             if source:\n-                data['source']=source[0]\n-            res = requests.post(url,data=data,verify=False)\n-            if not res.status_code in [201,200,400]:\n+                data['source'] = source[0]\n+            res = requests.post(url, data=data, verify=False)\n+            if not res.status_code in [201, 200, 400]:\n                 logger.info(\"Issues with adding: %s\" % data['domain'])\n         else:\n-            logger.info(\"don't yet know what to do with: %s[%s]\" % (indicator[1],indicator[0]))\n+            logger.info(\"don't yet know what to do with: %s[%s]\" % (indicator[1], indicator[0]))\n+\n \n-def bale_CRITs(harvest,filename):\n+def bale_CRITs(harvest, filename):\n     \"\"\" taking the output from combine and pushing it to the CRITs web API\"\"\"\n     # checking the minimum requirements for parameters\n     # it would be nice to have some metadata on the feeds that can be imported in the intel library:\n     #   -> confidence\n     #   -> type of feed (bot vs spam vs ddos, you get the picture)\n-    data={'confidence':'medium'}\n-    start_time=time.time()\n+    data = {'confidence': 'medium'}\n+    start_time = time.time()\n     config = ConfigParser.SafeConfigParser()\n     cfg_success = config.read('combine.cfg')\n     if not cfg_success:\n         logger.error('tiq_output: Could not read combine.cfg.\\n')\n         logger.error('HINT: edit combine-example.cfg and save as combine.cfg.\\n')\n         return\n-    if config.has_option('Baler','crits_username'):\n-        data['username']=config.get('Baler', 'crits_username')\n+    if config.has_option('Baler', 'crits_username'):\n+        data['username'] = config.get('Baler', 'crits_username')\n     else:\n         raise 'Please check the combine.cnf file for the crits_username field in the [Baler] section'\n-    if config.has_option('Baler','crits_api_key'):\n-        data['api_key']=config.get('Baler', 'crits_api_key')\n+    if config.has_option('Baler', 'crits_api_key'):\n+        data['api_key'] = config.get('Baler', 'crits_api_key')\n     else:\n         raise 'Please check the combine.cnf file for the crits_api_key field in the [Baler] section'\n-    if config.has_option('Baler','crits_campaign'):\n-        data['campaign']=config.get('Baler', 'crits_campaign')\n+    if config.has_option('Baler', 'crits_campaign'):\n+        data['campaign'] = config.get('Baler', 'crits_campaign')\n     else:\n         logger.info('Lacking a campaign name, we will default to \"combine.\" Errors might ensue if it does not exist in CRITs')\n-        data['campaign']='combine'\n-    if config.has_option('Baler','crits_url'):\n-        base_url=config.get('Baler','crits_url')\n+        data['campaign'] = 'combine'\n+    if config.has_option('Baler', 'crits_url'):\n+        base_url = config.get('Baler', 'crits_url')\n     else:\n         raise 'Please check the combine.cnf file for the crits_url field in the [Baler] section'\n-    if config.has_option('Baler','crits_maxThreads'):\n-        maxThreads=int(config.get('Baler', 'crits_maxThreads'))\n+    if config.has_option('Baler', 'crits_maxThreads'):\n+        maxThreads = int(config.get('Baler', 'crits_maxThreads'))\n     else:\n         logger.info('No number of maximum Threads has been given, defaulting to 10')\n-        maxThreads=10\n+        maxThreads = 10\n \n-    data['source']='Combine'\n-    data['method']='trawl'\n+    data['source'] = 'Combine'\n+    data['method'] = 'trawl'\n \n     # initializing the Queue to the list of indicators in the harvest\n-    ioc_queue=Queue()\n+    ioc_queue = Queue()\n     for indicator in harvest:\n         ioc_queue.put(indicator)\n-    total_iocs=ioc_queue.qsize()\n+    total_iocs = ioc_queue.qsize()\n \n     for x in range(maxThreads):\n-        th=threading.Thread(target=bale_CRITs_indicator, args=(base_url,data,ioc_queue))\n+        th = threading.Thread(target=bale_CRITs_indicator, args=(base_url, data, ioc_queue))\n         th.start()\n \n     for x in threading.enumerate():\n-        if x.name==\"MainThread\":\n+        if x.name == \"MainThread\":\n             continue\n         x.join()\n \n-    logger.info('Output %d indicators to CRITs using %d threads. Operation tool %d seconds\\n' % (total_iocs,maxThreads,time.time()-start_time))\n+    logger.info('Output %d indicators to CRITs using %d threads. Operation tool %d seconds\\n' %\n+                (total_iocs, maxThreads, time.time() - start_time))\n+\n \n def bale(input_file, output_file, output_format, is_regular):\n     config = ConfigParser.SafeConfigParser()\n@@ -203,13 +208,13 @@ def bale(input_file, output_file, output_format, is_regular):\n \n     logger.info('Reading processed data from %s' % input_file)\n     with open(input_file, 'rb') as f:\n-        harvest = json.load(f)\n+        harvest = json.load(f, encoding='utf8')\n \n     # TODO: also need plugins here (cf. #23)\n     if is_regular:\n-        format_funcs = {'csv': bale_reg_csv,'crits':bale_CRITs}\n+        format_funcs = {'csv': bale_reg_csv, 'crits': bale_CRITs}\n     else:\n-        format_funcs = {'csv': bale_enr_csv,'crits':bale_CRITs}\n+        format_funcs = {'csv': bale_enr_csv, 'crits': bale_CRITs}\n     format_funcs[output_format](harvest, output_file)\n \n if __name__ == \"__main__\":\ndiff --git a/winnower.py b/winnower.py\n--- a/winnower.py\n+++ b/winnower.py\n@@ -9,30 +9,36 @@\n import sys\n \n from netaddr import IPAddress, IPRange, IPSet\n+from sortedcontainers import SortedDict\n \n from logger import get_logger\n import logging\n \n logger = get_logger('winnower')\n \n+# from http://en.wikipedia.org/wiki/Reserved_IP_addresses:\n+reserved_ranges = IPSet(['0.0.0.0/8', '100.64.0.0/10', '127.0.0.0/8', '192.88.99.0/24',\n+                         '198.18.0.0/15', '198.51.100.0/24', '203.0.113.0/24', '233.252.0.0/24'])\n+gi_org = SortedDict()\n+\n \n def load_gi_org(filename):\n-    gi_org = {}\n     with open(filename, 'rb') as f:\n         org_reader = csv.DictReader(f, fieldnames=['start', 'end', 'org'])\n         for row in org_reader:\n-            gi_org[IPRange(row['start'], row['end'])] = row['org']\n+            gi_org[row['start']] = (IPRange(row['start'], row['end']), unicode(row['org'], errors='replace'))\n+\n     return gi_org\n \n \n-def org_by_addr(address, org_data):\n+def org_by_addr(address):\n     as_num = None\n     as_name = None\n-    for iprange in org_data:\n-        if address in iprange:\n-            as_num, sep, as_name = org_data[iprange].partition(' ')\n-            as_num = as_num.replace(\"AS\", \"\")  # Making sure the variable only has the number\n-            break\n+    gi_index = gi_org.bisect(str(int(address)))\n+    gi_net = gi_org[gi_org.iloc[gi_index - 1]]\n+    if address in gi_net[0]:\n+        as_num, sep, as_name = gi_net[1].partition(' ')\n+        as_num = as_num.replace(\"AS\", \"\")  # Making sure the variable only has the number\n     return as_num, as_name\n \n \n@@ -46,8 +52,8 @@ def maxhits(dns_records):\n     return hostname\n \n \n-def enrich_IPv4(address, org_data, geo_data, dnsdb=None):\n-    as_num, as_name = org_by_addr(address, org_data)\n+def enrich_IPv4(address, geo_data, dnsdb=None):\n+    as_num, as_name = org_by_addr(address)\n     country = geo_data.country_code_by_addr('%s' % address)\n     if dnsdb:\n         hostname = maxhits(dnsdb.query_rdata_ip('%s' % address))\n@@ -73,12 +79,9 @@ def filter_date(records, date):\n \n \n def reserved(address):\n-    # from http://en.wikipedia.org/wiki/Reserved_IP_addresses:\n-    ranges = IPSet(['0.0.0.0/8', '100.64.0.0/10', '127.0.0.0/8', '192.88.99.0/24',\n-                    '198.18.0.0/15', '198.51.100.0/24', '203.0.113.0/24', '233.252.0.0/24'])\n     a_reserved = address.is_reserved()\n     a_private = address.is_private()\n-    a_inr = address in ranges\n+    a_inr = address in reserved_ranges\n     if a_reserved or a_private or a_inr:\n         return True\n     else:\n@@ -138,7 +141,7 @@ def winnow(in_file, out_file, enr_file):\n \n     # TODO: make these locations configurable?\n     logger.info('Loading GeoIP data')\n-    org_data = load_gi_org('data/GeoIPASNum2.csv')\n+    gi_org = load_gi_org('data/GeoIPASNum2.csv')\n     geo_data = pygeoip.GeoIP('data/GeoIP.dat', pygeoip.MEMORY_CACHE)\n \n     wheat = []\n@@ -147,23 +150,21 @@ def winnow(in_file, out_file, enr_file):\n     logger.info('Beginning winnowing process')\n     for each in crop:\n         (addr, addr_type, direction, source, note, date) = each\n-        # TODO: enrich DNS indicators as well\n         if addr_type == 'IPv4' and is_ipv4(addr):\n-            logger.info('Enriching %s' % addr)\n+            #logger.info('Enriching %s' % addr)\n             ipaddr = IPAddress(addr)\n             if not reserved(ipaddr):\n                 wheat.append(each)\n                 if enrich_ip:\n-                    e_data = (addr, addr_type, direction, source, note, date) + enrich_IPv4(ipaddr, org_data, geo_data, dnsdb)\n+                    e_data = (addr, addr_type, direction, source, note, date) + enrich_IPv4(ipaddr, geo_data, dnsdb)\n                     enriched.append(e_data)\n                 else:\n-                    e_data = (addr, addr_type, direction, source, note, date) + enrich_IPv4(ipaddr, org_data, geo_data)\n+                    e_data = (addr, addr_type, direction, source, note, date) + enrich_IPv4(ipaddr, geo_data)\n                     enriched.append(e_data)\n             else:\n                 logger.error('Found invalid address: %s from: %s' % (addr, source))\n         elif addr_type == 'FQDN' and is_fqdn(addr):\n-            # TODO: validate these (cf. https://github.com/mlsecproject/combine/issues/15 )\n-            logger.info('Enriching %s' % addr)\n+            #logger.info('Enriching %s' % addr)\n             wheat.append(each)\n             if enrich_dns and dnsdb:\n                 e_data = (addr, addr_type, direction, source, note, date, enrich_FQDN(addr, date, dnsdb))\n@@ -173,10 +174,12 @@ def winnow(in_file, out_file, enr_file):\n \n     logger.info('Dumping results')\n     with open(out_file, 'wb') as f:\n-        json.dump(wheat, f, indent=2)\n+        w_data = json.dumps(wheat, indent=2, ensure_ascii=False).encode('utf8')\n+        f.write(w_data)\n \n     with open(enr_file, 'wb') as f:\n-        json.dump(enriched, f, indent=2)\n+        e_data = json.dumps(enriched, indent=2, ensure_ascii=False).encode('utf8')\n+        f.write(e_data)\n \n \n if __name__ == \"__main__\":\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2014-12-26T18:31:08Z"}