Python-digital-forensics-investigation-of-log-based-artifacts

提供:Dev Guides
移動先:案内検索

ログベースのアーティファクトの調査

これまで、Pythonを使用してWindowsでアーティファクトを取得する方法を見てきました。 この章では、Pythonを使用したログベースのアーティファクトの調査について学びましょう。

前書き

ログベースのアーティファクトは、デジタルフォレンジックの専門家にとって非常に役立つ情報の宝庫です。 情報を収集するためのさまざまな監視ソフトウェアがありますが、それらから有用な情報を解析するための主な問題は、大量のデータが必要なことです。

さまざまなログベースのアーティファクトとPythonでの調査

このセクションでは、さまざまなログベースのアーティファクトとPythonでの調査について説明します-

タイムスタンプ

タイムスタンプは、ログのアクティビティのデータと時間を伝えます。 これは、ログファイルの重要な要素の1つです。 これらのデータと時刻の値は、さまざまな形式で入力できることに注意してください。

以下に示すPythonスクリプトは、入力として生の日付時刻を取り、その出力として書式設定されたタイムスタンプを提供します。

このスクリプトでは、次の手順に従う必要があります-

  • 最初に、データのソースとデータ型とともに生データ値を取る引数を設定します。
  • 次に、異なる日付形式のデータに共通のインターフェースを提供するクラスを提供します。

Pythonコード

この目的のためにPythonコードを使用する方法を見てみましょう-

まず、次のPythonモジュールをインポートします-

from __future__ import print_function
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from datetime import datetime as dt
from datetime import timedelta

さて、いつものように、コマンドラインハンドラーの引数を指定する必要があります。 ここでは、3つの引数を受け入れます。1つ目は処理する日付値、2つ目はその日付値のソース、3つ目はそのタイプです-

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をそれぞれ処理する2つのメソッドを定義する必要があります-

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サーバーログは、ユーザーおよび地理的な場所に関する情報とともに有用なユーザー統計を取得できるため、もう1つの重要な成果物です。 以下は、情報を簡単に分析するために、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*"))]

次に、コマンドラインハンドラーの引数を指定します。 ここでは、2つの引数を受け入れます。1つ目は処理するIISログ、2つ目は目的の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

次に、コマンドラインハンドラーの引数を指定します。 ここでは2つの引数を受け入れることに注意してください。1つ目はYARAルールへのパス、2つ目はスキャンするファイルです。

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()関数を定義します-

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

次に、2つの関数を定義します。 最初に* 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レポートを生成できます。