XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Buffers.Binary;
using System.Diagnostics;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using XFEWorkflow.Plugins.WeCom.Native.Core;
using XFEWorkflow.Plugins.WeCom.Native.Integrations;

namespace XFEWorkflow.Plugins.WeCom.Native.MemoryLab;

internal sealed record MemoryBinding(string GroupId, string GroupName, string SenderId, string SenderName);
internal sealed record MemoryMessage(string LocalId, string ServerId, string ClientMessageId,
    string ConversationId, string SenderId, uint RawType, DateTimeOffset CreatedAtUtc,
    int ContentBytes, bool ForwardWireCandidate);
internal sealed record TypedMemorySnapshot(DateTimeOffset CapturedAtUtc, int ProcessId,
    string Version, string ImageSha256, string ImageBase, IReadOnlyList<MemoryBinding> Bindings,
    IReadOnlyList<MemoryMessage> Messages, long ElapsedMilliseconds, string Limitations)
{
    public IReadOnlyList<WeComGroup> Groups { get; init; } = [];
    public IReadOnlyList<WeComMember> Contacts { get; init; } = [];
}

internal static class TypedSnapshot
{
    internal const string SupportedHash = "F46DBFB0059D4527B76B8DD3DFCD1DD45604C5BA257AF80C064E4896E02CF50E";
    private const uint ConversationVtableRva = 0x0B0A17CC;
    private const uint UserVtableRva = 0x0AF98B84;
    private const uint MessageVtableRva = 0x0AF984F0;
    private static readonly UTF8Encoding StrictUtf8 = new(false, true);

    internal static TypedMemorySnapshot Read(int? processId = null, string groupName = "", string senderName = "", CancellationToken ct = default)
    {
        Stopwatch timer = Stopwatch.StartNew();
        ClientTarget client = ClientProbe.FindRunningClient(processId);
        if (client.Version != "5.0.11.6029") throw new InvalidOperationException("Uninvestigated client version.");
        using FileStream image = File.OpenRead(client.ExecutablePath);
        string hash = Convert.ToHexString(SHA256.HashData(image));
        if (hash != SupportedHash) throw new InvalidOperationException("Client image hash differs from the investigated build.");
        using Process process = Process.GetProcessById(client.ProcessId);
        ulong imageBase = (ulong)(process.MainModule?.BaseAddress ?? throw new InvalidOperationException("No main module."));
        using ProcessMemory memory = new(client.ProcessId);
        if (memory.GetMachine().ProcessMachine != 0x014c) throw new InvalidOperationException("Expected an x86 client.");

        var types = new[]
        {
            new ObjectType("Conversation", (uint)imageBase + ConversationVtableRva, 0x1E0),
            new ObjectType("User", (uint)imageBase + UserVtableRva, 0x358),
            new ObjectType("Message", (uint)imageBase + MessageVtableRva, 0x278)
        };
        foreach (var type in types) ValidateRtti(memory, type);
        List<(string Id, string Name)> groups = [];
        List<(string Id, string Name)> members = [];
        List<byte[]> candidateMessages = [];
        byte[] chunk = new byte[1024 * 1024 + 3];
        foreach (var region in memory.Regions(0x1_0000_0000))
        {
            if (!region.IsReadablePrivateData) continue;
            for (ulong offset = 0; offset < (ulong)region.RegionSize; offset += 1024 * 1024)
            {
                ct.ThrowIfCancellationRequested();
                if (timer.Elapsed > TimeSpan.FromSeconds(30)) throw new TimeoutException("Native scan budget exceeded.");
                ulong start = (ulong)region.BaseAddress + offset;
                int count = memory.Read(start, chunk, (int)Math.Min((ulong)chunk.Length, (ulong)region.RegionSize - offset));
                foreach (var type in types)
                {
                    int position = 0;
                    while (position <= count - 4)
                    {
                        int relative = chunk.AsSpan(position, count - position).IndexOf(type.Signature);
                        if (relative < 0) break;
                        int found = position + relative;
                        position = found + 4;
                        ulong address = start + (uint)found;
                        if (address % 4 != 0) continue;
                        byte[] data = new byte[type.Size];
                        if (memory.Read(address, data, data.Length) != data.Length || U32(data, 0) != type.Vtable) continue;
                        uint strong = U32(data, 4), weak = U32(data, 8);
                        if (strong is 0 or >= 1000000 || weak is 0 or >= 1000000) continue;
                        // MSVC _Ref_count_obj2 storage begins at +16 for these 8-byte-aligned model types.
                        if (type.Name == "Conversation")
                        {
                            string? name = ReadString(memory, data, 16 + 24);
                            string? id = ReadString(memory, data, 16);
                            if (id?.StartsWith("R:", StringComparison.Ordinal) == true && name is not null) groups.Add((id, name));
                        }
                        else if (type.Name == "User")
                        {
                            string? name = ReadString(memory, data, 16 + 8);
                            ulong id = U64(data, 16);
                            if (id != 0 && name is not null) members.Add((id.ToString(CultureInfo.InvariantCulture), name));
                        }
                        else candidateMessages.Add(data[16..]);
                    }
                }
            }
        }

        var distinctGroups = groups.Distinct().ToArray();
        var distinctMembers = members.Distinct().ToArray();
        var defaultGroups = distinctGroups.Where(x => TextMatching.SameDisplayName(x.Name, groupName)).ToArray();
        var defaultMembers = distinctMembers.Where(x => TextMatching.SameDisplayName(x.Name, senderName)).ToArray();
        if (groupName.Length > 0 && defaultGroups.Length != 1 || senderName.Length > 0 && defaultMembers.Length != 1)
            throw new InvalidOperationException("旧版默认群或成员无法唯一定位,请打开对应会话或清空默认配置后连接。");
        MemoryBinding[] defaults = defaultGroups.Length == 1 && defaultMembers.Length == 1
            ? [new(defaultGroups[0].Id, defaultGroups[0].Name, defaultMembers[0].Id, defaultMembers[0].Name)] : [];
        List<MemoryMessage> messages = [];
        foreach (byte[] data in candidateMessages)
        {
            string? conversation = ReadString(memory, data, 0x28);
            var sender = U64(data, 0x48);
            if (!ReplySettings.ValidId(conversation) || sender is 0 or ulong.MaxValue) continue;
            ulong unixTime = U64(data, 0x58);
            if (unixTime < 1262304000 || unixTime > 4102444800) continue;
            string? clientId = ReadString(memory, data, 0x10);
            messages.Add(new(U64(data, 0).ToString(CultureInfo.InvariantCulture),
                U64(data, 8).ToString(CultureInfo.InvariantCulture), clientId ?? "", conversation!,
                sender.ToString(CultureInfo.InvariantCulture), U32(data, 0x50), DateTimeOffset.FromUnixTimeSeconds((long)unixTime), 0, false));
        }
        return new(DateTimeOffset.UtcNow, client.ProcessId, client.Version, hash, $"0x{imageBase:X8}",
            defaults,
            messages.DistinctBy(m => (m.ConversationId, m.LocalId, m.ClientMessageId)).OrderBy(m => m.CreatedAtUtc).ToArray(),
            timer.ElapsedMilliseconds,
            "Read-only heap snapshot. Cached/history objects may be present; transient/unloaded messages may be missed. " +
            "Only message metadata is read. This snapshot operation never sends messages.")
        { Groups = distinctGroups.DistinctBy(x => x.Id).Select(x => new WeComGroup(x.Id, x.Name)).ToArray(),
          Contacts = distinctMembers.DistinctBy(x => x.Id).Select(x => new WeComMember(x.Id, x.Name)).ToArray() };
    }

    private static void ValidateRtti(ProcessMemory memory, ObjectType type)
    {
        byte[] word = new byte[4];
        if (memory.Read(type.Vtable - 4, word, 4) != 4) throw new InvalidOperationException("Vtable is inaccessible.");
        uint locator = U32(word, 0);
        byte[] col = new byte[20];
        if (memory.Read(locator, col, col.Length) != col.Length || U32(col, 0) != 0 || U32(col, 4) != 0)
            throw new InvalidOperationException("Unexpected x86 RTTI locator.");
        uint descriptor = U32(col, 12);
        byte[] name = new byte[256];
        int count = memory.Read(descriptor + 8, name, name.Length);
        int end = name.AsSpan(0, count).IndexOf((byte)0);
        string expected = $".?AV?$_Ref_count_obj2@V{type.Name}@model@wework@@@std@@";
        if (end < 0 || Encoding.ASCII.GetString(name, 0, end) != expected)
            throw new InvalidOperationException($"RTTI mismatch for {type.Name}.");
    }

    private static byte[]? ReadBytes(ProcessMemory memory, byte[] data, int offset, uint limit)
    {
        if (offset < 0 || offset + 24 > data.Length) return null;
        uint length = U32(data, offset + 16), capacity = U32(data, offset + 20);
        if (length > limit || capacity < length || capacity > limit * 2) return null;
        if (capacity == 15 && length <= 15) return data.AsSpan(offset, (int)length).ToArray();
        if (capacity < 16) return null;
        uint address = U32(data, offset);
        if (address < 0x10000 || (ulong)address + length + 1 > 0x1_0000_0000) return null;
        byte[] result = new byte[length + 1];
        if (memory.Read(address, result, result.Length) != result.Length || result[^1] != 0) return null;
        return result[..^1];
    }

    private static string? ReadString(ProcessMemory memory, byte[] data, int offset)
    {
        byte[]? value = ReadBytes(memory, data, offset, 512);
        if (value is null) return null;
        try { return StrictUtf8.GetString(value); }
        catch (DecoderFallbackException) { return null; }
    }

    // Recognizes a repeated message wire shape observed in the memory samples:
    // outer field 1 contains a child with a sender ID, time and type. This is
    // structural evidence only; it is deliberately not exposed as a production enum mapping.
    private static bool IsForwardWireCandidate(ReadOnlySpan<byte> data)
    {
        int position = 0, children = 0;
        while (position < data.Length)
        {
            if (!TryVarint(data, ref position, out ulong key) || key == 0) return false;
            uint field = (uint)(key >> 3), wire = (uint)(key & 7);
            if (field == 1 && wire == 2)
            {
                if (!TryVarint(data, ref position, out ulong length) || length > (ulong)(data.Length - position)) return false;
                ReadOnlySpan<byte> child = data.Slice(position, (int)length);
                position += (int)length;
                int childPosition = 0;
                bool hasSender = false, hasTime = false, hasType = false;
                while (childPosition < child.Length)
                {
                    if (!TryVarint(child, ref childPosition, out ulong childKey) || childKey == 0) return false;
                    uint childField = (uint)(childKey >> 3), childWire = (uint)(childKey & 7);
                    if (childWire == 0)
                    {
                        if (!TryVarint(child, ref childPosition, out ulong value)) return false;
                        if (childField == 1) hasSender = value > 0;
                        if (childField == 2) hasTime = value is >= 1262304000 and <= 4102444800;
                        if (childField == 5) hasType = value <= 65535;
                    }
                    else if (!Skip(child, ref childPosition, childWire)) return false;
                }
                if (!hasSender || !hasTime || !hasType) return false;
                if (++children > 4096) return false;
            }
            else if (!Skip(data, ref position, wire)) return false;
        }
        return children > 0;
    }

    private static bool Skip(ReadOnlySpan<byte> data, ref int position, uint wire)
    {
        ulong length;
        if (wire == 0) return TryVarint(data, ref position, out _);
        if (wire == 1) length = 8;
        else if (wire == 5) length = 4;
        else if (wire == 2)
        {
            if (!TryVarint(data, ref position, out length)) return false;
        }
        else return false;
        if (length > (ulong)(data.Length - position)) return false;
        position += (int)length;
        return true;
    }

    private static bool TryVarint(ReadOnlySpan<byte> data, ref int position, out ulong value)
    {
        value = 0;
        for (int shift = 0; shift < 64 && position < data.Length; shift += 7)
        {
            byte next = data[position++];
            if (shift == 63 && next > 1) return false;
            value |= (ulong)(next & 127) << shift;
            if ((next & 128) == 0) return true;
        }
        return false;
    }

    internal static void VerifyWireDecoder()
    {
        byte[] sample = Convert.FromHexString("0A0A08111080E2CFAA062802");
        if (!IsForwardWireCandidate(sample) || IsForwardWireCandidate(sample.AsSpan(0, sample.Length - 1)) ||
            IsForwardWireCandidate([0x0A, 0x01, 0xFF]) || IsForwardWireCandidate([0x0A, 0xFF, 0xFF, 0x7F]) ||
            IsForwardWireCandidate([0x0B]) || IsForwardWireCandidate([0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80]))
            throw new InvalidOperationException("Bounded protobuf-wire decoder self-test failed.");
    }
    private static uint U32(byte[] data, int offset) => BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(offset, 4));
    private static ulong U64(byte[] data, int offset) => BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(offset, 8));
    private sealed record ObjectType(string Name, uint Vtable, int Size)
    {
        internal byte[] Signature { get; } = BitConverter.GetBytes(Vtable);
    }
}