1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windowsでプロセス監視するツールを作ってみた

1
Posted at

概要

WindowsでのSysmonを活用したプロセス生成と非正規DLLのロードを監視するアプリをAntigravityとPPLXを使用して作成しました。その結果、署名のないDLLのロードが確認できるようになりました。

準備

sysmonの導入

MicroSoftよりSysmonをダウンロード展開
https://learn.microsoft.com/ja-jp/sysinternals/downloads/sysmon

以下のGithubよりsysmonconfig-excludes-only.xmlをダウンロードし、sysmonフォルダに移動する。
https://github.com/olafhartong/sysmon-modular

以下のコマンドでインストールと設定の適応をする
Sysmon64.exe -accepteula -i sysmonconfig-excludes-only.xml
すでにンストール済みで、Verbose設定を適応するには
Sysmon64.exe -c sysmonconfig-excludes-only.xml

コード

using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.IO;
using System.Web.Script.Serialization;   // System.Web.Extensions.dll
using System.Windows.Forms;
using System.Xml.Linq;

public class MainForm : Form
{
    const string LogName = "Microsoft-Windows-Sysmon/Operational";
    const string XPath = "*[System[(EventID=1 or EventID=7)]]";

    const string SIGNED_GROUP_MARK = "*SIGNED*"; // signed のとき ImageLoaded をまとめるための疑似値
    const string SIGNED_DISPLAY = "*SIGNED* (any ImageLoaded)";

    TabControl tabs;
    DataGridView gridNew;
    DataGridView gridAllow;

    Button btnStart;
    Button btnEnd;
    Button btnAllowSelected;
    Button btnSaveAllow;
    Button btnReloadAllow;
    Button btnClearNew;

    Label lblStatus;

    EventLogWatcher watcher;

    bool learning = false;

    Dictionary<Tuple<string, string>, DataGridViewRow> newIndex = new Dictionary<Tuple<string, string>, DataGridViewRow>();
    Dictionary<Tuple<string, string>, AllowItem> allow = new Dictionary<Tuple<string, string>, AllowItem>();
    HashSet<Tuple<string, string>> learningSet = new HashSet<Tuple<string, string>>();

    public MainForm()
    {
        Text = "Sysmon Allow Viewer (Grouping signed by Image)";
        Width = 1300;
        Height = 750;

        btnStart = new Button(); btnStart.Text = "Start"; btnStart.Width = 90;
        btnEnd = new Button(); btnEnd.Text = "End"; btnEnd.Width = 90;
        btnAllowSelected = new Button(); btnAllowSelected.Text = "Allow selected"; btnAllowSelected.Width = 130;
        btnSaveAllow = new Button(); btnSaveAllow.Text = "Save allowlist"; btnSaveAllow.Width = 130;
        btnReloadAllow = new Button(); btnReloadAllow.Text = "Reload allowlist"; btnReloadAllow.Width = 140;
        btnClearNew = new Button(); btnClearNew.Text = "Clear new"; btnClearNew.Width = 110;

        lblStatus = new Label(); lblStatus.AutoSize = true; lblStatus.Text = "Ready";

        var top = new FlowLayoutPanel();
        top.Dock = DockStyle.Top;
        top.Height = 38;
        top.WrapContents = false;
        top.AutoScroll = true;
        top.Controls.Add(btnStart);
        top.Controls.Add(btnEnd);
        top.Controls.Add(btnAllowSelected);
        top.Controls.Add(btnClearNew);
        top.Controls.Add(btnSaveAllow);
        top.Controls.Add(btnReloadAllow);
        top.Controls.Add(lblStatus);

        gridNew = CreateGrid();
        gridAllow = CreateGrid();

        tabs = new TabControl();
        tabs.Dock = DockStyle.Fill;

        var tabNew = new TabPage("New (Suspicious)");
        var tabAllow = new TabPage("Allowlist");

        tabNew.Controls.Add(gridNew);
        tabAllow.Controls.Add(gridAllow);

        tabs.TabPages.Add(tabNew);
        tabs.TabPages.Add(tabAllow);

        Controls.Add(tabs);
        Controls.Add(top);

        Shown += (s, e) => OnShown();
        FormClosing += (s, e) => StopWatcher();

        btnStart.Click += (s, e) => StartLearning();
        btnEnd.Click += (s, e) => EndLearning();
        btnAllowSelected.Click += (s, e) => AllowSelectedFromNew();
        btnSaveAllow.Click += (s, e) => { SaveAllowList(); RefreshAllowGrid(); Status("Saved allowlist."); };
        btnReloadAllow.Click += (s, e) => { LoadAllowList(); RefreshAllowGrid(); Status("Reloaded allowlist."); };
        btnClearNew.Click += (s, e) => { gridNew.Rows.Clear(); newIndex.Clear(); Status("Cleared new list."); };
    }

    void OnShown()
    {
        LoadAllowList();
        RefreshAllowGrid();
        StartWatcherNewOnly();
        Status("Watching new events. Allowlist loaded: " + allow.Count);
    }

    DataGridView CreateGrid()
    {
        var g = new DataGridView();
        g.Dock = DockStyle.Fill;
        g.ReadOnly = true;
        g.AllowUserToAddRows = false;
        g.RowHeadersVisible = false;
        g.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        g.MultiSelect = true;
        g.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        g.ShowCellToolTips = true;

        g.Columns.Add("LastSeenUtc", "LastSeen (UTC)");
        g.Columns.Add("Count", "Count");
        g.Columns.Add("Image", "Image");
        g.Columns.Add("ImageLoaded", "ImageLoaded (grouped if signed)");
        g.Columns.Add("Signed", "Signed");
        g.Columns.Add("Hashes", "Hashes");

        g.CellFormatting += (s, e) =>
        {
            if (e.RowIndex < 0) return;
            
            // 行のハイライト処理
            object valObj = g.Rows[e.RowIndex].Cells["Signed"].Value;
            string signedVal = (valObj != null) ? valObj.ToString() : null;
            if (signedVal != null && signedVal.Contains("unsigned"))
            {
                g.Rows[e.RowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.Yellow;
            }
            else
            {
                g.Rows[e.RowIndex].DefaultCellStyle.BackColor = g.DefaultCellStyle.BackColor;
            }

            if (e.Value == null) return;
            string colName = g.Columns[e.ColumnIndex].Name;
            if (colName == "Image" || colName == "ImageLoaded")
            {
                string path = e.Value.ToString();
                if (path != SIGNED_DISPLAY)
                {
                    e.Value = ShortenPath(path);
                    e.FormattingApplied = true;
                }
            }
        };

        g.CellToolTipTextNeeded += (s, e) =>
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            string colName = g.Columns[e.ColumnIndex].Name;
            if (colName == "Image" || colName == "ImageLoaded")
            {
                var val = g.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                if (val != null) e.ToolTipText = val.ToString();
            }
        };

        return g;
    }

    void StartWatcherNewOnly()
    {
        StopWatcher();
        var query = new EventLogQuery(LogName, PathType.LogName, XPath);

        watcher = new EventLogWatcher(query, (EventBookmark)null, false);
        watcher.EventRecordWritten += Watcher_EventRecordWritten;
        watcher.Enabled = true;
    }

    void StopWatcher()
    {
        try
        {
            if (watcher != null)
            {
                watcher.Enabled = false;
                watcher.EventRecordWritten -= Watcher_EventRecordWritten;
                watcher.Dispose();
                watcher = null;
            }
        }
        catch { }
    }

    void Watcher_EventRecordWritten(object sender, EventRecordWrittenEventArgs e)
    {
        if (e.EventException != null)
        {
            SafeUi(delegate { Status("Watcher error: " + e.EventException.Message); });
            return;
        }
        if (e.EventRecord == null) return;

        using (EventRecord evt = e.EventRecord)
        {
            try
            {
                XDocument doc = XDocument.Parse(evt.ToXml());
                XNamespace ns = doc.Root.GetDefaultNamespace();

                string image = GetEventData(doc, ns, "Image");
                string imageLoaded = GetEventData(doc, ns, "ImageLoaded");
                string signedRaw = GetEventData(doc, ns, "Signed");
                string hashes = GetEventData(doc, ns, "Hashes");
                string timeCreatedUtc = SafeAttr(doc.Root.Element(ns + "System"), ns + "TimeCreated", "SystemTime");

                string signedState = NormalizeSigned(signedRaw);

                // ★キー生成:signed の場合は Image 単位にまとめる
                Tuple<string, string> key = MakeKey(image, imageLoaded, signedState);

                // allow 済みは新規に出さない
                if (allow.ContainsKey(key))
                    return;

                if (learning)
                    learningSet.Add(key);

                // 表示上の ImageLoaded は grouped 行なら固定表示
                string displayImageLoaded = (key.Item2 == SIGNED_GROUP_MARK) ? SIGNED_DISPLAY : (imageLoaded ?? "");

                SafeUi(delegate
                {
                    UpsertNewRow(key, timeCreatedUtc, image, displayImageLoaded, signedState, hashes);
                });
            }
            catch (Exception ex)
            {
                SafeUi(delegate { Status("Parse error: " + ex.Message); });
            }
        }
    }

    // ★ signed の場合は ImageLoaded を無視してキーを固定化
    static Tuple<string, string> MakeKey(string image, string imageLoaded, string signedState)
    {
        string img = image ?? "";
        string loaded = imageLoaded ?? "";

        if (signedState == "signed")
            return Tuple.Create(img, SIGNED_GROUP_MARK);

        return Tuple.Create(img, loaded);
    }

    void UpsertNewRow(Tuple<string, string> key, string lastSeenUtc, string image, string imageLoadedDisplay, string signedState, string hashes)
    {
        DataGridViewRow row;
        if (newIndex.TryGetValue(key, out row))
        {
            int count = ToInt(row.Cells[1].Value) + 1;

            row.Cells[0].Value = lastSeenUtc;
            row.Cells[1].Value = count.ToString();
            row.Cells[2].Value = image;
            row.Cells[3].Value = imageLoadedDisplay;

            // Signedはマージ(signed+unsigned 等)
            string oldSigned = (row.Cells[4].Value ?? "").ToString();
            row.Cells[4].Value = MergeSignedState(oldSigned, signedState);

            if (!string.IsNullOrEmpty(hashes))
                row.Cells[5].Value = hashes;

            gridNew.Rows.Remove(row);
            gridNew.Rows.Insert(0, row);
        }
        else
        {
            gridNew.Rows.Insert(0, lastSeenUtc, "1", image, imageLoadedDisplay, signedState, hashes);
            row = gridNew.Rows[0];
            newIndex[key] = row;
        }

        if (gridNew.Rows.Count > 5000)
        {
            DataGridViewRow last = gridNew.Rows[gridNew.Rows.Count - 1];
            string lastImage = (last.Cells[2].Value ?? "").ToString();
            string lastImageLoadedDisplay = (last.Cells[3].Value ?? "").ToString();

            // 表示からキー復元は危険なので、indexのサイズ制限は単純に末尾を捨てるだけにする
            // (厳密にやるなら row.Tag に key を入れてそれを削除する)
            // ここは安全側:行削除のみ。Indexに残ってもメモリが少し増えるだけで致命ではない。
            gridNew.Rows.RemoveAt(gridNew.Rows.Count - 1);
        }
    }

    void StartLearning()
    {
        learning = true;
        learningSet.Clear();
        Status("Learning started. (End to commit to allowlist)");
    }

    void EndLearning()
    {
        learning = false;

        int added = 0;
        foreach (var key in learningSet)
        {
            if (allow.ContainsKey(key)) continue;

            var it = new AllowItem();
            it.Image = key.Item1;
            it.ImageLoadedKey = key.Item2;               // キーとして保存(*SIGNED* の可能性あり)
            it.ImageLoadedDisplay = (key.Item2 == SIGNED_GROUP_MARK) ? SIGNED_DISPLAY : key.Item2;
            it.FirstSeenUtc = DateTime.UtcNow.ToString("o");
            it.LastSeenUtc = it.FirstSeenUtc;
            it.Count = 0;
            it.SignedState = (key.Item2 == SIGNED_GROUP_MARK) ? "signed" : "";
            it.Hashes = "";

            allow[key] = it;
            added++;
        }

        SaveAllowList();
        RefreshAllowGrid();
        Status("Learning ended. Added to allowlist: " + added);
    }

    void AllowSelectedFromNew()
    {
        if (gridNew.SelectedRows == null || gridNew.SelectedRows.Count == 0)
        {
            Status("No rows selected.");
            return;
        }

        int moved = 0;

        // Collect allow items from selection
        var items = new List<AllowItem>();
        foreach (DataGridViewRow row in gridNew.SelectedRows)
        {
            string image = (row.Cells[2].Value ?? "").ToString();
            string imageLoadedDisplay = (row.Cells[3].Value ?? "").ToString();
            string signedState = (row.Cells[4].Value ?? "").ToString();
            string hashes = (row.Cells[5].Value ?? "").ToString();

            // display が SIGNED_DISPLAY の場合は *SIGNED* に正規化
            string imageLoadedKey = (imageLoadedDisplay == SIGNED_DISPLAY) ? SIGNED_GROUP_MARK : imageLoadedDisplay;

            var it = new AllowItem();
            it.Image = image;
            it.ImageLoadedKey = imageLoadedKey;
            it.ImageLoadedDisplay = imageLoadedDisplay;
            it.FirstSeenUtc = DateTime.UtcNow.ToString("o");
            it.LastSeenUtc = it.FirstSeenUtc;
            it.Count = 0;
            it.SignedState = signedState;
            it.Hashes = hashes;

            items.Add(it);
        }

        foreach (var it in items)
        {
            var key = Tuple.Create(it.Image ?? "", it.ImageLoadedKey ?? "");
            if (!allow.ContainsKey(key))
            {
                allow[key] = it;
                moved++;
            }
            else
            {
                allow[key].SignedState = MergeSignedState(allow[key].SignedState, it.SignedState);
                if (!string.IsNullOrEmpty(it.Hashes)) allow[key].Hashes = it.Hashes;
                allow[key].LastSeenUtc = DateTime.UtcNow.ToString("o");
            }
        }

        // Remove allowed from New
        for (int i = gridNew.Rows.Count - 1; i >= 0; i--)
        {
            var row = gridNew.Rows[i];
            string image = (row.Cells[2].Value ?? "").ToString();
            string imageLoadedDisplay = (row.Cells[3].Value ?? "").ToString();

            string imageLoadedKey = (imageLoadedDisplay == SIGNED_DISPLAY) ? SIGNED_GROUP_MARK : imageLoadedDisplay;
            var key = Tuple.Create(image, imageLoadedKey);

            if (allow.ContainsKey(key))
            {
                newIndex.Remove(key);
                gridNew.Rows.RemoveAt(i);
            }
        }

        SaveAllowList();
        RefreshAllowGrid();
        Status("Allowed: " + moved);
    }

    void RefreshAllowGrid()
    {
        gridAllow.Rows.Clear();
        foreach (var kv in allow)
        {
            AllowItem it = kv.Value;
            gridAllow.Rows.Add(it.LastSeenUtc, it.Count.ToString(), it.Image, it.ImageLoadedDisplay, it.SignedState, it.Hashes);
        }
    }

    string AllowPath()
    {
        return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "allowlist.json");
    }

    void SaveAllowList()
    {
        try
        {
            // Listで保存(キーは復元できるよう ImageLoadedKey を含める)
            var list = new List<AllowItem>(allow.Values);

            var ser = new JavaScriptSerializer();
            string json = ser.Serialize(list);

            File.WriteAllText(AllowPath(), json);
        }
        catch (Exception ex)
        {
            Status("Save error: " + ex.Message);
        }
    }

    void LoadAllowList()
    {
        try
        {
            string path = AllowPath();
            if (!File.Exists(path))
                return;

            string json = File.ReadAllText(path);

            var ser = new JavaScriptSerializer();
            var list = ser.Deserialize<List<AllowItem>>(json); // Deserialize<T>() [page:5]

            allow.Clear();
            if (list != null)
            {
                foreach (var it in list)
                {
                    if (it.Image == null) it.Image = "";
                    if (it.ImageLoadedKey == null) it.ImageLoadedKey = "";
                    if (it.ImageLoadedDisplay == null)
                        it.ImageLoadedDisplay = (it.ImageLoadedKey == SIGNED_GROUP_MARK) ? SIGNED_DISPLAY : it.ImageLoadedKey;
                    if (it.SignedState == null) it.SignedState = "";
                    if (it.Hashes == null) it.Hashes = "";
                    if (it.FirstSeenUtc == null) it.FirstSeenUtc = "";
                    if (it.LastSeenUtc == null) it.LastSeenUtc = "";
                    // Count null は来ない想定だが念のため

                    var key = Tuple.Create(it.Image, it.ImageLoadedKey);
                    allow[key] = it;
                }
            }
        }
        catch (Exception ex)
        {
            Status("Load error: " + ex.Message);
        }
    }

    void Status(string s)
    {
        lblStatus.Text = s + (learning ? "  [LEARNING]" : "");
    }

    void SafeUi(MethodInvoker action)
    {
        if (InvokeRequired) BeginInvoke(action);
        else action();
    }

    static int ToInt(object v)
    {
        if (v == null) return 0;
        int x;
        return int.TryParse(v.ToString(), out x) ? x : 0;
    }

    static string SafeAttr(XElement parent, XName childName, string attrName)
    {
        if (parent == null) return "";
        XElement el = parent.Element(childName);
        if (el == null) return "";
        XAttribute a = el.Attribute(attrName);
        return a != null ? a.Value : "";
    }

    static string GetEventData(XDocument doc, XNamespace ns, string name)
    {
        XElement eventData = doc.Root.Element(ns + "EventData");
        if (eventData == null) return "";

        foreach (XElement data in eventData.Elements(ns + "Data"))
        {
            XAttribute attr = data.Attribute("Name");
            if (attr != null && attr.Value == name)
                return data.Value ?? "";
        }
        return "";
    }

    static string NormalizeSigned(string signedRaw)
    {
        if (string.IsNullOrEmpty(signedRaw)) return "";
        string s = signedRaw.Trim().ToLowerInvariant();
        if (s == "true") return "signed";
        if (s == "false") return "unsigned";
        return s;
    }

    static string MergeSignedState(string oldState, string newState)
    {
        if (string.IsNullOrEmpty(newState)) return oldState ?? "";
        if (string.IsNullOrEmpty(oldState)) return newState;

        string o = (oldState ?? "").Trim().ToLowerInvariant();
        string n = (newState ?? "").Trim().ToLowerInvariant();

        if (o == n) return o;
        if (o == "signed+unsigned" || o == "unsigned+signed") return "signed+unsigned";

        if ((o == "signed" && n == "unsigned") || (o == "unsigned" && n == "signed"))
            return "signed+unsigned";

        return o + "+" + n;
    }

    static string ShortenPath(string path)
    {
        if (string.IsNullOrEmpty(path)) return path;
        string[] parts = path.Split('\\', '/');
        if (parts.Length <= 3) return path;
        return string.Join("\\", parts, parts.Length - 3, 3);
    }

    public class AllowItem
    {
        public string Image;

        // ★保存用:キーとしての ImageLoaded(*SIGNED* を含み得る)
        public string ImageLoadedKey;

        // ★表示用:*SIGNED* (any ImageLoaded) など
        public string ImageLoadedDisplay;

        public string FirstSeenUtc;
        public string LastSeenUtc;
        public int Count;

        public string SignedState;
        public string Hashes;
    }

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
}

コンパイル

aa.csとして保存した場合

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe ^
/target:winexe /platform:x64 /out:SysmonAllowViewer.exe ^
/r:System.Windows.Forms.dll /r:System.Drawing.dll /r:System.Xml.Linq.dll /r:System.Web.Extensions.dll ^
SysmonAllowViewer.cs 

実行

管理者としてcmdを起動し実行する。
.\SysmonAllowViewer.exe

実行すると以下のようにすぐSystmonID1と7に関するログが取得され出力される。

スクリーンショット 2026-01-20 234230.png

機能

  • Start,End : Startを押すと押したタイミングからEndボタンを押す間のログが記録される
  • Save Allowlist : Endボタンを押した後にこのボタンを押すことでJsonとして、許可リストとしてデータが保存される。
  • Clear newによって、現在表示されているログをクリアできる。
  • AllowSelected : 許可したいログをクリックし、ボタンを押すことで許可リストにできる。
  • Reroed Allowlist : 保存した許可リストを再適応

用途

Startを押して、普段使用するソフトを全部起動し、Endを押して正規の挙動を記録して保存する。あとは、普通に使用している間にぽつぽつ新規のログが出てくるので都度許可していく。署名済みDLLはまとめられているが、署名のないDLLはすべて出力される(黄色表示)。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?