Python數字網路取證-I



本章將解釋使用Python進行網路取證的基本原理。

理解網路取證

網路取證是數字取證的一個分支,它處理對計算機網路流量(包括本地網路和廣域網(WAN))的監控和分析,目的是收集資訊、收集證據或入侵檢測。網路取證在調查數字犯罪(例如盜竊智慧財產權或資訊洩露)中起著至關重要的作用。網路通訊的畫面可以幫助調查人員解決一些關鍵問題,如下所示:

  • 訪問了哪些網站?

  • 在我們的網路上上傳了哪些內容?

  • 從我們的網路下載了哪些內容?

  • 正在訪問哪些伺服器?

  • 有人正在將敏感資訊傳送到公司防火牆之外嗎?

網際網路證據查詢器 (IEF)

IEF 是一款數字取證工具,用於查詢、分析和展示在不同數字媒體(如計算機、智慧手機和平板電腦等)上發現的數字證據。它非常流行,並被成千上萬的取證專業人員使用。

IEF 的用途

由於其流行性,IEF 在很大程度上被取證專業人員使用。IEF 的一些用途如下:

  • 由於其強大的搜尋功能,它被用於同時搜尋多個檔案或資料媒體。

  • 它還用於透過新的雕刻技術從RAM的未分配空間恢復已刪除的資料。

  • 如果調查人員想要以其開啟時的原始格式重建網頁,則可以使用IEF。

  • 它還用於搜尋邏輯或物理磁碟卷。

使用Python將IEF報告轉儲到CSV

IEF 將資料儲存在SQLite資料庫中,以下Python指令碼將動態識別IEF資料庫中的結果表並將它們轉儲到各自的CSV檔案。

此過程按以下步驟進行

  • 首先,生成IEF結果資料庫,它將是一個以.db副檔名結尾的SQLite資料庫檔案。

  • 然後,查詢該資料庫以識別所有表。

  • 最後,將這些結果表寫入單個CSV檔案。

Python程式碼

讓我們看看如何為此目的使用Python程式碼:

對於Python指令碼,匯入必要的庫如下:

from __future__ import print_function

import argparse
import csv
import os
import sqlite3
import sys

現在,我們需要提供IEF資料庫檔案的路徑:

if __name__ == '__main__':
   parser = argparse.ArgumentParser('IEF to CSV')
   parser.add_argument("IEF_DATABASE", help="Input IEF database")
   parser.add_argument("OUTPUT_DIR", help="Output DIR")
   args = parser.parse_args()

現在,我們將確認IEF資料庫的存在,如下所示:

if not os.path.exists(args.OUTPUT_DIR):
   os.makedirs(args.OUTPUT_DIR)
if os.path.exists(args.IEF_DATABASE) and \ os.path.isfile(args.IEF_DATABASE):
   main(args.IEF_DATABASE, args.OUTPUT_DIR)
else:
   print("[-] Supplied input file {} does not exist or is not a " "file".format(args.IEF_DATABASE))
   sys.exit(1)

現在,像我們在之前的指令碼中一樣,透過遊標建立與SQLite資料庫的連線,以執行查詢:

def main(database, out_directory):
   print("[+] Connecting to SQLite database")
   conn = sqlite3.connect(database)
   c = conn.cursor()

以下幾行程式碼將從資料庫中獲取表名:

print("List of all tables to extract")
c.execute("select * from sqlite_master where type = 'table'")
tables = [x[2] for x in c.fetchall() if not x[2].startswith('_') and not x[2].endswith('_DATA')]

現在,我們將從表中選擇所有資料,並使用fetchall()方法在遊標物件上將包含表資料的完整列表的元組列表儲存在一個變數中:

print("Dumping {} tables to CSV files in {}".format(len(tables), out_directory))

for table in tables:
c.execute("pragma table_info('{}')".format(table))
table_columns = [x[1] for x in c.fetchall()]

c.execute("select * from '{}'".format(table))
table_data = c.fetchall()

現在,使用CSV_Writer()方法,我們將內容寫入CSV檔案:

csv_name = table + '.csv'
csv_path = os.path.join(out_directory, csv_name)
print('[+] Writing {} table to {} CSV file'.format(table,csv_name))

with open(csv_path, "w", newline = "") as csvfile:
   csv_writer = csv.writer(csvfile)
   csv_writer.writerow(table_columns)
   csv_writer.writerows(table_data)

上述指令碼將從IEF資料庫的表中獲取所有資料,並將內容寫入我們選擇的CSV檔案。

使用快取資料

從IEF結果資料庫中,我們可以獲取IEF本身不一定支援的更多資訊。我們可以從像雅虎、谷歌等電子郵件服務提供商那裡獲取快取資料(資訊的副產品),方法是使用IEF結果資料庫。

以下是使用IEF資料庫訪問在Google Chrome上訪問的雅虎郵件的快取資料資訊的Python指令碼。請注意,步驟與最後一個Python指令碼中遵循的步驟大致相同。

首先,匯入Python所需的庫,如下所示:

from __future__ import print_function
import argparse
import csv
import os
import sqlite3
import sys
import json

現在,提供IEF資料庫檔案的路徑以及命令列處理程式接受的兩個位置引數,就像在最後一個指令碼中一樣:

if __name__ == '__main__':
   parser = argparse.ArgumentParser('IEF to CSV')
   parser.add_argument("IEF_DATABASE", help="Input IEF database")
   parser.add_argument("OUTPUT_DIR", help="Output DIR")
   args = parser.parse_args()

現在,確認IEF資料庫的存在,如下所示:

directory = os.path.dirname(args.OUTPUT_CSV)

if not os.path.exists(directory):os.makedirs(directory)
if os.path.exists(args.IEF_DATABASE) and \ os.path.isfile(args.IEF_DATABASE):
   main(args.IEF_DATABASE, args.OUTPUT_CSV)
   else: print("Supplied input file {} does not exist or is not a " "file".format(args.IEF_DATABASE))
sys.exit(1)

現在,透過遊標建立與SQLite資料庫的連線,以執行查詢:

def main(database, out_csv):
   print("[+] Connecting to SQLite database")
   conn = sqlite3.connect(database)
   c = conn.cursor()

您可以使用以下幾行程式碼來獲取雅虎郵件聯絡人快取記錄的例項:

print("Querying IEF database for Yahoo Contact Fragments from " "the Chrome Cache Records Table")
   try:
      c.execute("select * from 'Chrome Cache Records' where URL like " "'https://data.mail.yahoo.com" "/classicab/v2/contacts/?format=json%'")
   except sqlite3.OperationalError:
      print("Received an error querying the database --    database may be" "corrupt or not have a Chrome Cache Records table")
      sys.exit(2)

現在,將從上述查詢返回的元組列表儲存到變數中,如下所示:

contact_cache = c.fetchall()
contact_data = process_contacts(contact_cache)
write_csv(contact_data, out_csv)

請注意,這裡我們將使用兩種方法,即process_contacts()用於設定結果列表以及遍歷每個聯絡人快取記錄,以及json.loads()用於將從表中提取的JSON資料儲存到變數中以供進一步操作:

def process_contacts(contact_cache):
   print("[+] Processing {} cache files matching Yahoo contact cache " " data".format(len(contact_cache)))
   results = []
   
   for contact in contact_cache:
      url = contact[0]
      first_visit = contact[1]
      last_visit = contact[2]
      last_sync = contact[3]
      loc = contact[8]
	   contact_json = json.loads(contact[7].decode())
      total_contacts = contact_json["total"]
      total_count = contact_json["count"]
      
      if "contacts" not in contact_json:
         continue
      for c in contact_json["contacts"]:
         name, anni, bday, emails, phones, links = ("", "", "", "", "", "")
            if "name" in c:
            name = c["name"]["givenName"] + " " + \ c["name"]["middleName"] + " " + c["name"]["familyName"]
            
            if "anniversary" in c:
            anni = c["anniversary"]["month"] + \"/" + c["anniversary"]["day"] + "/" + \c["anniversary"]["year"]
            
            if "birthday" in c:
            bday = c["birthday"]["month"] + "/" + \c["birthday"]["day"] + "/" + c["birthday"]["year"]
            
            if "emails" in c:
               emails = ', '.join([x["ep"] for x in c["emails"]])
            
            if "phones" in c:
               phones = ', '.join([x["ep"] for x in c["phones"]])
            
            if "links" in c:
              links = ', '.join([x["ep"] for x in c["links"]])

現在對於公司、職位和備註,使用get方法,如下所示:

company = c.get("company", "")
title = c.get("jobTitle", "")
notes = c.get("notes", "")

現在,讓我們將元資料和提取的資料元素列表附加到結果列表中,如下所示:

results.append([url, first_visit, last_visit, last_sync, loc, name, bday,anni, emails, phones, links, company, title, notes,total_contacts, total_count])
return results   

現在,使用CSV_Writer()方法,我們將內容寫入CSV檔案:

def write_csv(data, output):
   print("[+] Writing {} contacts to {}".format(len(data), output))
   with open(output, "w", newline="") as csvfile:
      csv_writer = csv.writer(csvfile)
      csv_writer.writerow([
         "URL", "First Visit (UTC)", "Last Visit (UTC)",
         "Last Sync (UTC)", "Location", "Contact Name", "Bday",
         "Anniversary", "Emails", "Phones", "Links", "Company", "Title",
         "Notes", "Total Contacts", "Count of Contacts in Cache"])
      csv_writer.writerows(data)  

藉助上述指令碼,我們可以使用IEF資料庫處理雅虎郵件的快取資料。

廣告
© . All rights reserved.