- Python數字取證
- Python數字取證 - 首頁
- 介紹
- Python入門
- 工件報告
- 移動裝置取證
- 嵌入式元資料的調查
- 網路取證-I
- 網路取證-II
- 使用電子郵件進行調查
- Windows重要工件-I
- Windows重要工件-II
- Windows重要工件-III
- 基於日誌的工件調查
- Python數字取證資源
- 快速指南
- Python數字取證 - 資源
- Python數字取證 - 討論
基於日誌的工件調查
到目前為止,我們已經瞭解瞭如何使用Python獲取Windows中的工件。在本章中,讓我們學習如何使用Python調查基於日誌的工件。
介紹
基於日誌的工件是資訊寶庫,對數字取證專家非常有用。雖然我們有各種監控軟體來收集資訊,但從這些軟體中解析有用資訊的主要問題是我們需要大量資料。
各種基於日誌的工件和Python中的調查
在本節中,讓我們討論各種基於日誌的工件及其在Python中的調查:
時間戳
時間戳傳達日誌中活動的日期和時間。它是任何日誌檔案的重要組成部分之一。請注意,這些日期和時間值可能採用各種格式。
下面顯示的Python指令碼將獲取原始日期時間作為輸入,並提供格式化的時間戳作為輸出。
對於此指令碼,我們需要遵循以下步驟:
首先,設定將獲取原始資料值以及資料來源和資料型別的引數。
現在,提供一個類,為不同日期格式的資料提供公共介面。
Python程式碼
讓我們看看如何為此目的使用Python程式碼:
首先,匯入以下Python模組:
from __future__ import print_function from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from datetime import datetime as dt from datetime import timedelta
現在,像往常一樣,我們需要為命令列處理程式提供引數。這裡它將接受三個引數,第一個是要處理的日期值,第二個是該日期值的來源,第三個是其型別:
if __name__ == '__main__':
parser = ArgumentParser('Timestamp Log-based artifact')
parser.add_argument("date_value", help="Raw date value to parse")
parser.add_argument(
"source", help = "Source format of date",choices = ParseDate.get_supported_formats())
parser.add_argument(
"type", help = "Data type of input value",choices = ('number', 'hex'), default = 'int')
args = parser.parse_args()
date_parser = ParseDate(args.date_value, args.source, args.type)
date_parser.run()
print(date_parser.timestamp)
現在,我們需要定義一個類,它將接受日期值、日期來源和值型別的引數:
class ParseDate(object):
def __init__(self, date_value, source, data_type):
self.date_value = date_value
self.source = source
self.data_type = data_type
self.timestamp = None
現在我們將定義一個方法,該方法將像main()方法一樣充當控制器:
def run(self):
if self.source == 'unix-epoch':
self.parse_unix_epoch()
elif self.source == 'unix-epoch-ms':
self.parse_unix_epoch(True)
elif self.source == 'windows-filetime':
self.parse_windows_filetime()
@classmethod
def get_supported_formats(cls):
return ['unix-epoch', 'unix-epoch-ms', 'windows-filetime']
現在,我們需要定義兩個方法,分別處理Unix紀元時間和FILETIME:
def parse_unix_epoch(self, milliseconds=False):
if self.data_type == 'hex':
conv_value = int(self.date_value)
if milliseconds:
conv_value = conv_value / 1000.0
elif self.data_type == 'number':
conv_value = float(self.date_value)
if milliseconds:
conv_value = conv_value / 1000.0
else:
print("Unsupported data type '{}' provided".format(self.data_type))
sys.exit('1')
ts = dt.fromtimestamp(conv_value)
self.timestamp = ts.strftime('%Y-%m-%d %H:%M:%S.%f')
def parse_windows_filetime(self):
if self.data_type == 'hex':
microseconds = int(self.date_value, 16) / 10.0
elif self.data_type == 'number':
microseconds = float(self.date_value) / 10
else:
print("Unsupported data type '{}' provided".format(self.data_type))
sys.exit('1')
ts = dt(1601, 1, 1) + timedelta(microseconds=microseconds)
self.timestamp = ts.strftime('%Y-%m-%d %H:%M:%S.%f')
執行上述指令碼後,透過提供時間戳,我們可以獲得易於閱讀的格式的轉換值。
Web伺服器日誌
從數字取證專家的角度來看,Web伺服器日誌是另一個重要的工件,因為它們可以獲取有用的使用者統計資訊以及有關使用者和地理位置的資訊。以下是將處理Web伺服器日誌後建立電子表格以方便分析資訊的Python指令碼。
首先,我們需要匯入以下Python模組:
from __future__ import print_function from argparse import ArgumentParser, FileType import re import shlex import logging import sys import csv logger = logging.getLogger(__file__)
現在,我們需要定義將從日誌中解析的模式:
iis_log_format = [
("date", re.compile(r"\d{4}-\d{2}-\d{2}")),
("time", re.compile(r"\d\d:\d\d:\d\d")),
("s-ip", re.compile(
r"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}")),
("cs-method", re.compile(
r"(GET)|(POST)|(PUT)|(DELETE)|(OPTIONS)|(HEAD)|(CONNECT)")),
("cs-uri-stem", re.compile(r"([A-Za-z0-1/\.-]*)")),
("cs-uri-query", re.compile(r"([A-Za-z0-1/\.-]*)")),
("s-port", re.compile(r"\d*")),
("cs-username", re.compile(r"([A-Za-z0-1/\.-]*)")),
("c-ip", re.compile(
r"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}")),
("cs(User-Agent)", re.compile(r".*")),
("sc-status", re.compile(r"\d*")),
("sc-substatus", re.compile(r"\d*")),
("sc-win32-status", re.compile(r"\d*")),
("time-taken", re.compile(r"\d*"))]
現在,為命令列處理程式提供引數。這裡它將接受兩個引數,第一個是要處理的IIS日誌,第二個是所需的CSV檔案路徑。
if __name__ == '__main__':
parser = ArgumentParser('Parsing Server Based Logs')
parser.add_argument('iis_log', help = "Path to IIS Log",type = FileType('r'))
parser.add_argument('csv_report', help = "Path to CSV report")
parser.add_argument('-l', help = "Path to processing log",default=__name__ + '.log')
args = parser.parse_args()
logger.setLevel(logging.DEBUG)
msg_fmt = logging.Formatter(
"%(asctime)-15s %(funcName)-10s ""%(levelname)-8s %(message)s")
strhndl = logging.StreamHandler(sys.stdout)
strhndl.setFormatter(fmt = msg_fmt)
fhndl = logging.FileHandler(args.log, mode = 'a')
fhndl.setFormatter(fmt = msg_fmt)
logger.addHandler(strhndl)
logger.addHandler(fhndl)
logger.info("Starting IIS Parsing ")
logger.debug("Supplied arguments: {}".format(", ".join(sys.argv[1:])))
logger.debug("System " + sys.platform)
logger.debug("Version " + sys.version)
main(args.iis_log, args.csv_report, logger)
iologger.info("IIS Parsing Complete")
現在我們需要定義main()方法來處理批次日誌資訊:
def main(iis_log, report_file, logger):
parsed_logs = []
for raw_line in iis_log:
line = raw_line.strip()
log_entry = {}
if line.startswith("#") or len(line) == 0:
continue
if '\"' in line:
line_iter = shlex.shlex(line_iter)
else:
line_iter = line.split(" ")
for count, split_entry in enumerate(line_iter):
col_name, col_pattern = iis_log_format[count]
if col_pattern.match(split_entry):
log_entry[col_name] = split_entry
else:
logger.error("Unknown column pattern discovered. "
"Line preserved in full below")
logger.error("Unparsed Line: {}".format(line))
parsed_logs.append(log_entry)
logger.info("Parsed {} lines".format(len(parsed_logs)))
cols = [x[0] for x in iis_log_format]
logger.info("Creating report file: {}".format(report_file))
write_csv(report_file, cols, parsed_logs)
logger.info("Report created")
最後,我們需要定義一個方法將輸出寫入電子表格:
def write_csv(outfile, fieldnames, data):
with open(outfile, 'w', newline="") as open_outfile:
csvfile = csv.DictWriter(open_outfile, fieldnames)
csvfile.writeheader()
csvfile.writerows(data)
執行上述指令碼後,我們將得到電子表格中的基於Web伺服器的日誌。
使用YARA掃描重要檔案
YARA(Yet Another Recursive Algorithm)是一種旨在用於惡意軟體識別和事件響應的模式匹配實用程式。我們將使用YARA掃描檔案。在下面的Python指令碼中,我們將使用YARA。
我們可以使用以下命令安裝YARA:
pip install YARA
我們可以按照以下步驟使用YARA規則掃描檔案:
首先,設定並編譯YARA規則
然後,掃描單個檔案,然後迭代目錄以處理各個檔案。
最後,我們將結果匯出到CSV。
Python程式碼
讓我們看看如何為此目的使用Python程式碼:
首先,我們需要匯入以下Python模組:
from __future__ import print_function from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import os import csv import yara
接下來,為命令列處理程式提供引數。請注意,這裡它將接受兩個引數——第一個是YARA規則的路徑,第二個是要掃描的檔案。
if __name__ == '__main__':
parser = ArgumentParser('Scanning files by YARA')
parser.add_argument(
'yara_rules',help = "Path to Yara rule to scan with. May be file or folder path.")
parser.add_argument('path_to_scan',help = "Path to file or folder to scan")
parser.add_argument('--output',help = "Path to output a CSV report of scan results")
args = parser.parse_args()
main(args.yara_rules, args.path_to_scan, args.output)
現在我們將定義main()函式,它將接受YARA規則的路徑和要掃描的檔案:
def main(yara_rules, path_to_scan, output):
if os.path.isdir(yara_rules):
yrules = yara.compile(yara_rules)
else:
yrules = yara.compile(filepath=yara_rules)
if os.path.isdir(path_to_scan):
match_info = process_directory(yrules, path_to_scan)
else:
match_info = process_file(yrules, path_to_scan)
columns = ['rule_name', 'hit_value', 'hit_offset', 'file_name',
'rule_string', 'rule_tag']
if output is None:
write_stdout(columns, match_info)
else:
write_csv(output, columns, match_info)
現在,定義一個方法,該方法將迭代目錄並將結果傳遞給另一個方法以進行進一步處理:
def process_directory(yrules, folder_path):
match_info = []
for root, _, files in os.walk(folder_path):
for entry in files:
file_entry = os.path.join(root, entry)
match_info += process_file(yrules, file_entry)
return match_info
接下來,定義兩個函式。請注意,首先我們將使用match()方法到yrules物件,另一個將在使用者未指定任何輸出檔案的情況下將匹配資訊報告到控制檯。觀察下面顯示的程式碼:
def process_file(yrules, file_path):
match = yrules.match(file_path)
match_info = []
for rule_set in match:
for hit in rule_set.strings:
match_info.append({
'file_name': file_path,
'rule_name': rule_set.rule,
'rule_tag': ",".join(rule_set.tags),
'hit_offset': hit[0],
'rule_string': hit[1],
'hit_value': hit[2]
})
return match_info
def write_stdout(columns, match_info):
for entry in match_info:
for col in columns:
print("{}: {}".format(col, entry[col]))
print("=" * 30)
最後,我們將定義一個方法,該方法將輸出寫入CSV檔案,如下所示:
def write_csv(outfile, fieldnames, data):
with open(outfile, 'w', newline="") as open_outfile:
csvfile = csv.DictWriter(open_outfile, fieldnames)
csvfile.writeheader()
csvfile.writerows(data)
成功執行上述指令碼後,我們可以在命令列提供適當的引數,並可以生成CSV報告。