{"cells":[{"metadata":{},"cell_type":"markdown","source":"# <font color='red'> Sample Pre-processing of Web Content for Dataset Preparation </font>"},{"metadata":{},"cell_type":"markdown","source":"## Initialisation Code"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Basic Libraries to be installed before moving ahead\n!pip install pysafebrowsing\n!pip install tld\n!pip install whois\n!pip install geoip2","execution_count":35,"outputs":[{"output_type":"stream","text":"Requirement already satisfied: geoip2 in /opt/conda/lib/python3.7/site-packages (3.0.0)\nRequirement already satisfied: maxminddb>=1.5.2 in /opt/conda/lib/python3.7/site-packages (from geoip2) (1.5.2)\nRequirement already satisfied: requests>=2.22.0 in /opt/conda/lib/python3.7/site-packages (from geoip2) (2.23.0)\nRequirement already satisfied: urllib3>=1.25.2 in /opt/conda/lib/python3.7/site-packages (from geoip2) (1.25.7)\nRequirement already satisfied: idna<3,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.22.0->geoip2) (2.9)\nRequirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.22.0->geoip2) (2020.4.5.1)\nRequirement already satisfied: chardet<4,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.22.0->geoip2) (3.0.4)\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Basic Initialisation\nimport time\nimport pandas as pd\nimport numpy as np\npd.set_option('mode.chained_assignment', None) #Switch off warning","execution_count":36,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Verifying pathname of dataset before loading\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename));\n        print(os.listdir(\"../input\"))","execution_count":37,"outputs":[{"output_type":"stream","text":"/kaggle/input/geoipdatabase/GeoLite2-Country.mmdb\n['geoipdatabase', 'preprocessingsampledata']\n/kaggle/input/preprocessingsampledata/PreprocessingSampleData.csv\n['geoipdatabase', 'preprocessingsampledata']\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"## Loading the Sample Web Content Crawled & Collected by MalCrawler"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Loading Dataset containing Raw Web Content, URL and IP Address (Output of MalCrawler)\ndef loadDataset():\n    df = pd.read_csv(\"/kaggle/input/preprocessingsampledata/PreprocessingSampleData.csv\")\n    return df\n\ndf = loadDataset()\ndf = df[['url','ip_add', 'content']] # The three Columns of the initial data\ndf","execution_count":29,"outputs":[{"output_type":"execute_result","execution_count":29,"data":{"text/plain":"                                                  url           ip_add  \\\n0                http://www.dutchthewiz.com/freeware/    175.67.214.68   \n1                    http://www.collectiblejewels.com  188.120.171.121   \n2                         http://www.deadlinedata.com     193.51.170.1   \n3   http://www.mil.fi/maavoimat/kalustoesittely/00...     13.237.35.44   \n4            http://www.avclub.com/content/node/24539    220.193.62.89   \n..                                                ...              ...   \n95      http://www.ipl.org/div/potus/gwashington.html    22.63.103.109   \n96                           http://sharellmartin.biz    102.44.184.56   \n97                           http://www.oatlands.org/   206.161.206.80   \n98                         http://www.threshold21.com    169.23.27.160   \n99                    http://www.dauntlessmotors.com/      139.90.4.65   \n\n                                              content  \n0   Decay suggest in 1315.. Current constitution, ...  \n1   breast addict nudger whash ky darkie catholics...  \n2   Nato's military stoic philosophy says to accep...  \n3   Night being newton. according to the formation...  \n4   34 per two children. if we exercise simple pra...  \n..                                                ...  \n95  In high-energy sixth congress, geneva. Desert ...  \n96  Forth. designation or headquarters to chicago'...  \n97  Ancient chinese gather sticks\". toponymist geo...  \n98  Internet itself flagellated eukaryota. their c...  \n99  Climate change.an for inspiration to medieval ...  \n\n[100 rows x 3 columns]","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>ip_add</th>\n      <th>content</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>http://www.dutchthewiz.com/freeware/</td>\n      <td>175.67.214.68</td>\n      <td>Decay suggest in 1315.. Current constitution, ...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>http://www.collectiblejewels.com</td>\n      <td>188.120.171.121</td>\n      <td>breast addict nudger whash ky darkie catholics...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>http://www.deadlinedata.com</td>\n      <td>193.51.170.1</td>\n      <td>Nato's military stoic philosophy says to accep...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>http://www.mil.fi/maavoimat/kalustoesittely/00...</td>\n      <td>13.237.35.44</td>\n      <td>Night being newton. according to the formation...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>http://www.avclub.com/content/node/24539</td>\n      <td>220.193.62.89</td>\n      <td>34 per two children. if we exercise simple pra...</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>95</th>\n      <td>http://www.ipl.org/div/potus/gwashington.html</td>\n      <td>22.63.103.109</td>\n      <td>In high-energy sixth congress, geneva. Desert ...</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>http://sharellmartin.biz</td>\n      <td>102.44.184.56</td>\n      <td>Forth. designation or headquarters to chicago'...</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>http://www.oatlands.org/</td>\n      <td>206.161.206.80</td>\n      <td>Ancient chinese gather sticks\". toponymist geo...</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>http://www.threshold21.com</td>\n      <td>169.23.27.160</td>\n      <td>Internet itself flagellated eukaryota. their c...</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>http://www.dauntlessmotors.com/</td>\n      <td>139.90.4.65</td>\n      <td>Climate change.an for inspiration to medieval ...</td>\n    </tr>\n  </tbody>\n</table>\n<p>100 rows × 3 columns</p>\n</div>"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Adding new blank columns to the dataframe df\ndf['geo_loc']=\"\"\ndf['url_len']=\"\"\ndf['js_len']=\"\"\ndf['js_obf_len']=\"\"\ndf['tld']=\"\"\ndf['who_is']=\"\"\ndf['https']=\"\"\ndf['label']=\"\"\ndf = df[['url','ip_add','geo_loc','url_len','js_len','js_obf_len','tld','who_is','https','content','label']]\n#df","execution_count":53,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Computing the 'geo_loc' Attribute from IP Address"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Filling the 'geo_loc' column of dataframe \nimport os\nimport geoip2.database\nimport socket\nimport time\n\nreader = geoip2.database.Reader('/kaggle/input/geoipdatabase/GeoLite2-Country.mmdb')\n\nfor x in df.index:\n    try:\n        ip_add = str(df['ip_add'][x])\n        response = reader.country(ip_add)\n        df['geo_loc'][x] = response.country.name\n        #print(x, \"Finished,value is:\",response.country.name)   \n    except Exception as msg:\n        df['geo_loc'][x] = \"\"\n        #print(x,\" Finished with Error Msg:\",msg)\n\nreader.close()\n#df","execution_count":50,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Computing 'url_len"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Generating 'url_len' from 'url'\ndf['url_len'] = df['url'].str.len()\n#df","execution_count":55,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Computing 'js_len'"},{"metadata":{"trusted":true},"cell_type":"code","source":"import re       #importing regex for string selection and parsing\n\ndef get_js_len_inKB(content): #Function for computing 'js_len from Web Content\n    js=re.findall(r'<script>(.*?)</script>',content)\n    complete_js=''.join(js)\n    js_len = len(content.encode('utf-8'))/1000\n    return js_len\nfor x in df.index: #Computing and Putting 'js_len' in Pandas Dataframe\n    df['js_len'][x] = get_js_len_inKB(df['content'][x])\n\n#df","execution_count":56,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Computing 'js_obf_len'"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Computed using Selenium Emulator, thus will have to be run separately and then added\n# Code given in https://github.com/lucianogiuseppe/JS-Auto-DeObfuscator/blob/master/jsado.py","execution_count":58,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Computing 'tld' Attribute"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Filling up TLD column\nfrom tld import get_tld\n\nfor x in df.index:       \n    try:\n        u = df.url[x]\n        s = get_tld(str(u), fix_protocol=True)\n        df['tld'][x] = s\n    except:\n        pass\n#df","execution_count":60,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Computing 'who_is' Attribute"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Whois processing\nimport whois\nstart_time = time.time()\n\nfor x in df.index:  \n    try:    \n        domain = whois.query(df['url'][x])\n        #print(domain.registrar)\n        if len(str(domain.registrar)) >1 :\n            df['who_is'][x]= 'complete'\n        else:\n            df['who_is'][x]= 'incomplete'\n    except Exception as msg:\n        #print(x,\", Error: \",msg)\n        df['who_is'][x]= 'incomplete'\n    #print(x,df['who_is'][x])\n\nprint(\"***Total Time taken --- %s seconds ---***\" % (time.time() - start_time))\n#df","execution_count":66,"outputs":[{"output_type":"stream","text":"***Total Time taken --- 0.10448932647705078 seconds ---***\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Alternate Code for Computing using WHOIS API\nfrom urllib.request  import  urlopen       # Importing url library\nimport  json                               # Importing the JSON Module\n\nurl =  'https://www.bits-pilani.ac.in'  #A sample URL\napiKey = 'at_YC7W9LM2w1lQOCMmN0KUe3OU7B8Jc'\nurl = 'https://www.whoisxmlapi.com/whoisserver/WhoisService?'\\\n    + 'domainName=' + url + '&apiKey=' + apiKey + \"&outputFormat=JSON\"\n\nwhois_data= urlopen(url).read().decode('utf8') #WHO IS info returned by API\ndata=json.loads(whois_data) # Converting it from JSON to a Python Dict Object \n#if data['registrarName']==\"\":\n    #who_is = 'incomplete'\n#else:\n    #who_is = 'complete'\n  \n# Sample of one URL is shown here\n# Similarly, who_is data is checked for all URLs in the dataset\n","execution_count":70,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Computing the 'https' Attribute"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Filling the column https_status\nimport http.client\n\nstart_time = time.time()\n\nfor x in df.index:\n    https_status= False\n    try:\n        conn = http.client.HTTPSConnection(df['url'][x])\n        conn.request(\"HEAD\", \"/\")\n        res = conn.getresponse()\n        if res.status == 200 or res.status==301 or res.status==302:\n            https_status= True   \n        #print(x,res.status,res.reason,https_status)\n    except Exception as msg:\n        df['https'][x]= 'no'\n        #print(x,\"Error: \",msg)\n    finally:\n        df['https'][x]= https_status\n        #conn.close\n\nprint(\"***Total Time taken --- %s seconds ---***\" % (time.time() - start_time))\n#df","execution_count":76,"outputs":[{"output_type":"stream","text":"***Total Time taken --- 0.027629613876342773 seconds ---***\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"## Allocation of Class Label "},{"metadata":{"trusted":true},"cell_type":"code","source":"# Filling the label of training set from Google Safe Browising API\nfrom pysafebrowsing import SafeBrowsing\nKEY= \"AIzaSyABO6DPGmHpCs8U5ii1Efkp1dUPJHQfGpo\"\n\nstart_time = time.time()\ns = SafeBrowsing(KEY)\n\nfor x in df.index:\n    \n    try:\n        url = df['url'][x]\n        r = s.lookup_urls([url])\n        label=r[url]['malicious']    \n        df['label']=label\n        #print(x, label)\n    except Exception as msg:\n        df['label']=\"\"\n        #print(x,\"Error: \",msg)\n\nprint(\"***Total Time taken --- %s seconds ---***\" % (time.time() - start_time))\n\n#df","execution_count":78,"outputs":[{"output_type":"stream","text":"***Total Time taken --- 2.215198516845703 seconds ---***\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"## Saving of Processed Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Saving the file\n#df.to_csv(\"Datasets/processed_webdata_sample.csv\")","execution_count":79,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.7.6"}},"nbformat":4,"nbformat_minor":4}