초기 커밋.

This commit is contained in:
dahyeon committed 2026-04-07 13:47:17 +09:00
1 parent 257792c473
commit 914bf2d813
3 files changed
+512

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
<Solution>
<Project Path="ConsoleApp1/ConsoleApp1.csproj" />
</Solution>
+12
View File
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
</Project>
+497
View File
@@ -0,0 +1,497 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
Console.OutputEncoding = Encoding.UTF8;
Console.Title = "KakaoTalk Monitor";
const bool DebugMode = false;
const int ScanIntervalMs = 2000;
const int MaxRegionBytes = 1 * 1024 * 1024; // 1MB
const int MinRegionBytes = 1024; // 1KB
const int MaxSeenIds = 10000;
var process = FindKakaoTalkProcess();
if (process == null)
{
Console.WriteLine("[!] KakaoTalk 실행 안됨");
return;
}
Console.WriteLine($"[*] KakaoTalk PID: {process.Id}");
IntPtr hProc = NativeMethods.OpenProcess(
NativeMethods.PROCESS_VM_READ | NativeMethods.PROCESS_QUERY_INFORMATION,
false,
process.Id);
if (hProc == IntPtr.Zero)
{
Console.WriteLine("[!] OpenProcess 실패 - 관리자 권한 필요 가능");
return;
}
Console.WriteLine("[*] 모니터링 시작...\n");
var monitor = new KakaoMonitor(hProc, DebugMode, MaxSeenIds, MinRegionBytes, MaxRegionBytes);
bool running = true;
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
running = false;
Console.WriteLine("\n[*] 종료 중...");
};
try
{
while (running)
{
try
{
monitor.ScanMemory();
}
catch (Exception ex)
{
Console.WriteLine($"[오류] {ex.Message}");
}
Thread.Sleep(ScanIntervalMs);
}
}
finally
{
NativeMethods.CloseHandle(hProc);
Console.WriteLine("[*] 프로세스 핸들 닫힘");
}
static Process? FindKakaoTalkProcess()
{
var procs = Process.GetProcessesByName("KakaoTalk");
if (procs.Length > 0) return procs[0];
return null;
}
// ============================
// Main monitor
// ============================
sealed class KakaoMonitor
{
private readonly IntPtr _hProc;
private readonly bool _debug;
private readonly int _minRegionBytes;
private readonly int _maxRegionBytes;
private readonly HashSet<long> _seenIds = new();
private readonly Queue<long> _seenQueue = new();
private readonly byte[] _pattern = Encoding.ASCII.GetBytes("\"message\":\"");
private int _scanRound = 0;
public KakaoMonitor(IntPtr hProc, bool debug, int maxSeenIds, int minRegionBytes, int maxRegionBytes)
{
_hProc = hProc;
_debug = debug;
MaxSeenIds = maxSeenIds;
_minRegionBytes = minRegionBytes;
_maxRegionBytes = maxRegionBytes;
}
public int MaxSeenIds { get; }
public void ScanMemory()
{
IntPtr addr = IntPtr.Zero;
int regionCount = 0;
int scannedCount = 0;
int matchedCount = 0;
while (true)
{
int result = NativeMethods.VirtualQueryEx(
_hProc,
addr,
out var mbi,
Marshal.SizeOf<NativeMethods.MEMORY_BASIC_INFORMATION>());
if (result == 0)
break;
regionCount++;
long baseAddr = mbi.BaseAddress.ToInt64();
long regionSize = mbi.RegionSize.ToInt64();
bool readable =
mbi.State == NativeMethods.MEM_COMMIT &&
(mbi.Protect == NativeMethods.PAGE_READWRITE ||
mbi.Protect == NativeMethods.PAGE_READONLY ||
mbi.Protect == NativeMethods.PAGE_WRITECOPY);
if (readable &&
regionSize >= _minRegionBytes &&
regionSize <= _maxRegionBytes &&
regionSize <= int.MaxValue)
{
scannedCount++;
try
{
byte[] buffer = new byte[(int)regionSize];
if (NativeMethods.ReadProcessMemory(
_hProc,
mbi.BaseAddress,
buffer,
buffer.Length,
out int bytesRead) &&
bytesRead > 0)
{
matchedCount += ScanBuffer(buffer, bytesRead);
}
}
catch (Exception ex)
{
if (_debug)
Console.WriteLine($"[DEBUG] region read fail @0x{baseAddr:X}: {ex.Message}");
}
}
long next = baseAddr + regionSize;
if (next <= baseAddr || next < 0)
break;
addr = new IntPtr(next);
}
_scanRound++;
if (_debug || _scanRound % 15 == 0)
{
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine($"[DEBUG] round={_scanRound}, region={regionCount}, scanned={scannedCount}, matched={matchedCount}, seen={_seenIds.Count}");
Console.ResetColor();
}
}
private int ScanBuffer(byte[] buf, int length)
{
int found = 0;
for (int i = 0; i <= length - _pattern.Length; i++)
{
if (!MatchAt(buf, i, _pattern))
continue;
int jsonStart = FindJsonStart(buf, i, 4096);
if (jsonStart < 0)
{
if (_debug) Console.WriteLine("[DEBUG] JSON 시작점({) 못찾음");
continue;
}
string? json = ExtractJson(buf, jsonStart, length);
if (json == null)
{
if (_debug) Console.WriteLine("[DEBUG] JSON 추출 실패");
continue;
}
if (!LooksLikeKakaoMessageJson(json))
{
if (_debug) Console.WriteLine("[DEBUG] KakaoMessage 후보 아님");
continue;
}
try
{
var msg = JsonSerializer.Deserialize(json, JsonContext.Default.KakaoMessage);
if (!IsValidMessage(msg))
continue;
if (!MarkSeen(msg!.MsgId))
continue;
found++;
OnMessage(msg!);
}
catch (Exception ex)
{
if (_debug)
{
string preview = json.Length > 160 ? json[..160] + "..." : json;
Console.WriteLine($"[DEBUG] 파싱오류: {ex.Message}");
Console.WriteLine($"[DEBUG] JSON preview: {preview}");
}
}
}
return found;
}
private bool MatchAt(byte[] buf, int pos, byte[] pattern)
{
for (int i = 0; i < pattern.Length; i++)
{
if (buf[pos + i] != pattern[i])
return false;
}
return true;
}
private int FindJsonStart(byte[] buf, int from, int maxBacktrack)
{
int min = Math.Max(0, from - maxBacktrack);
for (int i = from; i >= min; i--)
{
if (buf[i] == (byte)'{')
return i;
}
return -1;
}
private static bool LooksLikeKakaoMessageJson(string json)
{
return json.Contains("\"msgId\"") &&
json.Contains("\"chatId\"") &&
json.Contains("\"authorId\"") &&
json.Contains("\"sendAt\"") &&
json.Contains("\"message\"");
}
private static bool IsValidMessage(KakaoMessage? msg)
{
if (msg == null) return false;
if (msg.MsgId == 0) return false;
if (msg.ChatId == 0) return false;
if (msg.AuthorId == 0) return false;
if (msg.SendAt <= 0) return false;
if (msg.Deleted) return false;
// 텍스트가 없더라도 attachment가 있으면 이미지/기타 메시지일 수 있음
bool hasText = !string.IsNullOrWhiteSpace(msg.Message);
bool hasAttachment = !string.IsNullOrWhiteSpace(msg.Attachment);
return hasText || hasAttachment;
}
private bool MarkSeen(long msgId)
{
if (!_seenIds.Add(msgId))
return false;
_seenQueue.Enqueue(msgId);
while (_seenQueue.Count > MaxSeenIds)
{
long old = _seenQueue.Dequeue();
_seenIds.Remove(old);
}
return true;
}
private void OnMessage(KakaoMessage msg)
{
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.Write($"[{msg.SentAt:HH:mm:ss}] ");
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.Write($"chat:{msg.ChatId} ");
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write($"@{msg.AuthorId} ");
if (msg.IsImage)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("[이미지]");
}
else if (msg.IsReply)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"[답글] → {msg.Message}");
}
else
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"→ {msg.Message}");
}
Console.ResetColor();
}
private static string? ExtractJson(byte[] buf, int start, int length)
{
int depth = 0;
bool inString = false;
bool escaped = false;
for (int i = start; i < length; i++)
{
byte b = buf[i];
if (inString)
{
if (escaped)
{
escaped = false;
continue;
}
if (b == (byte)'\\')
{
escaped = true;
continue;
}
if (b == (byte)'"')
{
inString = false;
continue;
}
continue;
}
if (b == (byte)'"')
{
inString = true;
continue;
}
if (b == (byte)'{')
{
depth++;
}
else if (b == (byte)'}')
{
depth--;
if (depth == 0)
{
try
{
return Encoding.UTF8.GetString(buf, start, i - start + 1);
}
catch
{
return null;
}
}
if (depth < 0)
return null;
}
}
return null;
}
}
// ============================
// Model
// ============================
record KakaoMessage(
[property: JsonPropertyName("authorId")] long AuthorId,
[property: JsonPropertyName("chatId")] long ChatId,
[property: JsonPropertyName("logId")] long LogId,
[property: JsonPropertyName("msgId")] long MsgId,
[property: JsonPropertyName("prevId")] long PrevId,
[property: JsonPropertyName("threadId")] long ThreadId,
[property: JsonPropertyName("sendAt")] long SendAt,
[property: JsonPropertyName("message")] string Message,
[property: JsonPropertyName("attachment")] string Attachment,
[property: JsonPropertyName("supplement")] string Supplement,
[property: JsonPropertyName("type")] int Type,
[property: JsonPropertyName("scope")] int Scope,
[property: JsonPropertyName("deleted")] bool Deleted,
[property: JsonPropertyName("referer")] int Referer,
[property: JsonPropertyName("revision")] int Revision,
[property: JsonPropertyName("rewrite")] int Rewrite
)
{
public DateTimeOffset SentAt =>
DateTimeOffset.FromUnixTimeSeconds(SendAt).ToLocalTime();
public bool IsText => Type == 1;
public bool IsImage => Type == 2 || LooksLikeImageAttachment(Attachment);
public bool IsReply => ThreadId != 0 || PrevId != 0;
private static bool LooksLikeImageAttachment(string? attachment)
{
if (string.IsNullOrWhiteSpace(attachment))
return false;
return attachment.Contains("image", StringComparison.OrdinalIgnoreCase) ||
attachment.Contains("thumbnail", StringComparison.OrdinalIgnoreCase) ||
attachment.Contains(".jpg", StringComparison.OrdinalIgnoreCase) ||
attachment.Contains(".jpeg", StringComparison.OrdinalIgnoreCase) ||
attachment.Contains(".png", StringComparison.OrdinalIgnoreCase) ||
attachment.Contains(".webp", StringComparison.OrdinalIgnoreCase);
}
}
[JsonSerializable(typeof(KakaoMessage))]
internal partial class JsonContext : JsonSerializerContext
{
}
// ============================
// Native methods
// ============================
static class NativeMethods
{
public const int PROCESS_VM_READ = 0x0010;
public const int PROCESS_QUERY_INFORMATION = 0x0400;
public const uint MEM_COMMIT = 0x1000;
public const uint PAGE_READONLY = 0x02;
public const uint PAGE_READWRITE = 0x04;
public const uint PAGE_WRITECOPY = 0x08;
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(int access, bool inherit, int pid);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ReadProcessMemory(
IntPtr hProc,
IntPtr lpBaseAddress,
[Out] byte[] lpBuffer,
int dwSize,
out int lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int VirtualQueryEx(
IntPtr hProcess,
IntPtr lpAddress,
out MEMORY_BASIC_INFORMATION lpBuffer,
int dwLength);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject);
[StructLayout(LayoutKind.Sequential)]
public struct MEMORY_BASIC_INFORMATION
{
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public uint AllocationProtect;
public IntPtr RegionSize;
public uint State;
public uint Protect;
public uint Type;
}
}