71 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash 1c5fab1645 Fix: Stop the client dropping chat messages that begin with e
CChatManager::OnReceive opened with the same heartbeat guard the other
managers use, `if (szBuffer[0] == TOKEN_HEARTBEAT) return;`, before it
looked at the length. TOKEN_HEARTBEAT is 101, which is also the letter e,
and this channel carries free text rather than command bytes, so every
message starting with e -- "echo", "error", anything -- was silently
discarded. The sender never learned: the server's chat dialog had already
written the text into its own log, so the two sides disagreed about what
was said.

The guard is dead code here. Heartbeats travel on the main connection
only, as a multi-byte [101][Heartbeat] packet consumed by the main
dispatcher; the server never sends one on a chat sub-connection. Delete
it and keep the length check that follows.

The server keeps prepending a space when the GBK payload starts with
101, because already-deployed clients still carry the guard and losing
the message outright is worse than an invisible leading space. Note the
same guard, harmless today, still sits in the machine, file, proxy and
screen-hide managers.

Verified with the Debug instance and a local Debug client: with the
server's space temporarily disabled, chat_send "echo test" and
"second line" both showed up verbatim in the client dialog (read back
with WM_GETTEXT); with the space restored the first arrives as
" echo test". Details in docs/Mcp_Chat_Design.md section 5.

Co-Authored-By: deepseek-flash
2026-10-25 14:57:47 +01:00
yuanyuanxianganddeepseek-flash cc3e11d30d Improve: Cover protocol and policy error codes in the MCP smoke test
The suite only exercised the happy paths, so a regression in the
negative paths -- unknown method, unknown tool, a missing required
argument, an oversized batch or a policy refusal -- would have gone
unnoticed. Add those checks alongside a section that reads the switches
from get_server_status, picks a feature that is actually turned off and
asserts its tool answers -32006; with every switch on it skips rather
than guessing, and with -AuditLog it also asserts the refusal shows up
as CALL_DENIED.

Document the full error-code table in section 12, including which codes
mean "retry with different arguments" and which mean "this is a policy
decision, retrying is pointless", and note that a batch call never
fails as a whole for per-host errors.

Verified against the Debug instance with McpKeylog temporarily set to
zero: get_keylog refused with -32006 and the audit log gained the
matching CALL_DENIED line, 34 checks passing; with the switch restored
32 pass, and 37 with a search path.

Co-Authored-By: deepseek-flash
2026-10-25 14:44:45 +01:00
yuanyuanxianganddeepseek-flash 7c5bf3e73d Feature: Filter search_file results by size, mtime and slim fields
Add four optional arguments to search_file that narrow the match list
after the client has returned it: min_size and max_size in bytes,
modified_after in either YYYY-MM-DD or YYYY-MM-DD HH:MM:SS form, and
name_only to keep just path and name per entry. The client still runs
the same name-matched recursive search, so these filters cut the
response size and the reasoning work on our side, not the scan time on
the host -- the summary sentence says so and totalAll keeps the
pre-filter count so a too-narrow condition is obvious. Invalid values
(negative sizes, an inverted range, a malformed timestamp) are rejected
with -32602 before any packet goes out.

The timestamp validator only accepted the ten-character form because
its shape loop never allowed the two colons, which rejected every
nineteen-character value; the loop now whitelists them.

Smoke tests cover the unchanged totalAll under a size filter, the slim
name_only payload and a rejected timestamp, for 33 checks when the
search path is supplied. Design notes are in section 11.4.

Co-Authored-By: deepseek-flash
2026-10-25 14:41:52 +01:00
yuanyuanxianganddeepseek-flash 929065e7be Feature: Filter the MCP host lists by group, OS and client type
list_online_hosts and list_all_hosts could only page, so finding "the
hosts in this group" or "the Linux ones" meant walking pages or falling
back to search_hosts, which has no client type filter and treats online
and offline hosts differently.

Both tools now accept group, os and client_type. They are substring
matches, combined with AND and case-insensitive over ASCII, matching the
semantics search_hosts already used, and the shared implementation keeps
the two tools from drifting apart. The filter runs before paging, so
total counts the matches and totalAll keeps the pre-filter size, and the
summary switches to the "matches" wording with a trailing line naming
the unfiltered size - a mistyped condition then shows up immediately
instead of silently returning nothing.

Offline hosts carry no clientType in their stored record, so a
client_type filter never matches them; the tool description says so and
points at os for that case.

Verified on the Debug instance: client_type=exe matches the single EXE
host while client_type=lnx matches nothing and still reports totalAll=1;
list_all_hosts with group=default matches all 3161 recorded hosts and
splits them into 1 online and 3160 offline, and os=zzz matches none. The
smoke test gains two checks and passes 28/28.

Co-Authored-By: deepseek-flash
2026-10-25 14:37:28 +01:00
yuanyuanxianganddeepseek-flash 5ce453797c Feature: Add a get_server_status tool to the MCP server
Answering "did my rebuild actually take effect" or "why was that tool
refused" used to mean reading list_online_hosts and get_audit_log and
inferring the rest. A single read-only call now returns the server's own
state: brand and version, the exe link time (taken from the file's last
write, which unlike __DATE__ reflects the whole build), how long the
process has been up, the address and port MCP is actually listening on,
every MCP switch, online and offline host counts, the number of sessions
in flight per family, and how many source IPs are currently blocked.

The bind and port are recorded by Start rather than re-read from the
configuration, so the tool reports what the listener really got. Session
counters take each subsystem's lock in turn and release it immediately,
so the numbers are an estimate of one moment, not a consistent snapshot.
Nothing sensitive is exposed: the token and the command whitelist never
appear, and the switches are reported as booleans only.

The tool is registered as read-only, non-destructive, idempotent and
server-local, which brings tools/list to 53 entries. The smoke test gains
three checks for it, including one that fails if a token-shaped field
ever appears in the output.

Verified on the Debug instance: the summary line reports version, uptime
and listener correctly, sessions.terminal goes 0 to 1 while a persistent
terminal is open and back to 0 after terminal_close, and the smoke test
passes 26/26.

Co-Authored-By: deepseek-flash
2026-10-25 14:35:19 +01:00
yuanyuanxianganddeepseek-flash ae37e812ee Feature: Page and filter the MCP audit log tool
get_audit_log used to hand back every entry in the main window's message
mirror on each call. The mirror is a 1000-entry ring buffer, so a busy
server returned a lot of text the caller never looked at, and there was
no way to ask for just the MCP entries or just the ones mentioning a
particular subject.

The tool now takes the same limit/offset pair as the other list tools
and two optional substring filters: type matches the type column and
keyword matches the message text, both case-insensitive. Filtering runs
before paging, so total counts the matches while totalAll keeps the size
of the whole mirror, and the summary line adds the pre-filter count when
a filter is in use so a typo is easy to spot. The GBK to UTF-8
conversion moved into the filter loop so the comparison happens between
strings in the same encoding, still under the dialog's critical section.

The output schema gains total/totalAll/offset/limit/hasMore, and the
smoke test now asserts the paging fields, the limit bound and an empty
result for a filter that cannot match, bringing it to 23 checks.

Verified on the Debug instance: limit=2 returns entries 1-2 then 3-4
with hasMore set, offset=999 reports the out-of-range text, type=mcp
matches the "MCP命令执行" entry, type=提示 matches both hint types and
keyword=监听 matches the listening-port line.

Co-Authored-By: deepseek-flash
2026-10-25 14:31:14 +01:00
yuanyuanxianganddeepseek-flash d9a1a9ebcb Fix: Record policy refusals in the MCP audit log
Every policy denial - read-only mode, one of the Mcp* switches turned
off, or a host that lacks the required capability - answers -32006. The
audit log only ever showed CALL_FAIL for those, which lumped them
together with parameter errors, offline hosts and timeouts, so after the
fact there was no way to tell "nobody called this" from "it was blocked
by policy".

The hooks all live in one place: the tools/call exit in the HTTP
handler now also reads error.code and error.message from the response it
already parses, and appends a CALL_DENIED event when the code is -32006.
The original CALL_FAIL line is still written, so its statistics keep
their old meaning, and the reason text is the fixed English sentence
each branch already returns - no tool arguments or user input reach the
log. Tool names taken from the request are flattened to a single line
first, both in the denied event and in the existing CALL_OK/CALL_FAIL
lines, so a crafted name cannot forge extra audit rows.

Also refresh the stale note in the design document that still called the
client search MAX_PATH overflow unfixed; the source was fixed in
8f718d9, but already-deployed clients still carry it, which is why the
smoke test keeps its search cases opt-in.

Verified on the Debug instance: with McpFileTransfer temporarily set to
0, download_file returns -32006 and the audit log gains the expected
CALL_DENIED line right after its CALL_FAIL; with the switch restored the
same call is CALL_OK again and no denied line appears. The read-only
smoke test passes 20/20.

Co-Authored-By: deepseek-flash
2026-10-25 14:28:16 +01:00
yuanyuanxianganddeepseek-flash 16f23e164c Fix: Clear the file transfer session when its sub-connection drops
A file transfer session holds raw pointers to its file-manager and
stream sub-connections, but nothing on the offline path looked at them.
OfflineProc cleans up terminal, remote-control and chat sessions and
skipped file transfers entirely, so a client that disconnected in the
middle of a transfer left the session pointing at a context that went
back to the connection pool. When the tool thread timed out it called
CancelIO on that stale pointer, which could cancel somebody else's
connection.

Add a context-to-device table next to the sessions, kept under the same
mutex and erased by ClearFileTransfer so a recycled pointer is never
mistaken for a live one. OfflineProc now calls
OnFileTransferContextClosed, which drops both pointers. A dropped
stream sub-connection means the transfer cannot complete, so it also
fails the session with error 1003 and wakes the waiting thread; the
file-manager sub-connection only issues the command and its loss is not
treated as a failure of the transfer itself.

Verified against the debug client: killing it 1.2 s into a 500 MB
download returns "Connection lost: the transfer sub-connection closed"
after about 1 s instead of waiting out timeout_ms, and the server stays
up. After the client restarts, two consecutive downloads and one upload
still work.

Co-Authored-By: deepseek-flash
2026-10-25 14:20:13 +01:00
yuanyuanxianganddeepseek-flash 39f0928de7 Fix: Finish a directory-only download instead of waiting for the timeout
The completion check compared filesDone against totalFiles minus
directoryCount and only ran on COMMAND_FILE_COMPLETE_V2. The client
sends no COMPLETE for directory entries, so a download of an empty
directory, or of a tree that holds only subdirectories, had zero
expected files and could never satisfy the check. The call sat there
until timeout_ms expired (600 s by default) and then reported 1002.

Mark the session done as soon as the directory entries account for
every entry the client declared. Verified with the debug client: an
empty directory returns in 0.2 s with zero files, a tree of nested
subdirectories returns in 0.2 s with the directories created, and a
directory holding three files still downloads them with the same
sizes and hashes as before.

Co-Authored-By: deepseek-flash
2026-10-25 14:16:46 +01:00
yuanyuanxianganddeepseek-flash 8f718d9b39 Fix: Stop the client file search from overflowing its path buffers
SearchFilesRecursive built "%s\*.*" and "%s\%s" with wsprintf into
char[MAX_PATH] buffers and never checked the lengths. The recursion
allows 32 levels, so a search from a drive root accumulates paths well
past 260 characters and writes off the end of the stack frame. Debug
builds raise Run-Time Check Failure #2 and the dialog blocks the search
thread; release builds corrupt the stack silently.

Check the length before each build and skip the entry when the full
path does not fit, so neither the name nor the recursion below it is
recorded. The root directory is checked once at function entry, which
also stops an over-long root from being enumerated at all.

Apply the same guard to the directory listing paths in both file
managers, and bound the search pattern built from the incoming keyword.
Zero-initialize the buffers filled by ExpandEnvironmentStringsA so a
failed expansion is treated as an empty path instead of reading
uninitialized stack.

Verified against the debug client with a full C:\ scan (10,000 results,
finished, no dialog) and a repeated deep search afterwards.

Co-Authored-By: deepseek-flash
2026-10-25 14:05:25 +01:00
yuanyuanxianganddeepseek-flash abe7e99a77 Feature: Harden the MCP transport and add non-destructive host tools
Cap MCP request bodies at 2 MB, set a 15 s idle read timeout and a 60 s
write timeout, and give httplib an explicit 32-thread pool: long tools
such as chat_wait hold a worker for up to 55 s, and the default pool of
8 to 15 left other callers queued.

Every tool returned by tools/list now carries readOnlyHint,
destructiveHint, idempotentHint and openWorldHint. The table is
per-tool; anything not registered defaults to destructive so a new
write tool cannot silently look harmless. Read-only tools are forced
to destructiveHint=false.

get_host_detail appends the technical fields the host store already
holds (cpuCores, memoryGB, systemBits, programBits, user, isAdmin,
installTime, expiredDate, monitors, exeVersion, clientPath, pid,
publicIp). The JSON writer is pinned to 15 significant digits so
memoryGB renders as 27.8 instead of 27.800000000000001. list hosts
output is unchanged.

Add host_set_remark and host_set_watch_level. Both validate the host
against the store, are refused in readonly mode, repaint the affected
row, and are audited without recording the value written.

Add search_file, which drives the client file-manager search channel
and returns paged results. The root path is normalized before sending:
the client enumerates with wsprintf("%s\*.*"), so a trailing
backslash produced C:\*.* and FindFirstFile failed, returning zero
hits instantly. The client only searches recursively, so non-recursive
requests are filtered server-side by comparing the parent directory.
Collection stops at 5000 records or 4 MB and the client is told to
stop; on timeout the partial results are returned. Search result
packets are never closed early: the sub-connection stays open until
TOKEN_SEARCH_FILE_FINISH, because the client's search thread holds a
pointer into the file manager object.

Batch reads report a skipped counter and are bounded to 50 ids and a
50 s deadline.

Add tools/mcp_smoke.ps1, a read-only end-to-end smoke test that asserts
auth rejection, the payload limit, annotation coverage, paging fields
and the main read tools. It takes the token from the environment and
never prints it.

Document all of the above in docs/Mcp_Design.md section 10, including
the client-side MAX_PATH stack overflow that a deep search_file call
can trigger, together with the workaround of searching shallow
directories.

Co-Authored-By: deepseek-flash
2026-10-25 13:59:17 +01:00
yuanyuanxianganddeepseek-flash ac5b174b5f Feature: Add offline hosts, batch reads and MCP hardening
Expose hosts the server already knows about. list_all_hosts enumerates
both live contexts and the historical records in the client list, with
authStatus as a three-state string instead of a boolean. search_hosts
now honours online=false instead of returning an empty list, while the
default stays online-only so existing callers see the same results.
get_host_detail falls back to the last known record for an offline host
rather than failing with -32002.

Let read-only tools take an ids array of up to 50 hosts in one call.
The batch path reuses the single-host dispatcher and pages per host, so
behaviour cannot drift; write tools reject ids with -32602 so a mistake
cannot fan out across machines.

Add get_keylog behind its own McpKeylog switch. It drives the client's
existing keylogger sub-connection, accumulates the streamed text for a
bounded window and byte cap, then closes the sub-connection and returns
UTF-8 lines. The client pushes its buffered history first, so a result
contains both history and fresh keystrokes; the tool description says so.

Harden the endpoint. Failed bearer checks are counted per source IP and
ten failures within a minute block the IP for fifteen minutes. Auth
failures and tool calls append to logs\mcp_audit.log with metadata only:
no token, no arguments, no response bodies, and rotation at 5 MB. Loopback
sources are audited but never blocked, because the built-in frp tunnel
makes every remote request arrive from 127.0.0.1 and banning that address
would lock out legitimate clients along with the attacker.

Give list-style tools one pagination contract (limit/offset plus
total/totalAll/hasMore) and fix the generated schemas so id and ids are
genuine alternatives: the stale required:[id] left over from the
single-host schema would otherwise reject ids-only calls.

Co-Authored-By: deepseek-flash
2026-10-25 12:44:45 +01:00
yuanyuanxianganddeepseek-flash cc0e4bbd7a Fix: Pass win keys down the hook chain while a chat is locked
During a locked chat the client installs a WH_KEYBOARD_LL hook that
swallows Alt+Tab, Alt+F4, Alt+Esc, Ctrl+Esc and the Win keys, so the person
sitting at the machine cannot get out of the lock. The hook returned 1
without calling CallNextHookEx. Low-level hooks run last installed first,
and this one is installed later than the server's hotkey forwarding hook,
so it sits in front of it: returning 1 ended the chain and the forwarding
hook never saw those keys. With YAMA running on the same machine as the
client, Win shortcuts stopped reaching the remote host for as long as the
lock was up.

The event is now passed down the chain before it is swallowed.
CallNextHookEx hands the event to the other hooks only, not to the system
or the shell, so the local shell is still blocked and the lock behaves
exactly as before, while the forwarding hook can see the key and act on
it.

Co-Authored-By: deepseek-flash
2026-10-25 02:40:30 +02:00
yuanyuanxianganddeepseek-flash 73aa2725b9 Fix: Pick an MSBuild instance that has ATL, not the first found
build.ps1 took the first MSBuild.exe matching a hardcoded glob under
%ProgramFiles% / %ProgramFiles(x86)%. On a machine that has both a
command-line build tools instance and an IDE, that is the build tools one.
It ships the v142 compiler, but ATL is a separate optional component there,
so the link step failed with LNK1104 on atls.lib while the same sources
built cleanly in the IDE whose instance carries ATL. The vswhere lookup
meant to cover installations on other drives never ran, because the glob
had already matched.

Candidates are now validated against VC\Tools\MSVC\*\atlmfc\lib\x86\atls.lib
before being accepted, every rejected instance is reported, and the vswhere
lookup enumerates all instances and applies the same check, so an
installation on another drive is found as well. When no instance carries
ATL the first candidate is still used, with a warning, which keeps the
previous behaviour and lets MSBuild emit the more specific error.

The script is also saved as UTF-8 with BOM: Windows PowerShell 5.1 reads a
BOM-less UTF-8 script as ANSI, which turns some Chinese comment characters
into a trailing backtick and swallows the following line.

This commit also carries the pending build script work: the Go server
builder, the -ClientOnly fast path, and the serverd / client debug presets
in build.cmd. Skills.md documents the two new presets.

Co-Authored-By: deepseek-flash
2026-10-25 02:38:46 +02:00
yuanyuanxianganddeepseek-flash 37d0297f07 Fix: Keep the keylogger thread pumping so the hook chain stays alive
The low-level keyboard hook callback runs only while the thread that
installed it pumps messages, but KeyLogger() gated PeekMessage on
IsConnected(). With offline recording enabled (kbrecord=Yes) and no
keyboard sub-connection, the hook stayed installed while its thread
never pumped, so every keystroke on the machine stalled against
LowLevelHooksTimeout (300 ms by default) and the hook was eventually
dropped by the system. Because the client installs its hook after YAMA
installs its own, the client's hook sits in front of YAMA's in the
chain, and the starved events broke the key pairs YAMA needs: Win
shortcuts and Ctrl+V forwarding stopped working while ordinary typing
was unaffected.

Pump messages unconditionally; this code is only reached while the hook
is installed, and the offline-record path installs it even without a
keyboard sub-connection.

Co-Authored-By: deepseek-flash
2026-10-25 02:22:17 +02:00
yuanyuanxianganddeepseek-flash 7160ea8f42 Fix: Stop the online-host list header from flickering
The list header is a child window of the list view, and
LVS_EX_DOUBLEBUFFER only covers the item area. The list view was created
without WS_CLIPCHILDREN, so every whole-list Invalidate or RedrawWindow
also erased the header with the class background brush before repainting
it. On top of that, AdjustColumnWidths ran on every WM_SIZE and issued an
unconditional SetColumnWidth per column, and each call repaints the
header. The result was an occasional one-frame blink of the header row:
irregular, low frequency, and confined to the header because the item
area is double-buffered.

Both lists now carry WS_CLIPCHILDREN, RDW_ALLCHILDREN was dropped from the
redraw calls that only need the list body (that flag forces child
repaints even when they are clipped), and column widths are only set when
they actually change.

The header still needs its background erase, but only for the strip to
the right of the last column: AdjustColumnWidths reserves 20px there and
the header's own paint stops at the last column, so that strip is colored
by WM_ERASEBKGND alone. Skipping the erase entirely left it black after a
minimize/restore cycle, when the window contents are discarded. The
header subclass now fills just that strip with COLOR_3DFACE and leaves the
column area untouched, which keeps the flicker fix, and the needRefresh
branch of OnSize forces an erase-redraw of the header so the strip is
repainted on minimize/restore and maximize/normalize.

Verified with a standalone probe that mirrors the list setup for the
header erase counts, and by rebuilding the app and checking the
minimize/restore case reported against the first version of this change.

Co-Authored-By: deepseek-flash
2026-10-24 15:45:49 +02:00
yuanyuanxianganddeepseek-flash 434812f87d Fix: Show the instant-message popup on packed clients
Clients packaged as SC_AES/sRDI shellcode run the payload image as raw
shellcode inside the loader stub, so the instant-message manager was
handed the stub's module handle. The stub's resource section carries no
IDD_DIALOG, and Windows rejects resource APIs on manually mapped images,
so DialogBoxParamA failed (error 1812 on Windows 11) and the bottom-right
popup never appeared after the operator sent a message.

The popup now falls back to an embedded compiled dialog template
generated from the IDD_DIALOG block in Script.rc and verified
byte-for-byte against the resource in the built ghost.exe. When the
resource lookup fails, the dialog is created with
DialogBoxIndirectParamA instead. Deployments where the resource lookup
already works keep the original path unchanged.

The incoming text is now terminated at the copied length. The server
sends the message body without a trailing NUL, so a message that filled
the 1024-byte buffer left SetDlgItemText reading past the end.

The title is now set with SetWindowTextW before the window is shown.
DialogBoxParamA converts the template's UTF-16 caption through the
system ANSI code page, so the Chinese title turned into "???" on 1252
systems (verified locally with a caption containing a character outside
CP936). The title follows the UI language: Chinese systems keep the
Chinese title, everything else shows "Message". The message body still
uses the ANSI path, preserving the existing per-ACP semantics.

Co-Authored-By: deepseek-flash
2026-10-23 12:22:44 +02:00
yuanyuanxianganddeepseek-flash c99a1c375e Feature: Add MCP tools for remote chat with the client user
Add chat_open, chat_send, chat_wait and chat_close to the MCP tool set,
behind a new McpChat switch that defaults to off and is independent of
the read-only switch. The tools reuse the existing client chat link: the
main connection sends COMMAND_CHAT, the client opens a sub-connection
with TOKEN_CONN_AUTH and TOKEN_CHAT_START, the server answers with
COMMAND_NEXT_CHAT, and both directions then carry raw CP936 text.

Sessions are per host and held in shared pointers under their own mutex,
so a waiting chat_wait survives a close or a dropped sub-connection, and
chat_send is serialised per session. Text is converted strictly between
UTF-8 and CP936: invalid UTF-8, characters GBK cannot represent (emoji,
accented letters) and messages over the client's 4000-byte buffer are
rejected with -32602 instead of being mangled. A one-second settle delay
after the sub-connection binds keeps the first message from reaching the
client before its chat window exists.

The routing hooks run before the host-management hooks in MessageHandle
and clear the route in OfflineProc before the context leaves the list. A
five-second tombstone absorbs a late TOKEN_CHAT_START after a timeout, so
a failed chat_open does not pop the MFC chat dialog. Idle sessions are
swept on every tool call, and audit entries record the session id and
byte counts only, never message bodies.

The settings dialog gains the chat checkbox and the translated labels
for all three languages, and the strict UTF-8 to CP936 helpers move from
McpMachine.cpp to McpInternal so both tool families can share them.

Co-Authored-By: deepseek-flash
2026-10-23 11:19:21 +02:00
yuanyuanxianganddeepseek-flash fff7c67af6 Fix: Make the remote chat dialog Unicode and loader-independent
Clients packaged as SC_AES/sRDI shellcode run the payload image as raw
shellcode inside the loader stub, so the chat manager was handed the
stub's module handle. The stub's resource section only carries a
manifest, and Windows resource APIs reject manually mapped images
outright, so creating IDD_CHAT failed and the chat thread exited before
the window ever existed.

The chat window now falls back to an embedded compiled dialog template
that is byte-identical to the IDD_CHAT resource, and the title-bar icon
is rebuilt directly from the module's own resource directory instead of
LoadIcon, bypassing the loader on both paths. The PE walking code checks
every offset against SizeOfImage and the resource directory size, so a
malformed or truncated image returns NULL instead of faulting.
Deployments where the resource lookup already works keep the original
code path unchanged.

The dialog is now created and driven with the wide-character API. The
client is still an MBCS build, but an ANSI dialog renders text with the
system code page, so GBK chat text turned into mojibake on German and
other non-936 systems. Incoming text is converted CP936 to UTF-16 and
outgoing text strictly back to CP936; characters GBK cannot represent
(emoji, accented letters) are refused with a visible notice instead of
silently becoming '?'. Static labels follow the system UI language, and
IDD_CHAT now uses the scalable MS Shell Dlg face so font linking can
supply CJK glyphs.

The window is now positioned explicitly as well. DS_CENTER in the
template put it at the work area origin on the three-monitor host: the
centred position came out negative there and Windows clamps out-of-range
creation coordinates to that origin. It is centred in the work area of
the monitor under the cursor instead, falling back to SPI_GETWORKAREA.

Teardown no longer leaves a hidden window behind either. The dialog
thread blocked in GetMessageW and never saw m_bRun cleared, while the
destructor waited for that thread before sending the message that would
have destroyed the window, so a close command that never arrived (the
sub-connection already gone, or WaitSendIdle timing out before CancelIO)
leaked the window, the dialog thread and the manager loop. The
destructor now destroys the window first, the loop checks m_bRun before
blocking, and it destroys the window itself if it exits first.

Co-Authored-By: deepseek-flash
2026-10-23 11:19:21 +02:00
yuanyuanxianganddeepseek-flash 3ae6298746 Fix: Align macOS mouse coordinates with the captured display
The macOS client derived its logical screen size from [NSScreen mainScreen]
while it captured CGMainDisplayID. In clamshell mode with an external display
the former can still report the disabled built-in panel (1470x956) while the
captured frame is 1280x1024, so every injected point was scaled by
logical/encode and drifted linearly with the distance from the top left
corner, independently on each axis. Take the logical size from
CGDisplayBounds of the captured display instead, and report the same bounds
in the login resolution.

For hosts that still run the old client, the remote desktop dialog gains a
per-host mouse calibration in its system menu. The factors are stored by
client ID together with the reported resolution and the captured frame size,
so they stop applying once the client is upgraded or a different display is
captured, and come back automatically when the original display returns.
When no calibration has been saved the dialog pre-fills the factors from
frame/reported, but only for macOS clients, because the other clients derive
their conversion from the captured display itself and a mismatching report
there would be misleading.

Co-Authored-By: deepseek-flash
2026-10-22 11:33:39 +02:00
yuanyuanxianganddeepseek-flash 38cd207f5d Feature: Add host management and connection management MCP tools
Expose the online-list TLS column through list_online_hosts, search_hosts
and get_host_detail. The value comes from the flag the client reports at
login, so old clients always read false.

Add list_network_connections and kill_network_connection on top of the
connection manager sub-connection protocol. The kill path matches the
original 110-byte record instead of rebuilding addresses, supports a dry
run, refuses UDP/IPv6 targets, and verifies that the quadruple really
disappeared instead of assuming success.

Add a host_* family backed by the machine manager protocol: ten read
tools covering every tab of the host management dialog, and four
recoverable write tools for process freeze/thaw, window restore/hide/
maximize/minimize, service start/stop/pause/continue/restart, and
scheduled task run/stop. Every write re-reads the snapshot before sending
and re-checks afterwards, reporting -32009 for stale targets rather than
acting blindly. The family is gated by McpMachine, the risky subset by
McpMachineDangerous, and writes additionally require read-only mode to
be off.

Route managed sub-connections from MessageHandle and OfflineProc, keep
the single-in-flight rule by sharing the pending table with a request
kind, and move the shared JSON/lock/encoding helpers into McpInternal so
both tool families use one implementation. Settings dialog, design docs
and en_US/zh_TW/de_DE translations are updated accordingly.

Co-Authored-By: deepseek-flash
2026-10-21 20:01:41 +02:00
yuanyuanxianganddeepseek-flash 6c8336b497 Fix: Repair task actions and harden machine management
Scheduled task actions never worked end to end: the server built task
packets with Unicode-style lengths in a MultiByte build, the client had
no dispatch for the run/stop/delete/create commands, and the directory
column was derived by replacing every occurrence of the task name, which
misplaced tasks whose name also appeared in a parent folder. Packets are
now assembled with narrow strings, the four commands are routed to
RunOrStopTask/DelTask/CreateTask, and the folder is taken from the task
path suffix only. The task list reply is trimmed to its real length
instead of sending the whole 32 KB scratch buffer.

On the client side, thawing a process resumed a single thread, the
inject output path was copied from a narrow string using a wide-character
length, and an empty window list dereferenced a NULL buffer. The service
list leaked its enumeration block and one service handle per skipped
entry, and the description was copied without a bound. Service start and
stop now validate every handle, initialize the status structure, and stop
synchronously before the start that follows a restart request, which
previously always failed because the service was still in STOP_PENDING.
Deleting a process used to test only the low byte of the PID and leaked
the process handle on early exits, and a failed path conversion kept the
previous process image name. The IE history timestamp wrote minutes and
seconds in the wrong order, the favorites reader queried and closed an
uninitialized registry key, software enumeration never closed its subkeys,
and the task scheduler objects were not released after use.

The network state list now frees the module, snapshot, and extended
tables on every exit path, uses HeapFree for tables allocated on the
process heap, and no longer calls an export that may be missing. Growth
failures everywhere keep the original buffer instead of overwriting the
pointer, the hosts reader rejects an invalid file size, and the COM task
walk releases definitions and folders.

Co-Authored-By: deepseek-flash
2026-10-20 21:48:13 +02:00
yuanyuanxianganddeepseek-flash c208b7368e Fix: Format net-state addresses as narrow strings on the client
The client is a MultiByte build, so the destination buffers are char[]
and _T("%s:%u") expands to an ANSI format that expects a char pointer.
The code nevertheless converted inet_ntoa() output to WCHAR* first, and
the ANSI %s stopped at the zero byte that follows the first wide
character. Every address therefore collapsed to its leading digit, so
192.168.0.55:443 was shown as 1 and 0.0.0.0:80 as 0 in the local and
remote address columns of the network connections tab.

Write the address and port straight into the char buffers with
sprintf_s in all four enumeration paths (legacy and Vista APIs, TCP and
UDP), and drop the now unused char2wchar_t helper.

Co-Authored-By: deepseek-flash
2026-10-20 21:24:47 +02:00
yuanyuanxianganddeepseek-flash 15a50db0a7 Fix: Keep IPv4 address bytes in network order for connection list
iphlpapi stores the address in network byte order inside the memory of
the DWORD, it is not a host-order integer. For 192.168.0.55 the DWORD
value on x86 is 0x3700A8C0 while its bytes are C0 A8 00 37, so shifting
the value by 24/16/8/0 produced 37 00 A8 C0 and the dialog rendered
"55.0.168.192" for both the local and remote address.

Copy the DWORD with memcpy instead, which preserves the memory layout
that inet_ntop and SetTcpEntry both expect. GetAddr4 is changed the
same way, otherwise a forced disconnect would rebuild a wrong address
and miss the target connection.

Co-Authored-By: deepseek-flash
2026-10-20 21:15:45 +02:00
yuanyuanxianganddeepseek-flash ca35e6e26f Feature: Add menu icons for the advanced and disclaimer entries
Add four 16x16 bitmaps and wire them through the existing m_bmOnline
table. The three entries under the "Advanced" menu had no icon at all,
and the disclaimer entry shared the help question mark with "what is
this", so the two were indistinguishable.

- desktop quality levels: a monitor with three ascending level bars in
  the screen
- screen preview levels: a thumbnail card with a sun, a folded corner
  and layered hills
- file transfer speed: a half-circle gauge with a red needle
- disclaimer: a document with a folded corner and an amber exclamation
  badge, so it no longer looks like the help entry

Grow the bitmap array to 75 entries and reserve resource IDs 412-415.

Co-Authored-By: deepseek-flash
2026-10-20 21:13:05 +02:00
yuanyuanxiang 679136e73e Release v1.4.1 2026-10-20 15:00:35 +02:00
yuanyuanxiang b637c94e24 Feature: Allow user to select an installation location for client 2026-10-20 13:12:16 +02:00
yuanyuanxianganddeepseek-flash f76cd79bb0 Fix: Renew expired licenses from today and report the actual expiry
Preset renewal stored its target date as the old expiry plus the entered
days, while the authorization actually issued to the client is always
today plus a day count. For a license that had already expired, the
preset date was therefore in the past: SendPendingRenewal clamped the
day count to one, the client received a one-day license starting today,
but the renewal tip and the logs still printed the stale preset date.
The result was a message such as "renewed until 2026-05-30" while the
license really ran until tomorrow.

Presetting a renewal now bases the new date on today when the license
has already expired, and on the original expiry date otherwise, which
matches the one-day-per-day extension admins expect for live licenses.
The renewal dialog and the success prompt state which base was used, so
the computed date is never ambiguous. Renewal tips and both logging
paths (heartbeat-driven SendPendingRenewal and client-requested
GenerateRenewalInfo) now print the date that was actually issued, which
also corrects legacy preset records whose stored date has already
passed.

Co-Authored-By: deepseek-flash
2026-10-19 15:15:49 +02:00
yuanyuanxianganddeepseek-flash 39c8daa9b0 Fix: Keep the audit log open across WebSocket reconnects
Hiding the browser tab while the audit log was open closed the socket,
because the visibility handler treats only the remote screen, terminal
and wall pages as streaming pages. Returning to the tab reconnected the
socket, and the onopen restore path took its catch-all branch, which
navigated to the device list. The audit log therefore vanished whenever
the browser was minimized.

The catch-all branch now leaves the active page alone when it is the
audit log, and only refreshes the device list in the background. Every
other page keeps the previous behaviour: the login page advances with a
cached token, and the terminal page falls back to the device list
because its session died with the socket. Audit results already rendered
stay on screen, so the admin can keep reading without re-querying.

Co-Authored-By: deepseek-flash
2026-10-19 10:39:36 +02:00
yuanyuanxianganddeepseek-flash cd4f3675fd Improve: Replace native browser prompts with themed in-app dialogs
Native alert() and confirm() render their buttons in the browser or OS
locale, so on a German system prompts such as the Clear Screen Wall
confirmation showed German labels that disagreed with the rest of the
web UI. Both are now served by a single themed modal that reuses the
logout confirmation styling: an info variant with one OK button for
notices, and a danger variant with Cancel/OK for destructive actions.

The alert helper is fire-and-forget, while the confirm helper returns a
Promise, so the two call sites that need an answer (clearWall and
deleteUser) are now async. Dialog title and message are written with
textContent so device names, user names and server error strings can
never be interpreted as markup. A pending dialog is resolved as
cancelled when another one supersedes it, keeping callers from hanging,
and clicking the backdrop or pressing Escape closes the dialog. Remote
keyboard forwarding now ignores keys while a dialog is open.

Co-Authored-By: deepseek-flash
2026-10-19 10:27:09 +02:00
yuanyuanxianganddeepseek-flash bbb3d8c2fa Fix: Recover proxied client IPs and fit audit filters on phones
The MFC web server now resolves the real client address from the
WebSocket upgrade request when the TCP peer is loopback, so audit records
and login rate limiting stop reporting the reverse proxy's 127.0.0.1.
X-Forwarded-For is preferred over X-Real-IP because its last hop is the
address the local proxy appended; a client-supplied header list cannot
forge it. Forwarded headers are ignored for non-loopback peers so a
client connecting directly over the internet cannot spoof its identity
or rotate addresses to bypass throttling. FRP deployments can keep using
the existing Proxy Protocol v2 support instead.

Collapse the audit log search conditions behind a toolbar toggle that
starts closed and switches to an accent-colored "Hide filters" state
while the panel is open. On portrait phones the panel uses one control
per row, and From/To move their border and padding onto a wrapper so the
iOS WebKit datetime-local width miscalculation cannot overflow the
viewport.

Co-Authored-By: deepseek-flash
2026-10-19 10:05:58 +02:00
yuanyuanxianganddeepseek-flash ca671d6453 Feature: In-memory web audit log for the MFC server
Add a process-local security audit trail to the Windows server's web
console, mirroring the Go server's event names and reply shape. The ring
keeps the most recent 1000 events since process start and is never
persisted.

- New query_audit WebSocket command, admin-only, with time/event/actor/
  IP/device/keyword/warn-only filters and pagination; the reply is the
  audit_result payload the existing Audit Log page already understands.
  The challenge advertises caps.auditLog so browsers enable the button.
- Record logins (success, failure, throttling, salt probes), WebSocket
  connect/close, screen and terminal session start/stop/denials,
  clipboard transfers (byte counts only), RDP resets, and admin user
  mutations.
- Repeated failed logins and username probes are de-duplicated per
  connection so scanners cannot flood the ring.
- Audit writes never hold m_ClientsMutex: disconnect paths snapshot the
  client identity before the map entry is erased, and offline-device
  stops are audited after the clients lock is released.

Co-Authored-By: deepseek-flash
2026-10-18 19:16:17 +02:00
yuanyuanxianganddeepseek-flash a522424491 Feature: Security audit logging with admin web query page
Add a dedicated security audit trail to the Go server. Login attempts,
authorization denials, WebSocket lifecycle, remote screen and terminal
sessions, clipboard operations, device authentication and admin mutations
now emit stable JSON-line events (audit=true, event=<name>) to a separate
logs/audit.log, mirrored to server.log. The path is configurable through
YAMA_AUDIT_LOG and the separate file can be switched off. Records never
contain passcodes, password hashes, tokens or clipboard contents, and
untrusted string fields are stripped of control characters and truncated
so they cannot forge log lines.

Expose the trail to administrators through a query_audit WebSocket command
and an Audit Log page in the web UI. The page filters by time range, event
(exact or prefix), actor, IP, device id, keyword and warning level, pages
newest-first, and stays hidden unless the server advertises the auditLog
capability, so older C++ servers degrade cleanly. Each query scans at most
the newest 32 MB of the current file to bound latency, records itself as
admin.audit.query, and tolerates torn or non-audit lines.

Add unit tests for event emission and redaction, query filtering, paging,
malformed lines, missing or disabled audit files, and handler
authorization.

Co-Authored-By: deepseek-flash
2026-10-18 18:44:17 +02:00
yuanyuanxianganddeepseek-flash b1ddec1b8a Feature: Offline device history with delete and remote uninstall
Persist every device that has ever logged in to the Go server in a small
JSON store (devices.json, overridable with YAMA_DEVICES_FILE and capped by
YAMA_DEVICES_MAX, default 1000 newest). The store follows the users.json
convention: atomic temp-file write with fsync and rename, a 500 ms debounce
for bursts of reconnects, first_seen preserved across logins, and pruning
that evicts offline records before devices that are still connected.
Devices connected at shutdown are stamped offline before the final flush so
last_seen stays accurate across restarts.

The server advertises an offlineDevices capability and device_list now
appends historical devices that are not online, marked with online:false and
last_seen. The web UI shows an Offline checkbox after Total/Showing (state
kept in localStorage), renders offline cards dimmed and dashed, and always
lists them in the screen-wall sidebar. Older servers without the capability
keep the online-only list.

Grid and List cards gain a delete button after the terminal button, admin
only, behind a confirmation dialog. Deleting an offline device removes its
history record; deleting an online device first sends the single-byte
TOKEN_UNINSTALL command (matching the MFC OnOnlineUninstall flow) and then
removes the record too, so the device does not come back as a dead offline
entry. The agent's own disconnect then runs the existing cleanup path:
screen and terminal sub-connections are closed, the hub entry is removed,
and browsers receive device_offline to release their watch sets, wall
sessions, and stream references. Wall mode exposes no delete action.

Tests cover history persistence/pruning/recovery, offline ordering, the
device_list merge, and all three delete outcomes (offline removal, online
uninstall with a single 0x3F byte, and viewer rejection).

Co-Authored-By: deepseek-flash
2026-10-18 17:54:30 +02:00
yuanyuanxianganddeepseek-flash 1922f87dd2 Feature: Multi-device screen wall on the Go server
Bring the Go web backend up to parity with the MFC server's screen wall.
A browser tab can now stream several devices over one WebSocket: the
single `watching` field becomes a per-connection watch set guarded by the
hub mutex, capped at 32 devices per socket. The challenge advertises
`caps.multiWatch` and `caps.keyframeRequest`, binary frames stay keyed by
the low 32 bits of the device ID, and connect/disconnect replies echo the
device id and request id so the wall can route concurrent responses.

Input commands (mouse, key, clipboard, rdp_reset) resolve their target
from the watch set: an explicit id must be a current subscription, and an
absent id is accepted only while exactly one device is watched. Legacy
frontends that do not send `multiWatch` keep replace-all semantics, so a
repeated device switch cannot grow the set without bound. Offline
devices are removed from every watch set, and teardown is computed from a
snapshot taken outside the hub lock to avoid re-entrant locking.

Add the `keyframe` command: it replays the cached IDR, then asks the
device to emit a fresh one, rate-limited to one request per device per
second. This exposed a Go-only corruption bug: the client answers the
request with TOKEN_KEYFRAME (134), which the dispatcher treated as a
no-op. That token only appears on forced IDRs because the client's GOP is
effectively infinite, so the dropped IDR left the browser decoding
P-frames against a reference chain it never received, producing
persistent garbling. Relay it as a keyframe instead. Also drop the
cached IDR when the resolution changes, mirroring the C++ server, so a
late joiner cannot receive an old-geometry keyframe.

Add tests for the watch-set transitions and for relaying TOKEN_KEYFRAME.

Co-Authored-By: deepseek-flash
2026-10-18 11:51:28 +02:00
yuanyuanxianganddeepseek-flash 8eab26c1f6 Feature: Web screen wall for multi-device live monitoring
Add a third view to the web UI, the screen wall, which shows several
devices at once in one tab with 1x1 / 2x2 / 3x3 / 4x4 / 5x5 layouts and a
device sidebar on the left. Tiles are monitoring-only; clicking one
enlarges that device into the existing single-screen page for control, and
Back returns to the wall. The same device can be added several times: all
tiles of one device share a single decoder and a single stream.

The wall decodes at most 9 streams on desktop and 4 on touch devices.
Tiles beyond the budget keep receiving frames but have their decoder
closed and show the last frame plus a Paused badge; they are promoted
automatically when a live tile goes away. Subscriptions are reference
counted on the client (streams map with owner sets), so a stream is only
connected on the 0 -> 1 transition and disconnected on 1 -> 0, and the
wall and the single-screen page can share one device without tearing the
stream down.

Server side, WebClient now holds a set of watched devices instead of a
single id. A new multiWatch command flag selects set semantics, while
clients without it keep the old replace-all behaviour, so an old frontend
against the new server is unchanged. connect and disconnect responses echo
id and req so the frontend can route them, input commands carry an id and
are resolved against the watch set (dropped when the set has several
devices and no id), and the per-client watch set is capped at 32.

For fast recovery after a pause or when joining late, the server caches
each device's raw IDR payload and replays it on connect and on a new
keyframe command, then asks the client to force a new IDR. The client gets
COMMAND_SCREEN_KEYFRAME_REQ = 169 and an atomic request flag that is only
cleared after an IDR actually came out of the encoder, so a failed capture
or EAGAIN does not lose the request. The frontend retries the keyframe
request up to three times; an old client that ignores the command simply
recovers on the next natural GOP.

Also fix the keyframe cache double wrapping: BroadcastH264Frame used to
cache the full packet header and HandleConnect wrapped it again. The cache
now stores data + 9, len - 9 and every sender wraps it through
BuildFramePacket, and the cache is cleared on cold start and on resolution
change. StopRemoteDesktop is always called outside m_ClientsMutex, with
the ids collected under the lock first.

Co-Authored-By: deepseek-flash
2026-10-18 11:03:17 +02:00
yuanyuanxianganddeepseek-v4-pro 04f4eb9947 Fix: share web login session across browser tabs
The login token and role were stored in sessionStorage, which is
isolated per tab, so opening a second tab forced a fresh password
login. Switch every token/role read and write to localStorage so all
tabs on the same origin share the session and a new tab auto-resumes
it on load. Expiry (device_list ok:false) and explicit logout still
clear it as before.

Co-Authored-By: deepseek-v4-pro
2026-10-17 22:44:50 +02:00
yuanyuanxianganddeepseek-v4-pro 5cea1167be Feature: Web remote desktop phone IME input box ("I")
Add an "I" button to the mobile shortcut bar that opens a chat-style
input box pinned above the virtual keyboard. Text is delivered to the
remote through the existing clipboard bridge (clipboard_set + synthetic
Ctrl+V); an empty box turns Enter/Backspace into remote Enter/Backspace
so the phone can submit and edit text in the focused window. The box
soft-wraps and auto-grows up to four lines.

The box is a <textarea>, so the desktop key-forwarding handlers now skip
TEXTAREA targets as well, which stops an empty-box Backspace from being
forwarded twice (once by imeBackspace, once by the document handler).

Co-Authored-By: deepseek-v4-pro
2026-10-17 22:06:46 +02:00
yuanyuanxianganddeepseek-v4-pro 0c04f7516b Feature: Web remote desktop bidirectional text clipboard sync
Add keyboard-shortcut (Ctrl+C / Ctrl+X / Ctrl+V) text clipboard transfer
between the browser and the remote desktop, reusing the clipboard protocol
that already exists in the native viewer (COMMAND_SCREEN_GET_CLIPBOARD=24,
COMMAND_SCREEN_SET_CLIPBOARD=25, TOKEN_CLIPBOARD_TEXT=118) so the client
needs no change.

Local -> remote: pressing Ctrl+V reads the browser clipboard, pushes it to
the remote clipboard (UTF-8 -> GBK, matching the client's CF_TEXT/ANSI
handling) and then synthesizes a remote Ctrl+V so the pasted text is the
newly delivered one.

Remote -> local: Ctrl+C or Ctrl+X is forwarded to the remote as usual and,
after a short delay, the remote clipboard is pulled back and written to the
browser clipboard for a later local Ctrl+V.

Both the MFC and Go servers get the same three clipboard signaling paths
(clipboard_set, clipboard_get, clipboard_text) so the shared single-page
frontend behaves identically on either backend.

Co-Authored-By: deepseek-v4-pro
2026-10-17 19:52:38 +02:00
yuanyuanxianganddeepseek-v4-pro e6b4fe3a85 Fix: reissue client_id on clone collision and harden V1 file-transfer command
撞 ID 的克隆机(同镜像 MachineGuid 相同导致 client_id 相同)此前会被服务端暂存为
替补、永远无法转正,从而不显示在主机列表。现在服务端检测到「client_id 相同但主机名
不同」时,主动下发 COMMAND_REGEN_CLIENT_ID,客户端在旧 ID 基础上掺随机 UUID 重算后
重连,以新 ID 正常上线;触发条件仅看主机名,排除 IP 漂移与纯用户名变化,避免误伤
正常重连的机器。

同时加固 V1 服务端→客户端文件传输:COMMAND_GET_FILE 指令的一次性 md5 令牌绑定登记
时的客户端源 IP(PutCmd/PopCmd 均带 peerIP),防止异常客户端冒用;并对指令包增加边界
校验(len 与 NUL 结尾),杜绝无 NUL 包导致的越界读。

Co-Authored-By: deepseek-v4-pro
2026-10-17 09:29:33 +02:00
yuanyuanxianganddeepseek-v4-pro d3a339247b Fix: reconnect after server restart without reinstalling the loader
The S_SERVER_EXIT respawn fix previously lived in test.cpp, which a
deployed TestRun.exe cannot pick up without reinstalling. Move the
reconnect decision into ClientDll::IsStoped(): when the master instance
is in S_SERVER_EXIT, report reconnectable immediately instead of waiting
for live shared instances to drain, so the already-deployed loader
reconnects against a hot-loaded DLL.

Shared instances stay connected to their own servers, preserving the
IsSharedRunning contract that the master's state change must not tear
them down.

Also guard the RUNNING_PARALLEL branch so re-entering StartClient on
reconnect spawns parallel instances once instead of duplicating them.

Co-Authored-By: deepseek-v4-pro
2026-10-16 21:36:52 +02:00
yuanyuanxianganddeepseek-v4-pro 33986f4893 Fix: shared-host respawn block and web login brand placeholder
Two unrelated fixes bundled here.

1. Client respawn (ClientDll.cpp EasyRun/Run, test.cpp Run): after a host
   is shared or transferred to another server, restarting the master
   (server A) left the host's main instance stuck, because the respawn
   loop waited on IsStoped() (g_bThreadExit && GetCount()==0), which never
   becomes true while a still-alive shared instance holds AddCount(1).
   S_SERVER_EXIT now triggers an immediate reconnect without waiting for
   shared instances; client-exit / update still waits for all instances to
   drain. Verified by 100 restart cycles.

2. Web login page (WebService.cpp): the MFC web server only substituted
   __BASE_PATH__ in index.html and left __BRAND_NAME__ as a literal token
   in the login page title/heading. Substitute it with "SimpleRemoter" to
   match the original branding and the Go server's default.

Co-Authored-By: deepseek-v4-pro
2026-10-16 21:08:42 +02:00
yuanyuanxianganddeepseek-v4-pro e5f5720867 Fix: Add missing FileManagerDlg translations to language files
FileManagerDlg.cpp still had several user-facing Chinese strings with no
entry in en_US/zh_TW/de_DE: the "invalid file handle", "no files
selected", "V2 transfer started", "V2 download request sent" and "main
connection not found" messages. Add translations for all five.

The "main connection not found" string contained a literal '=', which
CIniParser treats as the key/value delimiter, so it could never match as
a translation key. Reword it to "clientID %llu" (no '=') so the key
round-trips. The two Mprintf log lines on the V2 checksum path are
log-only and intentionally left untranslated.

Co-Authored-By: deepseek-v4-pro
2026-10-16 13:54:00 +02:00
yuanyuanxianganddeepseek-v4-pro d7b49a3d06 Feat: Add whitelist action to log-list right-click menu
Adds a "白名单" item after "解除封禁" in the message-log context menu.
It extracts the IP from each selected log entry, asks for confirmation,
then adds it to the shared IPWhitelist singleton — which IOCPServer and
the DLL rate limiter already consult live — so the entry takes effect on
new connections immediately, without a restart. The whitelist is
persisted to settings\IPWhitelist the same way the Network dialog does.

- An IP already in the whitelist is reported as such and skipped.
- An IP in the IP blacklist (banned) is reported as banned and skipped,
  rather than silently removed from the blacklist.
- Menu item, confirmation, and result strings are added to the
  en_US/zh_TW/de_DE language files.

Co-Authored-By: deepseek-v4-pro
2026-10-16 13:16:33 +02:00
yuanyuanxianganddeepseek-v4-pro c85039ea0a Fix: Online-host list column-toggle leaves ghost artifact after last column
CListCtrlEx::OnEraseBkgnd (with m_bSkipEraseBkgnd) only erases the empty
area below the last item, not the horizontal strip right of the last
column (the ~20px scrollbar reserve AdjustColumnWidths always leaves).
Changing the column count via SetColumnVisible/ToggleColumnVisibility
redistributed widths but never repainted with background erase, so stale
pixels from the previous last column lingered next to the new one (e.g.
after "TLS") until a tab switch or minimize/restore forced a full redraw.

Mirror the proven OnSize needRefresh path: temporarily lift the
skip-erase flag and issue a full RedrawWindow with
RDW_ERASE|RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_UPDATENOW after each
visibility change.

Co-Authored-By: deepseek-v4-pro
2026-10-16 13:03:05 +02:00
yuanyuanxianganddeepseek-v4-pro a447452521 Fix: Silence SOCKET_DLLLOADER log flood and tighten device-port logging
SOCKET_DLLLOADER (210) is the shellcode / memory-DLL loader asking the
server for the full DLL payload before it can load the client. The MFC
master console serves it via SendServerDll; the Go web device port has no
payload to hand out, so every memory-DLL client startup/reconnect fell
into the default dispatch branch and logged "Unhandled command 210",
flooding the log. Add a protocol constant and drop the command silently.

While auditing the device-port logging surface:

- Downgrade wrapTLS's per-connection hex-dump lines and the screen-spy
  "[timing]" cold-start line from Info to Debug (they fire once per TCP
  connection / screen view and are diagnostics, not operational events).

- Distinguish a sub-connection hijack attempt from a plain orphan: when a
  screen/terminal sub-conn claims a MasterID from a source IP other than
  the device's login conn, log a dedicated Warn instead of mislabeling it
  as "orphan ... unknown device".

Co-Authored-By: deepseek-v4-pro
2026-10-16 12:26:35 +02:00
yuanyuanxiang 614b03994c Fix: No permission to share/transfer a client host issue 2026-10-16 07:35:53 +02:00
yuanyuanxianganddeepseek-v4-pro 99e3bcbc6d Feat: Per-client TLS transport toggle (TLS column + remote enable/disable)
Add a per-client TLS transport toggle controlled from the server, using the
presence of the client's trust-anchor certificate in the registry as the
single source of truth (no separate tls_enable flag).

- Client reports its TLS status via a new RES_TLS token (cert present -> 1)
  appended to LOGIN_INFOR's reserved field.
- Server online list gains a "TLS" column after the permission column.
- The "experimental features" right-click menu gains "TLS传输" / "取消TLS"
  with confirmation and a guard that prompts (instead of sending) when the
  server has no TLS certificate ready.
- New COMMAND_TLS_ENABLE / COMMAND_TLS_DISABLE (166/167): the server pushes
  its cert PEM into the client registry settings\tls_cert (enable) or deletes
  it (disable). The client picks this up on next startup via the existing
  ReadTrustAnchor logic, so the switch is non-live by design.
- Icons and en_US/zh_TW/de_DE translations for the new menu items.

Co-Authored-By: deepseek-v4-pro
2026-10-16 07:04:54 +02:00
yuanyuanxianganddeepseek-v4-pro 8f02e73b9c Fix: Refresh MCP menu checkmark after settings change
The MCP settings menu item's checkmark was set only once at startup in
CreateSolidMenu, so toggling MCP in the settings dialog left the menu stale
until restart. Update the checkmark in OnMcpSettings after the dialog closes
so it matches [settings] McpEnabled immediately.

Co-Authored-By: deepseek-v4-pro
2026-10-15 19:43:58 +02:00
yuanyuanxianganddeepseek-v4-pro 7651ee8602 Feat: ConnAuth HMAC verification gated by YAMA_CONN_AUTH_KEY
Verify the HMAC-SHA256 signature and timestamp of device sub-connections
(screen/terminal/file) when the YAMA_CONN_AUTH_KEY environment variable is
set. With the key set, a sub-connection whose signature or clock skew fails
is answered with a non-OK ConnAuth status and dropped; without the key the
legacy always-OK behavior is preserved.

The key is never compiled in: it is read from the environment at startup, so
no secret enters the repository. Source-IP binding in hub.BindScreenConn
remains in place as defense-in-depth.

Co-Authored-By: deepseek-v4-pro
2026-10-15 19:43:58 +02:00
yuanyuanxianganddeepseek-v4-pro 4ff965a2b4 Feat: White-label web UI branding for subpath deployments
When the web remote desktop is mounted under another domain's subpath
(YAMA_WEB_BASE_PATH non-empty), read the product title from
YAMA_WEB_BRAND_NAME, substitute it for the SimpleRemoter titles and
PWA manifest name, and strip the security notice and website links.
The brand name is JSON- and HTML-escaped so operator input can't
produce malformed output. Served from the domain root, the official
SimpleRemoter branding is left unchanged.

Co-Authored-By: deepseek-v4-pro
2026-10-15 19:43:58 +02:00
yuanyuanxianganddeepseek-v4-pro 77b688c981 Feat: Fold hostname into client ID and log clone-ID collisions
Cloned miniPC images share the same MachineGuid, so their client_id
collides and only one host appears in the list. Fold the hostname into
the V2 client-ID hash so hosts with distinct names no longer collide.
Already-persisted client IDs are unchanged: they recompute only after
the settings/client_id registry value is cleared.

Server side, when a login reuses an existing client_id but the hostname,
IP, or username differs, emit a WARN diagnostic before assigning the
connection to the standby list. Observation-only, no behavior change.

Co-Authored-By: deepseek-v4-pro
2026-10-15 19:43:58 +02:00
yuanyuanxianganddeepseek-v4-pro c93f09e9ac Feat: TLS certificate menu and config dialog for the MFC server
Add a "TLS证书" item to the Extensions menu below "MCP设置" that opens a
runtime-built dialog to enable one-way TLS and set the certificate and
private-key paths. On OK it writes the [tls] Enabled/CertPath/KeyPath keys
and calls ServerTlsIdentity::Load() so the change takes effect for new
connections immediately (design doc §7.1), mirroring the existing
CMcpSettingsDlg runtime-template pattern. All new strings are wired into
the en_US / zh_TW / de_DE language files, and the menu item is gated by
HIDE_MENU_TLS_CERTIFICATE / MF_TLS_CERTIFICATE like MCP settings.

Co-Authored-By: deepseek-v4-pro
2026-10-15 19:42:52 +02:00
yuanyuanxianganddeepseek-v4-pro 96b9eea70a Feat: One-way TLS transport for the MFC server
Add optional one-way TLS to the MFC server (server/2015Remote) so the device
port can serve both TLS clients and legacy plaintext clients on the same port,
mirroring the Go server.

Server: on a connection's first bytes, sniff for a TLS ClientHello (0x16 0x03
+ handshake type 0x01). When [tls] Enabled=1 and the identity loads, hand the
socket to a short-lived blocking handshake thread (Option A) running Schannel
AcceptSecurityContext, then decrypt on recv and encrypt on send; plaintext
connections replay the sniffed bytes straight into the existing parse path, so
the plaintext code path is otherwise unchanged. The identity is loaded once
from [tls] CertPath/KeyPath as PEM + CNG (PKCS#8) — the same key pair the Go
server uses — and a missing [tls] section, an empty value, or a load failure
leaves plaintext serving intact and fail-closes any TLS ClientHello.

Also fix two transport-reliability bugs that surfaced end-to-end:
- send path: encrypt only the freshly appended plaintext tail and post a
  single IOWrite wake-up guarded by a bSendPending flag, so back-to-back small
  sends (terminal resize -> COMMAND_NEXT -> resize) no longer run concurrent
  WSASends over the same mutable buffer (client saw DecryptMessage failures,
  with WSAGetLastError() = 6001 / ERROR_DECRYPTION_FAILED);
- client Recv: keep the handshake's unconsumed tail bytes in m_raw and drain
  them before the next recv, and log the real SECURITY_STATUS on
  DecryptMessage failure instead of the stale Winsock error.

Co-Authored-By: deepseek-v4-pro
2026-10-15 13:48:27 +02:00
yuanyuanxianganddeepseek-v4-pro ca0d7626d2 Feat: One-way TLS transport for the device port
Add optional one-way TLS on the device port (6543), enabled per client via a
pinned trust anchor, so new clients encrypt their transport while legacy
plaintext clients keep working unchanged.

Server (server/go): sniff each accepted connection and wrap TLS peers
(ClientHello 0x16 0x03 + handshake type 0x01) in crypto/tls with MinVersion
TLS 1.2; everything else stays on the plaintext path. TLS is enabled only when
both YAMA_TLS_CERT and YAMA_TLS_KEY are set, and a cert/key load failure fails
startup loudly rather than silently serving plaintext.

Client (client/, Windows): Schannel one-way TLS. When the trust anchor is
present — registry value Software\<exehash>\settings\tls_cert (REG_SZ holding
the PEM), with fallback to settings.ini [settings] tls_cert or yama-ca.pem
beside the exe — every outbound connection (main + sub-connections) completes
a TLS 1.2 handshake before the app protocol and is strictly pinned to that
anchor via a chain engine with hExclusiveRoot; any handshake/cert failure is
fail-closed (no plaintext downgrade). Send uses EncryptMessage; Recv uses
DecryptMessage and reads plaintext from the stream-mode DATA segment (bufs[1])
rather than the record header.

Co-Authored-By: deepseek-v4-pro
2026-10-14 21:10:21 +02:00
yuanyuanxianganddeepseek-v4-pro 8d4c118ae6 Fix: Skip video capture when camera fails to open
CCaptureVideo::Open now returns S_FALSE when BindVideoFilter cannot bind a capture device, instead of S_OK. CVideoManager records the result in m_bVideoOpened and exits WorkThread before SendBitMapInfor, so a host without a webcam no longer sends a 0x0 BITMAPINFO to the controller.

Co-Authored-By: deepseek-v4-pro
2026-10-13 17:05:37 +02:00
yuanyuanxianganddeepseek-v4-pro d477cbfee9 Fix: Treat a zero MaxBufferedBytes as disabled
Consistent with the per-IP limits, a zero cap now means "no limit" instead
of closing every connection after its first byte, so a Config built from
zero values cannot wedge the listener.

Co-Authored-By: deepseek-v4-pro
2026-10-13 16:28:13 +02:00
yuanyuanxianganddeepseek-v4-pro 870a5832ea Security: Cap per-connection inbound buffer to prevent memory DoS
The protocol length field is validated to 50 MiB, but a peer that sends
bytes which never assemble into a complete packet — for example an HTTP-mask
envelope without its terminating CRLF CRLF, which Parse() waits on
indefinitely — could grow the per-connection input buffer without bound.
handleConnection now closes the connection once unparsed buffered bytes
exceed MaxBufferedBytes (default 50 MiB + 64 KiB slack, covering the largest
legitimate packet plus its mask envelope and a read chunk).

Co-Authored-By: deepseek-v4-pro
2026-10-13 16:27:20 +02:00
yuanyuanxianganddeepseek-v4-pro 8e0f1283c6 Security: Add per-IP connection and login rate limiting
The TCP device port is exposed directly to the public internet, so a single
host must not be able to exhaust the global connection budget, flood new
connection attempts, or brute-force the device authorization passcode.

- server: cap concurrent connections and the accept rate per source IP
  (defaults 256 concurrent / 120 per minute, overridable via
  YAMA_PERIP_MAX_CONNS and YAMA_PERIP_CONN_RATE). Rejections happen at
  accept time, before any buffer or goroutine is allocated, and a rejected
  device simply retries on its reconnect loop.
- cmd: throttle TOKEN_AUTH per source IP (120/min) and answer over-limit
  attempts with a normal failed response so clients get a definitive reply.
- web: periodically sweep the login rate-limit maps so the username-keyed
  one (which is attacker-controlled) cannot grow without bound.

Per-IP defaults are generous enough that a NAT office whose devices share
one source IP is unaffected.

Co-Authored-By: deepseek-v4-pro
2026-10-13 16:25:34 +02:00
yuanyuanxianganddeepseek-v4-pro 2de21b2b6b Fix: Bind screen/terminal sub-conns only to the device's source IP
A screen or terminal sub-connection was keyed solely by a MasterID that any
TCP peer may supply, so any internet host could claim an online device's
MasterID and bind a sub-conn in its place, hijacking the live screen stream
or a pending shell session. The ConnAuth signature cannot be verified on the
server because its key lives in a vendored client library, so the trust
anchor here is the source IP: sub-conns are always opened device-to-server
from the same host as the login conn. BindScreenConn and BindTerminalConn
now reject a sub-conn whose peer IP differs from the device's recorded
main-connection PeerIP.

Co-Authored-By: deepseek-v4-pro
2026-10-13 16:19:39 +02:00
yuanyuanxianganddeepseek-v4-pro 53b7151fb7 Feature: Add admin-only SSO bridge to web UI
Bridge an already-authenticated portal session into a YAMA web session via
a new /sso endpoint, so portal administrators can enter the remote-desktop
UI without a second login. Only the "admin" portal role is bridged; any
other role (viewer, unknown) still falls back to the built-in login form,
so a low-privileged portal account cannot bypass authentication.

- wsauth: extract IssueToken from VerifyLogin so an out-of-band-authenticated
  identity (SSO) can mint a session token without the challenge/response.
- web: add the SSODetector interface, a fail-closed JWT detector (HMAC-only),
  and the /sso handler gated to the admin role.
- cmd: enable the JWT detector via YAMA_SSO_JWT_SECRET, the shared HS256
  secret matching the parent portal.
- web UI: attempt SSO before showing the login form, falling back to login
  when the server returns 401.
- docs: document SSO (admin-only) and license trial-vs-paid troubleshooting
  in README and the env example.

Co-Authored-By: deepseek-v4-pro
2026-10-13 15:46:04 +02:00
yuanyuanxianganddeepseek-v4-pro d2149851b2 Fix: Decode host-management and clipboard text as GBK/UTF-8 on non-Chinese systems
The 主机管理 dialog wrote client data (process names, window titles, net
connection state, software entries, IE history, favorites, services,
scheduled tasks, hosts) through the ANSI InsertItem/SetItemText path, which
re-converts through CP_ACP and garbles Chinese when the operator machine
runs a non-Chinese ACP. Decode each client string with its real code page
and write it via LVM_SETITEMTEXTW, mirroring SystemDlg::SetClientTextItem.
Scheduled-task columns are split by encoding: name/path/exe come from the
client as UTF-8 (BSTRToUTF8) while the status literal stays GBK. Also detect
a UTF-8 BOM in the hosts file so a Notepad-saved hosts (EF BB BF) no longer
shows "锘?" on its first line.

In the keyboard dialog, the clipboard preview edit was an ANSI-class window
filled via utf8_to_ansi (CP_ACP) + SetWindowTextA, so Chinese was replaced
with '?' before it reached the control. Rebuild m_EditClipText as a
Unicode-class window and write the UTF-8 clipboard text via SetWindowTextW,
matching the m_edit record control.

Co-Authored-By: deepseek-v4-pro
2026-10-12 15:41:24 +02:00
yuanyuanxianganddeepseek-v4-pro ca6f76565c Change: Hide client chat dialog on close instead of terminating
Closing the client-side chat dialog (via the "end chat" button or the title-bar
X) now only hides the window and keeps the session alive, instead of destroying
it. Closing the chat stays server-initiated: the next message from the server
reopens the hidden dialog via the existing SW_RESTORE path in OnReceive, and the
dialog is only truly destroyed on COMMAND_CHAT_CLOSE or connection close.

Co-Authored-By: deepseek-v4-pro
2026-10-10 14:39:34 +02:00
yuanyuanxianganddeepseek-v4-pro d15cd77a28 Fix: Decode geographic location as UTF-8 across client and server
Geographic location (city, country) from the geo APIs is UTF-8, but the client
and several server paths converted or stored it in the system ANSI code page,
turning umlauts ("ö"/"ä") into "?" or GBK mojibake ("B枚blingen"). Keep the
value UTF-8 end to end: the client caches it as UTF-8 and re-queries once after
an upgrade (keyed by __DATE__, the app's version convention), while the server
stores and displays it as UTF-8 in the online list, the activity log, the
client-info export, JSON/email payloads and search.

Also add a confirmation prompt before opening a remote chat from the toolbar,
with German, English and Traditional-Chinese translations.

Co-Authored-By: deepseek-v4-pro
2026-10-10 13:58:38 +02:00
yuanyuanxianganddeepseek-v4-pro 1a9312d2d1 Fix: Decode remote file-list names/paths from GBK/UTF-8 on non-Chinese systems
The Windows ghost client lists directories with FindFirstFileA, so remote
file names arrive as GBK/936 bytes. Both file-manager dialogs wrote them
back through ANSI InsertItem/SetItemText, which re-converts through CP_ACP
and garbles Chinese names when the operator machine runs a non-Chinese ACP.

Decode the name/path from the client encoding (GBK for Windows, UTF-8 for
LNX/MAC, chosen by RES_CLIENT_TYPE) and write the text via LVM_SETITEMTEXTW,
keeping the icon through an empty InsertItem - the same pattern used for the
process list, window list and client-list path.

Co-Authored-By: deepseek-v4-pro
2026-10-09 16:23:23 +02:00
yuanyuanxianganddeepseek-v4-pro f3a8406050 Fix: Decode client file path correctly in client list and info popup
The client reports its own exe path as UTF-8 in RES_FILE_PATH. Two
display sites re-decoded those bytes with the wrong code page and turned
Chinese paths into mojibake on non-Chinese servers:

- The client-list "程序路径" column wrote ProgramPath through the ANSI
  SetItemText path, so the UTF-8 bytes were misread as the system ACP.
  Decode UTF-8 to wide and write with LVM_SETITEMTEXTW instead (same
  pattern as the window/process lists).

- The double-click info popup normalized the client RES_* fields to the
  system ACP and rendered strText with CP_ACP -> wide. The app's internal
  ANSI convention is fixed GBK/936 (/execution-charset:.936 plus
  setlocale(".936")), so on non-Chinese systems the path collapsed to '?'.
  Normalize to 936 and decode 936 instead, which also fixes the popup's
  GBK labels and username in the same pass.

Co-Authored-By: deepseek-v4-pro
2026-10-09 15:00:39 +02:00
yuanyuanxianganddeepseek-v4-pro ff6b290580 Fix: Decode process list names/paths as GBK on Windows
Process management decoded the client's process name/path bytes with
GetClientEncoding, which returns UTF-8 for CLIENT_CAP_UTF8 clients. But
the Windows client builds the process list with the ANSI A-interface
(Process32FirstA / QueryFullProcessImageNameA), which emits the client's
system code page (GBK on Chinese Windows) regardless of the UTF-8
capability -- unlike window titles, which were migrated to the
W-interface plus UTF-8. Decoding GBK as UTF-8 garbled Chinese process
names and paths.

Add GetProcessListEncoding(): 936 for Windows clients, UTF-8 for
LNX/MAC, matching McpServer::BuildListProcesses, and use it in
ShowProcessList (which still writes via LVM_SETITEMTEXTW).

Also raise the IP history cap to 1000 and rename the experimental
"隐私屏幕" menu item to "虚拟屏幕".

Co-Authored-By: deepseek-v4-pro
2026-10-09 14:05:52 +02:00
yuanyuanxianganddeepseek-v4-pro da0ec983ba Feature: Show live transfer speed in file-transfer dialog title
Add a smoothed bytes-per-second readout to the CDlgFileSend title,
refreshed about every 200 ms during transfer (e.g. "发送文件 - 5.3M/s").
The base title is captured on the first progress frame and the speed
suffix applied through Unicode APIs (GetWindowTextW / SetWindowTextW),
so the whole title stays correct on non-Chinese systems where the ANSI
message path would misdecode GBK as the system ACP.

Also add the missing "接收文件 (V2)" translation (en_US "Receive File (V2)",
zh_TW "接收檔案 (V2)"), so the V2 receive title no longer falls back to
raw Chinese on non-Chinese systems.

Co-Authored-By: deepseek-v4-pro
2026-10-08 22:15:31 +02:00
yuanyuanxianganddeepseek-v4-pro 6220335f63 Fix: Decode GBK dialog/toolbar text on non-Chinese systems
MBCS dialog templates are decoded with the system ANSI code page, so on
non-Chinese systems the GBK template strings turn into "?" before
TranslateDialog can read them. Set those strings explicitly in OnInitDialog
(PluginSettings save/close, the three Advanced dialogs, the file-manager
search buttons/checkboxes, and Trigger Settings) so they are re-decoded
with the thread locale. Also fix the language-selection dialog and the
toolbar "Lang/语言" button: the language dialog's template is built as
WCHAR strings but created through the ANSI path, so its title, label, and
buttons are set explicitly in OnInitDialog (AppendString stays on CP_ACP),
with the title looked up via _TR("切换语言") and set through SetWindowTextW
after an explicit GBK conversion; new en_US ("Switch Language") and zh_TW
("切換語言") translations accompany it. The toolbar button is set through
the Unicode TB_SETBUTTONINFOW message after an explicit GBK conversion. Add
en_US/zh_TW translations for the experimental-features context menu items.

Co-Authored-By: deepseek-v4-pro
2026-10-08 21:53:53 +02:00
yuanyuanxianganddeepseek-v4-pro c7f7b7b29b Fix: Expand env vars in V2 file receive path
V2 upload to a remote directory picked via the quick-icon shortcuts
(Desktop / Downloads / Home) landed files in a literal "%USERPROFILE%"
folder instead of the real profile. The shortcuts set m_Remote_Path to an
unexpanded "%USERPROFILE%\..." template (FileManagerDlg.cpp
OnRemoteDesktop/Downloads/Home), and the V2 receive path handed that
filename straight to RecvFileChunkV2 (prebuilt FileUpload lib), which writes
it verbatim. V1 upload already expanded env vars in COMMAND_FILE_SIZE
(client/FileManager.cpp ExpandPath), so this is a V2-only regression.

Expand the filename's environment variables in CKernelManager::OnReceive's
COMMAND_SEND_FILE_V2 branch before RecvFileChunkV2, rebuilding the packet
only when the expanded length differs; other packet types pass through
unchanged.

Co-Authored-By: deepseek-v4-pro
2026-10-08 17:56:18 +02:00
yuanyuanxianganddeepseek-v4-pro 59fead7b5f Fix: Deliver file-transfer speed via MasterSettings (was CMD_FILE_SPEED)
The file-transfer speed dialog previously sent a separate CMD_FILE_SPEED
(5 bytes) back-to-back before COMMAND_SCREEN_SPY / COMMAND_LIST_DRIVE when
opening remote desktop or file manager. The IOCP send path batches two
consecutive Send2Client calls into one WSASend of the accumulated
OutCompressedBuffer, so the client received the [FILE_SPEED][SCREEN_SPY]
command stream twice - the root cause of two remote-desktop dialogs popping
up on a single click (introduced in commit 76decec).

Fold the two values into MasterSettings (TransferChunkKb / TransferDurationMs,
uint16 each, before Reserved, sizeof unchanged at 1000) so they reach every
client on login and are broadcast to online clients when the dialog saves.
The client persists them into [transfer] on CMD_MASTERSETTING, guarded by
TransferChunkKb != 0 so older masters keep local defaults. CMD_FILE_SPEED(252)
and its client handler remain for backward compatibility, but the master no
longer sends it.

Update the design doc, the three GBK lang files' prompt entry, and the READMEs.

Co-Authored-By: deepseek-v4-pro
2026-10-07 21:19:04 +02:00
153 changed files with 22341 additions and 1251 deletions

No files matched your search

+1
View File
@@ -93,6 +93,7 @@ Bin/*
nul
server/go/web/assets/index.html
server/go/users.json
server/go/devices.json
server/go/build/
server/go/.claude/settings.json
android/app/.cxx/
+26 -1
View File
@@ -378,6 +378,31 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
## 更新日志
### v1.4.1 (2026.10.20)
**Web 运维控制台 & 安全加固 & 单向 TLS**
**新功能:**
- **Web 屏幕墙**:同一标签页以 1×1 ~ 5×5 布局同时监控多台设备,桌面 9 路 / 触控 4 路实时解码,超出预算暂停并自动晋升;点击 tile 进入单画面控制;同一设备可重复添加并共享一路流;MFC 与 Go 服务端同步支持(旧前端 / 旧服务端自动降级)
- **安全审计日志**:登录 / 授权拒绝 / WS 生命周期 / 屏幕与终端会话 / 剪贴板(仅字节数)/ 设备认证 / 管理变更;Go 端持久化 `logs/audit.log`,MFC 端保留最近 1000 条内存环形缓冲;Web 新增审计日志查询页(时间 / 事件 / 操作者 / IP / 设备 / 关键字 / 告警过滤 + 分页)
- **离线设备历史(Go)**:`devices.json` 持久化所有登录过的设备,设备列表可按需显示离线记录;管理员可删除记录或对在线设备执行远程卸载
- **单向 TLS 传输**:设备端口同一端口嗅探 ClientHello,TLS 1.2 客户端加密、旧明文客户端不受影响;MFC「扩展 > TLS证书」运行时配置;在线列表新增 TLS 列,右键可远程启用 / 取消(客户端下次启动生效)
- **Web 远程桌面增强**:Ctrl+C/X/V 双向文本剪贴板同步、手机「I」输入框(经剪贴板桥注入)、登录会话跨标签页共享、管理员 SSO 桥接
- **客户端安装位置选择**:ProgramData / ProgramFiles - Admin / SystemRoot - Admin / APPDATA / LOCALAPPDATA
- **Go Web UI 白标**:`YAMA_WEB_BRAND_NAME` 替换产品名并移除安全提示与外链
- **安全加固**:每 IP 连接与登录限流、单连接入站缓冲上限、屏幕 / 终端子连接绑定源 IP、可选 ConnAuth HMAC 校验
- **克隆机 ID 去重**:V2 `client_id` 折叠主机名,撞 ID 时服务端下发 `COMMAND_REGEN_CLIENT_ID` 让客户端重算重连
**改进:**
- 文件传输速度改由 MasterSettings 下发(修复重复弹窗),传输对话框标题实时显示速度
- 客户端聊天关闭仅隐藏;日志右键新增白名单;MCP 勾选即时刷新;Web 原生 alert/confirm 全部替换为主题化应用内对话框
- 非中文系统统一按 GBK / UTF-8 解码(对话框 / 进程列表 / 文件列表 / 路径 / 地理位置 / 主机管理 / 剪贴板)
**Bug 修复:**
- 共享 / 转移主机后重启主控不重连;分享 / 转移权限误判
- 已过期授权续期从今天起算,提示与日志显示实际到期日
- V2 上传快捷目录未展开 `%USERPROFILE%`;无摄像头主机发送 0×0 画面信息;列切换残留像素;Go 设备端口日志刷屏;审计页最小化后跳回设备页
### v1.4.0 (2026.10.7)
**SimplePlugins 功能迁移 & 远程交互增强 & MCP 扩展 & 国际化**
@@ -390,7 +415,7 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
- **主机管理**:迁移 CMachineManager(进程 / 窗口 / 网络 / 软件 / IE 历史 / 收藏夹 / 服务 / 任务 / hosts 枚举 + 进程注入),COMMAND_MACHINE_MANAGE 162
- **授权失败触发器**:新增 TRIGGER_AUTH_FAILED 触发类型(与主机上线触发独立),授权失败时下发插件 DLL,受 ShouldLogAuth 去重约束
- **iPhone 远程音频**:WebAudio + 自托管 opus-decoder WASM 解码,修复 iOS 无 MSE 静音
- **画质与传输控制**:远程桌面 / 屏幕预览质量等级菜单(各 6 档可配置)+ 文件传输速度对话框(7 档 + 无限档,CMD_FILE_SPEED 252)
- **画质与传输控制**:远程桌面 / 屏幕预览质量等级菜单(各 6 档可配置)+ 文件传输速度对话框(7 档 + 无限档,经 MasterSettings 下发)
- **Shine/HELL 协议选择**:分享 / 传输主机时可选协议,尾随冒号字段透传,旧客户端兼容
- **Go Web UI 子路径部署**:YAMA_WEB_BASE_PATH 挂载整个 Web UI 到 URL 前缀
- **国际化**:德语(de_DE)第 4 种语言、语言切换工具栏按钮、剩余字符串翻译补齐;远程桌面剪贴板按钮(全屏可达)
+26 -1
View File
@@ -378,6 +378,31 @@ Valid : 2026-02-01 to 2028-02-01
## Changelog
### v1.4.1 (2026.10.20)
**Web operations console & security hardening & one-way TLS**
**New features:**
- **Web screen wall**: monitor several devices in one tab with 1x1 to 5x5 layouts; desktop decodes up to 9 live streams and touch devices 4, tiles over budget show Paused and are promoted automatically; click a tile for single-screen control; the same device can be added repeatedly and shares one stream; supported by both the MFC and Go servers (old frontends / old servers degrade automatically)
- **Security audit log**: login attempts, authorization denials, WebSocket lifecycle, screen / terminal sessions, clipboard (byte counts only), device authentication and admin mutations; the Go server persists to `logs/audit.log`, the MFC server keeps the newest 1000 events in an in-memory ring; new Audit Log page with time / event / actor / IP / device / keyword / warn filters and paging
- **Offline device history (Go)**: `devices.json` persists every device that has ever logged in, and the device list can show offline records; admins can delete a record or remotely uninstall an online device
- **One-way TLS transport**: the device port sniffs ClientHello on the same port, so TLS 1.2 clients are encrypted while legacy plaintext clients keep working; "Extensions > TLS Certificate" configures the MFC server at runtime; a TLS column and a per-client remote enable / disable action (effective on the client's next start)
- **Web remote desktop enhancements**: bidirectional Ctrl+C/X/V text clipboard sync, a phone "I" input box that injects text through the clipboard bridge, login sessions shared across tabs, and an admin-only SSO bridge
- **Client install location**: ProgramData / ProgramFiles - Admin / SystemRoot - Admin / APPDATA / LOCALAPPDATA
- **White-label Go web UI**: `YAMA_WEB_BRAND_NAME` replaces the product name and removes the security notice and external links
- **Security hardening**: per-IP connection and login rate limits, a per-connection inbound buffer cap, source-IP binding for screen / terminal sub-connections, and optional ConnAuth HMAC verification
- **Clone ID deduplication**: the V2 `client_id` folds in the hostname; on a collision the server sends `COMMAND_REGEN_CLIENT_ID` so the client recomputes and reconnects
**Improvements:**
- File-transfer speed is delivered via MasterSettings (fixes duplicate dialogs), and the transfer dialog title shows live speed
- Closing the client chat now hides it; whitelist action in the log context menu; MCP checkmark refreshes immediately; native browser alert/confirm replaced with themed in-app dialogs
- GBK / UTF-8 decoding across non-Chinese systems (dialogs, process list, file lists, paths, geolocation, machine management, clipboard)
**Bug fixes:**
- Hosts did not reconnect after a master restart following share / transfer; share / transfer permission misjudgment
- Expired licenses now renew from today, and prompts and logs show the actually issued date
- V2 quick-folder uploads did not expand `%USERPROFILE%`; webcam-less hosts sent 0x0 bitmap info; stale pixels after column toggles; Go device-port log flood; audit page reset after minimizing the browser
### v1.4.0 (2026.10.7)
**SimplePlugins Feature Migration & Remote Interaction Enhancements & MCP Expansion & i18n**
@@ -390,7 +415,7 @@ Valid : 2026-02-01 to 2028-02-01
- **Machine management**: CMachineManager migrated (process / window / network / software / IE history / favorites / service / task / hosts enumeration plus process injection), COMMAND_MACHINE_MANAGE 162
- **Auth-failed trigger**: new TRIGGER_AUTH_FAILED type (independent of the host-online trigger) pushes plugin DLLs on authorization failure, gated by ShouldLogAuth dedup
- **iPhone remote audio**: Web Audio API + self-hosted opus-decoder WASM decoding fixes silent audio on iOS without MSE
- **Quality & transfer controls**: configurable remote-desktop / screen-preview quality-level menus (six presets each) plus a file-transfer speed dialog (seven presets + unlimited, CMD_FILE_SPEED 252)
- **Quality & transfer controls**: configurable remote-desktop / screen-preview quality-level menus (six presets each) plus a file-transfer speed dialog (seven presets + unlimited, delivered via MasterSettings)
- **Shine/HELL protocol selection**: choose the protocol when sharing / transferring a host, passed as a trailing colon field, backward compatible
- **Go web UI subpath deployment**: YAMA_WEB_BASE_PATH mounts the whole web UI under a URL prefix
- **i18n**: German (de_DE) as the fourth language, a language-switch toolbar button, remaining string translations; remote-desktop clipboard buttons (reachable in fullscreen)
+26 -1
View File
@@ -378,6 +378,31 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
## 更新日誌
### v1.4.1 (2026.10.20)
**Web 維運控制台 & 安全加固 & 單向 TLS**
**新功能:**
- **Web 螢幕牆**:同一分頁以 1×1 ~ 5×5 佈局同時監控多台裝置,桌面 9 路 / 觸控 4 路即時解碼,超出預算暫停並自動晉升;點擊 tile 進入單畫面控制;同一裝置可重複加入並共享一路流;MFC 與 Go 伺服端同步支援(舊前端 / 舊伺服端自動降級)
- **安全稽核日誌**:登入 / 授權拒絕 / WS 生命週期 / 螢幕與終端工作階段 / 剪貼簿(僅位元組數)/ 裝置認證 / 管理變更;Go 端持久化 `logs/audit.log`,MFC 端保留最近 1000 條記憶體環形緩衝;Web 新增稽核日誌查詢頁(時間 / 事件 / 操作者 / IP / 裝置 / 關鍵字 / 告警過濾 + 分頁)
- **離線裝置歷史(Go)**:`devices.json` 持久化所有登入過的裝置,裝置列表可依需顯示離線記錄;管理員可刪除記錄或對線上裝置執行遠端解除安裝
- **單向 TLS 傳輸**:裝置連接埠同一連接埠嗅探 ClientHello,TLS 1.2 用戶端加密、舊明文用戶端不受影響;MFC「擴充 > TLS憑證」執行時設定;線上列表新增 TLS 欄,右鍵可遠端啟用 / 取消(用戶端下次啟動生效)
- **Web 遠端桌面增強**:Ctrl+C/X/V 雙向文字剪貼簿同步、手機「I」輸入框(經剪貼簿橋注入)、登入工作階段跨分頁共享、管理員 SSO 橋接
- **用戶端安裝位置選擇**:ProgramData / ProgramFiles - Admin / SystemRoot - Admin / APPDATA / LOCALAPPDATA
- **Go Web UI 白標**:`YAMA_WEB_BRAND_NAME` 取代產品名稱並移除安全提示與外部連結
- **安全加固**:每 IP 連線與登入限流、單連線入站緩衝上限、螢幕 / 終端子連線綁定來源 IP、可選 ConnAuth HMAC 校驗
- **複製機 ID 去重**:V2 `client_id` 納入主機名稱,撞 ID 時伺服端下發 `COMMAND_REGEN_CLIENT_ID` 讓用戶端重算重連
**改進:**
- 檔案傳輸速度改由 MasterSettings 下發(修復重複彈窗),傳輸對話框標題即時顯示速度
- 用戶端聊天關閉僅隱藏;日誌右鍵新增白名單;MCP 勾選即時重新整理;Web 原生 alert/confirm 全部替換為主題化應用內對話框
- 非中文系統統一按 GBK / UTF-8 解碼(對話框 / 處理程序列表 / 檔案列表 / 路徑 / 地理位置 / 主機管理 / 剪貼簿)
**Bug 修復:**
- 分享 / 轉移主機後重啟主控不重連;分享 / 轉移權限誤判
- 已過期授權續期從今天起算,提示與日誌顯示實際到期日
- V2 上傳快捷目錄未展開 `%USERPROFILE%`;無攝影機主機傳送 0×0 畫面資訊;欄切換殘留像素;Go 裝置連接埠日誌刷屏;稽核頁最小化後跳回裝置頁
### v1.4.0 (2026.10.7)
**SimplePlugins 功能遷移 & 遠端互動增強 & MCP 擴充 & 國際化**
@@ -390,7 +415,7 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
- **主機管理**:遷移 CMachineManager(處理程序 / 視窗 / 網路 / 軟體 / IE 歷史 / 收藏夾 / 服務 / 排程工作 / hosts 列舉 + 處理程序注入),COMMAND_MACHINE_MANAGE 162
- **授權失敗觸發器**:新增 TRIGGER_AUTH_FAILED 觸發類型(與主機上線觸發獨立),授權失敗時下發外掛程式 DLL,受 ShouldLogAuth 去重約束
- **iPhone 遠端音訊**:WebAudio + 自託管 opus-decoder WASM 解碼,修復 iOS 無 MSE 靜音
- **品質與傳輸控制**:遠端桌面 / 螢幕預覽品質等級選單(各 6 檔可設定)+ 檔案傳輸速度對話框(7 檔 + 無限檔,CMD_FILE_SPEED 252)
- **品質與傳輸控制**:遠端桌面 / 螢幕預覽品質等級選單(各 6 檔可設定)+ 檔案傳輸速度對話框(7 檔 + 無限檔,經 MasterSettings 下發)
- **Shine/HELL 協定選擇**:分享 / 傳輸主機時可選協定,尾隨冒號欄位透傳,舊用戶端相容
- **Go Web UI 子路徑部署**:YAMA_WEB_BASE_PATH 掛載整個 Web UI 到 URL 前綴
- **國際化**:德語(de_DE)第 4 種語言、語言切換工具列按鈕、剩餘字串翻譯補齊;遠端桌面剪貼簿按鈕(全螢幕可達)
+2
View File
@@ -9,6 +9,8 @@
- build.cmd publish:编译YAMA.exe且通过upx压缩,所生成的可执行文件较小。
- buld.cmd server:只编译YAMA.exe,需保证所依赖的客户端程序已经编译。
- build.cmd go-server:编译 Go 服务端,可以选择带publish 参数进行upx压缩。
- build.cmd serverd:编译 Debug 版服务端(x64),输出 Bin\Yama_x64d.exe。
- build.cmd client:编译 Debug 版客户端(x64),输出 x64\Debug\ghost.exe。
## Go 服务端
+6 -1
View File
@@ -1,8 +1,10 @@
@echo off
:: SimpleRemoter Quick Build Script
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server]
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|serverd|client]
:: go-server Build Go fallback server only -> Bin\YamaGo_x64.exe
:: go-server publish Same, plus UPX --best compression
:: serverd Debug server only (x64) -> Bin\Yama_x64d.exe
:: client Debug client (x64) -> x64\Debug\ghost.exe
setlocal enabledelayedexpansion
@@ -21,6 +23,9 @@ if /i "%~1"=="server" (set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :par
if /i "%~1"=="clean" (set EXTRA_ARGS=!EXTRA_ARGS! -Clean& shift& goto :parse_args)
if /i "%~1"=="publish" (set EXTRA_ARGS=!EXTRA_ARGS! -Publish& shift& goto :parse_args)
if /i "%~1"=="go-server" (set EXTRA_ARGS=!EXTRA_ARGS! -GoServer& shift& goto :parse_args)
:: Debug presets: serverd = debug server x64 only, client = debug ghost x64 only
if /i "%~1"=="serverd" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :parse_args)
if /i "%~1"=="client" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ClientOnly& shift& goto :parse_args)
echo Unknown argument: %~1
shift
goto :parse_args
+103 -11
View File
@@ -1,9 +1,10 @@
# SimpleRemoter Build Script
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-Clean] [-Publish]
# SimpleRemoter Build Script
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-ClientOnly] [-Clean] [-Publish]
#
# Requirements:
# - Visual Studio 2019 or 2022
# - v142 toolset (MSVC v142 - VS 2019 C++ build tools)
# - ATL (C++ ATL for v142 build tools)
# - MFC libraries (C++ MFC for v142 build tools)
param(
@@ -14,6 +15,7 @@ param(
[string]$Platform = "x64",
[switch]$ServerOnly, # Only build main server (Yama), skip client projects
[switch]$ClientOnly, # Only build the client executable (ghost), skip server
[switch]$Clean, # Clean before build
[switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress
[switch]$GoServer # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe
@@ -119,8 +121,27 @@ if ($GoServer) {
exit 0
}
# 判断某个 VS 安装是否带 ATL/MFC 组件。ATL 头文件用 #pragma comment(lib, "atls.lib")
# 自动链接,只装了编译工具(BuildTools)的实例常常没有这一块:编译能过、链接报
# LNK1104 无法打开 atls.lib。同机既装 BuildTools 又装 IDE 时,按路径取第一个会挑错。
function Test-VcAtlPresent {
param([string]$VsRoot)
if (-not $VsRoot) { return $false }
$atlLib = Join-Path $VsRoot "VC\Tools\MSVC\*\atlmfc\lib\x86\atls.lib"
return [bool](Get-ChildItem $atlLib -ErrorAction SilentlyContinue | Select-Object -First 1)
}
# 从 ...\MSBuild\Current\Bin\MSBuild.exe 反推 VS 安装根目录。
function Get-VsRootFromMsBuild {
param([string]$MsBuildPath)
$idx = $MsBuildPath.IndexOf("\MSBuild\", [System.StringComparison]::OrdinalIgnoreCase)
if ($idx -lt 0) { return $null }
return $MsBuildPath.Substring(0, $idx)
}
# Find MSBuild (VS2019 or VS2022, including Insiders/Preview)
# Order: Prefer installations with v142 toolset (VS2019) over VS2022 BuildTools
# Order: Prefer installations with v142 toolset (VS2019) over VS2022 BuildTools,
# and within that prefer instances that actually carry ATL/MFC.
$msBuildPaths = @(
# VS2019 Insiders/Preview (non-standard path) - has v142 + MFC
"${env:ProgramFiles}\Microsoft Visual Studio\18\*\MSBuild\Current\Bin\MSBuild.exe",
@@ -134,12 +155,17 @@ $msBuildPaths = @(
)
$msBuild = $null
$fallbackMsBuild = $null # 第一个找到的候选(可能不带 ATL),仅在没有带 ATL 的实例时兜底
foreach ($pattern in $msBuildPaths) {
$found = Get-ChildItem $pattern -ErrorAction SilentlyContinue | Select-Object -First 1
if ($found) {
$msBuild = $found.FullName
break
foreach ($found in @(Get-ChildItem $pattern -ErrorAction SilentlyContinue)) {
if (-not $fallbackMsBuild) { $fallbackMsBuild = $found.FullName }
if (Test-VcAtlPresent (Get-VsRootFromMsBuild $found.FullName)) {
$msBuild = $found.FullName
break
}
Write-Host "Skipping MSBuild without ATL/MFC: $($found.FullName)" -ForegroundColor DarkYellow
}
if ($msBuild) { break }
}
# 兜底:默认路径找不到(例如 VS 装在 D 盘)时,用 vswhere 反查。
@@ -147,19 +173,34 @@ foreach ($pattern in $msBuildPaths) {
if (-not $msBuild) {
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
if (Test-Path $vswhere) {
$found = & $vswhere -latest -products * -requires Microsoft.Component.MSBuild `
-find "MSBuild\**\Bin\MSBuild.exe" 2>$null |
Select-Object -First 1
if ($found) { $msBuild = $found }
# 不能用 -requires Microsoft.VisualStudio.Component.VC.ATL 过滤组件 id:
# 各 VS 版本的 id 不一样(v142/v143/预览版),且预览实例可能根本查不到。
# 因此列出全部实例,再逐个用 atls.lib 落地校验(上面那条 glob 只看得到 C 盘,
# VS 装在 D 盘时只能靠这里找到)。
$hits = @(& $vswhere -products * -requires Microsoft.Component.MSBuild `
-find "MSBuild\**\Bin\MSBuild.exe" 2>$null)
foreach ($hit in $hits) {
if (-not $hit) { continue }
if (-not $fallbackMsBuild) { $fallbackMsBuild = $hit }
if (Test-VcAtlPresent (Get-VsRootFromMsBuild $hit)) { $msBuild = $hit; break }
}
}
}
# 一个带 ATL 的实例都没有:仍用兜底候选,让 MSBuild 报出更具体的错误。
if (-not $msBuild -and $fallbackMsBuild) {
Write-Host "WARNING: no VS instance with ATL/MFC found, using $fallbackMsBuild" -ForegroundColor Yellow
Write-Host " Install 'C++ ATL for v142 build tools' if linking fails on atls.lib." -ForegroundColor DarkGray
$msBuild = $fallbackMsBuild
}
if (-not $msBuild) {
Write-Host "ERROR: MSBuild not found." -ForegroundColor Red
Write-Host ""
Write-Host "Please install Visual Studio 2019 or 2022 with:" -ForegroundColor Yellow
Write-Host " - Desktop development with C++" -ForegroundColor White
Write-Host " - MSVC v142 - VS 2019 C++ x64/x86 build tools" -ForegroundColor White
Write-Host " - C++ ATL for v142 build tools" -ForegroundColor White
Write-Host " - C++ MFC for v142 build tools" -ForegroundColor White
exit 1
}
@@ -218,6 +259,9 @@ function Build-Project {
Write-Host "If you see 'v142 build tools cannot be found':" -ForegroundColor Yellow
Write-Host " Install 'MSVC v142 - VS 2019 C++ build tools' via VS Installer" -ForegroundColor White
Write-Host ""
Write-Host "If you see 'LNK1104: cannot open file atls.lib':" -ForegroundColor Yellow
Write-Host " Install 'C++ ATL for v142 build tools' via VS Installer" -ForegroundColor White
Write-Host ""
Write-Host "If you see 'MFC libraries are required':" -ForegroundColor Yellow
Write-Host " Install 'C++ MFC for v142 build tools' via VS Installer" -ForegroundColor White
exit 1
@@ -226,6 +270,54 @@ function Build-Project {
Write-Host "OK: $Project" -ForegroundColor Green
}
# Debug client fast path: build the client executable and stop.
# Only ghost is built — the other client projects (ServerDll, TestRun, TinyRun,
# SCLoader) exist to be embedded in the server and are irrelevant when the goal
# is debugging the client itself.
if ($ClientOnly) {
$clientProject = "ghost"
$clientPlatforms = if ($Platform -eq "all") { @("x86", "x64") } else { @($Platform) }
$startTime = Get-Date
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " SimpleRemoter Client Build" -ForegroundColor Cyan
Write-Host " Config: $Config" -ForegroundColor Cyan
Write-Host " Platform: $Platform" -ForegroundColor Cyan
Write-Host " VS: $vsYear" -ForegroundColor Cyan
Write-Host " Clean: $Clean" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
foreach ($plat in $clientPlatforms) {
Build-Project -Project $clientProject -Configuration $Config -Platform $plat -ForceClean $Clean
}
$elapsed = (Get-Date) - $startTime
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host " Build Completed!" -ForegroundColor Green
Write-Host " Time: $($elapsed.TotalSeconds.ToString('F1')) seconds" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Output files:" -ForegroundColor Cyan
# VS default OutDir for this project: $(SolutionDir)$(Platform)\$(Configuration)\
# x86 output lands in <root>\Debug, x64 in <root>\x64\Debug.
foreach ($plat in $clientPlatforms) {
$outDir = if ($plat -eq "x64") { Join-Path (Join-Path $rootDir "x64") $Config } else { Join-Path $rootDir $Config }
$clientOut = Join-Path $outDir "ghost.exe"
if (Test-Path $clientOut) {
$size = (Get-Item $clientOut).Length / 1MB
Write-Host " $clientOut ($($size.ToString('F2')) MB)" -ForegroundColor White
} else {
Write-Host " WARNING: expected output not found at $clientOut" -ForegroundColor Yellow
}
}
exit 0
}
# Determine platforms to build
$platforms = if ($Platform -eq "all") { @("x86", "x64") } else { @($Platform) }
+4 -2
View File
@@ -46,13 +46,15 @@ CCaptureVideo::~CCaptureVideo()
HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
{
Mprintf("CCaptureVideo call Open\n");
HRESULT hResult = S_OK;
HRESULT hResult = S_FALSE;
do {
hResult = InitCaptureGraphBuilder();
if (FAILED(hResult))
break;
if(!BindVideoFilter(iDeviceID, &m_pBF))
if (!BindVideoFilter(iDeviceID, &m_pBF)) {
hResult = S_FALSE;
break;
}
hResult = m_pGB->AddFilter(m_pBF, L"Capture Filter");
+44
View File
@@ -0,0 +1,44 @@
// ChatDialogTemplate.h: IDD_CHAT 的编译后 DLGTEMPLATEEX(内嵌内存模板)
//
// 用途:加壳部署(EXE + SC_AES/sRDI)的客户端里,ChatManager 的 hInstance 是外壳进程
// 映像(GetModuleHandle(NULL)),其资源里只有清单、没有 IDD_CHAT;而载荷 EXE 以裸
// shellcode 在壳进程内运行,未注册进加载器,FindResource/LoadResource/CreateDialogParamW
// 一律取不到资源(实测 Win11 26200 返回 err=1812 / 59)。此时用下面的内存模板直接
// CreateDialogIndirectParamW 建窗,与部署形态无关。
//
// 数据来源:client/Script.rc 的 IDD_CHAT(DIALOGEX)。DLGTEMPLATEEX 的字符串字段
// 一律是 UTF-16,同一份字节既可用于 A 接口也可用于 W 接口;聊天窗口固定用 W 接口
// 创建成 Unicode 对话框,否则 MBCS 客户端在非中文系统(德语等)上会按系统代码页
// 渲染 GBK 字节,中文全部乱码。
//
// 重新生成(改动 Script.rc 的 IDD_CHAT 后必须同步):
// 1. rc /fo dlg.res dlg.rc (dlg.rc 只保留与 Script.rc 相同的 IDD_CHAT 块)
// 2. link /dll /noentry /machine:x64 /out:dlg.dll dlg.res
// 3. 从 dlg.dll 的 RT_DIALOG(5) → 106 → 任意语言 取数据块,按 16 字节一行导出。
// 当前块 240 字节:CAPTION "Remote Chat"、FONT 9 "MS Shell Dlg" charset 1、
// 控件 ID 1001/1002/1003/1004,与 Script.rc 完全一致。
#ifndef YAMA_CHAT_DIALOG_TEMPLATE_H
#define YAMA_CHAT_DIALOG_TEMPLATE_H
// DLGTEMPLATEEX 的 DWORD 字段要求模板指针 4 字节对齐;显式声明对齐,避免依赖
// 编译器把字节数组放在什么边界上。
__declspec(align(4)) static const unsigned char kChatDialogTemplate[] = {
0x01, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x08, 0xCA, 0x80,
0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEB, 0x00, 0x9B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x52, 0x00,
0x65, 0x00, 0x6D, 0x00, 0x6F, 0x00, 0x74, 0x00, 0x65, 0x00, 0x20, 0x00, 0x43, 0x00, 0x68, 0x00,
0x61, 0x00, 0x74, 0x00, 0x00, 0x00, 0x09, 0x00, 0x90, 0x01, 0x00, 0x01, 0x4D, 0x00, 0x53, 0x00,
0x20, 0x00, 0x53, 0x00, 0x68, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x20, 0x00, 0x44, 0x00,
0x6C, 0x00, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x08, 0xA1, 0x50, 0x03, 0x00, 0x03, 0x00, 0xE5, 0x00, 0x6B, 0x00, 0xE9, 0x03, 0x00, 0x00,
0xFF, 0xFF, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x00, 0xA1, 0x50, 0x03, 0x00, 0x71, 0x00, 0xAA, 0x00, 0x26, 0x00, 0xEA, 0x03, 0x00, 0x00,
0xFF, 0xFF, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x01, 0x50, 0xB2, 0x00, 0x74, 0x00, 0x36, 0x00, 0x0E, 0x00, 0xEB, 0x03, 0x00, 0x00,
0xFF, 0xFF, 0x80, 0x00, 0x53, 0x00, 0x65, 0x00, 0x6E, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x50, 0xB2, 0x00, 0x85, 0x00,
0x36, 0x00, 0x0E, 0x00, 0xEC, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0x80, 0x00, 0x45, 0x00, 0x6E, 0x00,
0x64, 0x00, 0x20, 0x00, 0x43, 0x00, 0x68, 0x00, 0x61, 0x00, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#endif // YAMA_CHAT_DIALOG_TEMPLATE_H
+239 -53
View File
@@ -4,9 +4,12 @@
#include "stdafx.h"
#include "ChatManager.h"
#include "ChatDialogTemplate.h"
#include "ImageResource.h"
#include "Common.h"
#include "resource.h"
#include <TlHelp32.h>
#include <string>
#if ENABLE_MESSAGE
@@ -28,6 +31,27 @@ static SuspendOrResumeProcess g_lpfnNtResumeProcess = NULL;
static HHOOK g_hKeyBoard = NULL;
static int g_nLocked = 0;
// 加壳部署用:从本模块映像自建的聊天窗口图标,只建一次,进程内复用(不销毁)
static volatile LONG g_lOwnIconsState = 0; // 0=未建 1=建中 2=已建
static HICON g_hOwnIconSmall = NULL;
static HICON g_hOwnIconBig = NULL;
static void EnsureOwnChatIcons()
{
if (InterlockedCompareExchange(&g_lOwnIconsState, 1, 0) == 0) {
g_hOwnIconSmall = CreateImageIcon(&__ImageBase, IDI_ICON_MSG,
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
g_hOwnIconBig = CreateImageIcon(&__ImageBase, IDI_ICON_MSG,
GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON));
InterlockedExchange(&g_lOwnIconsState, 2); // 全屏障,发布句柄
return;
}
// 另一个线程正在建:短暂等待其发布,避免读到尚未赋值的句柄
for (int i = 0; i < 50 && g_lOwnIconsState != 2; i++) {
Sleep(1);
}
}
static DWORD GetWinlogonPid()
{
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
@@ -62,6 +86,11 @@ static LRESULT CALLBACK KeyBoardProc(int code, WPARAM wParam, LPARAM lParam)
|| (p->vkCode == VK_ESCAPE && (GetKeyState(VK_CONTROL) & 0x8000) != 0) // Ctrl+Esc
|| (p->vkCode == VK_LWIN)
|| (p->vkCode == VK_RWIN)) {
// 低层钩子按后装先调用的顺序排队,直接 return 1 会让链上更早安装的
// 钩子(例如同机运行的主控的系统热键转发)永远收不到这些键。
// 先沿链传递再返回 1:别的钩子能看见按键并自行决定是否转发,
// 本机 shell 仍然被拦住,锁屏效果不变。
::CallNextHookEx(g_hKeyBoard, code, wParam, lParam);
return 1;
}
break;
@@ -133,6 +162,113 @@ static void UnlockScreen()
g_nLocked = 0;
}
//////////////////////////////////////////////////////////////////////
// 聊天文字:Unicode 窗口与 CP936 转换
//////////////////////////////////////////////////////////////////////
// 聊天窗口是 Unicode 对话框:客户端整体是 MBCS 工程,但聊天窗口用 W 接口创建,
// 文字以 UTF-16 存在内存里,与系统 ANSI 代码页无关——德语/日语等非中文系统上
// 中文不再乱码。静态标签按系统 UI 语言选择:中文系统保持中文,其余用英文。
struct ChatUiStrings {
const wchar_t* caption;
const wchar_t* send;
const wchar_t* end;
const wchar_t* self;
const wchar_t* peer;
const wchar_t* errChars;
const wchar_t* errTooLong;
};
static const ChatUiStrings& ChatUi()
{
static const ChatUiStrings zhChatUi = {
L"远程交谈", L"发送消息", L"结束交谈", L"自己:", L"对方:",
L"消息未发送:含 GBK 不支持的字符(emoji 或带变音符号的字母)",
L"消息未发送:超过 4000 字节上限"
};
static const ChatUiStrings enChatUi = {
L"Remote Chat", L"Send", L"End Chat", L"Me:", L"Peer:",
L"Not sent: the message contains characters GBK cannot represent "
L"(emoji or accented letters)",
L"Not sent: the message exceeds the 4000-byte limit"
};
static const bool bChineseUI =
(PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_CHINESE);
return bChineseUI ? zhChatUi : enChatUi;
}
// 服务端聊天正文一律是 CP936 字节;转成 UTF-16 交给 Unicode 编辑框显示。
static bool Cp936ToWide(const char* src, int cbSrc, std::wstring& out)
{
out.clear();
if (!src || cbSrc <= 0) return true;
int cch = MultiByteToWideChar(936, 0, src, cbSrc, NULL, 0);
if (cch <= 0) return false;
out.resize((size_t)cch);
return MultiByteToWideChar(936, 0, src, cbSrc, &out[0], cch) > 0;
}
static size_t ChatBoundedStrlen(const char* s, size_t nMax)
{
size_t n = 0;
while (n < nMax && s[n] != '\0') ++n;
return n;
}
// 追加一条聊天记录。控件是 Unicode 窗口,即使在 MBCS 工程里也必须用 W 接口,
// 否则文字会被按系统代码页转换。
static void AppendChatLine(HWND hDlg, const wchar_t* who, const wchar_t* body)
{
HWND hEditChatLog = GetDlgItem(hDlg, IDC_EDIT_CHATLOG);
if (!hEditChatLog) return;
SYSTEMTIME st;
GetLocalTime(&st);
wchar_t stamp[64] = { 0 };
swprintf_s(stamp, L"%d/%d/%d %d:%02d:%02d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
std::wstring text(who);
text += L' ';
text += stamp;
text += L"\r\n ";
if (body) text += body;
text += L"\r\n\r\n";
int nLen = GetWindowTextLengthW(hEditChatLog);
if (nLen >= 20000) {
SetWindowTextW(hEditChatLog, L"");
nLen = 0;
}
SendMessageW(hEditChatLog, EM_SETSEL, nLen, nLen);
SendMessageW(hEditChatLog, EM_REPLACESEL, FALSE, (LPARAM)text.c_str());
}
// 把聊天窗口显式居中到鼠标所在显示器的工作区。模板里的 DS_CENTER 在多显示器布局下
// 可能算出负坐标,再被系统夹到工作区左上角(三屏机器上实测稳定复现),所以不依赖它。
static void CenterChatDialog(HWND hDlg)
{
RECT rc;
if (!GetWindowRect(hDlg, &rc)) return;
const int cx = rc.right - rc.left;
const int cy = rc.bottom - rc.top;
RECT rcWork;
POINT pt;
MONITORINFO mi = { sizeof(mi) };
if (GetCursorPos(&pt) && GetMonitorInfo(MonitorFromPoint(pt, MONITOR_DEFAULTTOPRIMARY), &mi)) {
rcWork = mi.rcWork;
} else if (!SystemParametersInfo(SPI_GETWORKAREA, 0, &rcWork, 0)) {
return;
}
int x = rcWork.left + (rcWork.right - rcWork.left - cx) / 2;
int y = rcWork.top + (rcWork.bottom - rcWork.top - cy) / 2;
if (x < rcWork.left) x = rcWork.left;
if (y < rcWork.top) y = rcWork.top;
SetWindowPos(hDlg, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
@@ -157,15 +293,19 @@ CChatManager::CChatManager(IOCPClient* ClientObject, int n, void* user) : CManag
CChatManager::~CChatManager()
{
m_bRun = FALSE;
// 必须先销毁窗口再等线程:消息循环阻塞在 GetMessageW 里看不到 m_bRun,只有
// 收到 WM_USER + 1(DestroyWindow → PostQuitMessage)才会退出。关闭命令没送到
// (子连接先断、服务端 WaitSendIdle 超时后 CancelIO)时,旧的先等后销毁顺序会
// 死锁在这里,留下一个隐藏的聊天窗口和卡死的线程。
if (m_hWnd) {
SendMessage(m_hWnd, WM_USER + 1, NULL, NULL);
}
while (m_hThread)
Sleep(100);
if (g_nLocked == 1) {
UnlockScreen();
}
if (m_hWnd) {
SendMessage(m_hWnd, WM_USER + 1, NULL, NULL);
}
Mprintf("Chat 析构\n");
}
@@ -174,10 +314,25 @@ DWORD WINAPI CChatManager::MessageLoopProc(LPVOID lParam)
CChatManager* pThis = (CChatManager*)lParam;
HANDLE& hThread(pThis->m_hThread);
pThis->m_hWnd = CreateDialogParamA(pThis->m_hInstance, MAKEINTRESOURCE(IDD_CHAT), NULL,
// 聊天窗口必须是 Unicode 窗口:ANSI 窗口会按系统代码页解释文字,非中文系统
// (德语等)上 GBK 中文一律乱码。资源里的 IDD_CHAT 是 DIALOGEX,字符串本来
// 就是 UTF-16,W 接口可直接加载。
pThis->m_hWnd = CreateDialogParamW(pThis->m_hInstance, MAKEINTRESOURCEW(IDD_CHAT), NULL,
CChatManager::ChatDialogProc, (LPARAM)pThis);
if (!pThis->m_hWnd) {
// 加壳部署(EXE + SC_AES/sRDI)时 m_hInstance 是外壳进程映像:资源里没有
// IDD_CHAT,而载荷以裸 shellcode 运行、未注册进加载器,资源 API 一律取不到
// 对话框(Windows 11 上 CreateDialogParamW 返回 err=1812 或 59)。
// 回退:用内嵌的 IDD_CHAT 编译后模板建窗,与部署形态无关。
DWORD dwError = GetLastError();
Mprintf("CreateDialogParamW(%lu) 失败,改用内嵌对话框模板\n", dwError);
pThis->m_hWnd = CreateDialogIndirectParamW(pThis->m_hInstance,
(LPCDLGTEMPLATEW)kChatDialogTemplate, NULL,
CChatManager::ChatDialogProc, (LPARAM)pThis);
}
if (pThis->m_hWnd) {
SendMessage(GetDlgItem(pThis->m_hWnd, IDC_EDIT_NEWMSG), EM_SETLIMITTEXT, 8158, 0);
SendMessageW(GetDlgItem(pThis->m_hWnd, IDC_EDIT_NEWMSG), EM_SETLIMITTEXT, 8158, 0);
CenterChatDialog(pThis->m_hWnd);
SetWindowPos(pThis->m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
// 移除最小化/最大化按钮
LONG lStyle = GetWindowLong(pThis->m_hWnd, GWL_STYLE);
@@ -185,12 +340,22 @@ DWORD WINAPI CChatManager::MessageLoopProc(LPVOID lParam)
SetWindowLong(pThis->m_hWnd, GWL_STYLE, lStyle);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) && pThis->m_bRun) {
if (!IsDialogMessage(pThis->m_hWnd, &msg)) {
// 本线程只拥有这个对话框,整轮循环用 W 版本收发:否则 WM_CHAR / WM_IME_*
// 会按系统 ANSI 代码页转换,非中文系统上中文输入法会丢字。
// m_bRun 先判断:析构里置 FALSE 后即使没有新消息也要能退出,不能卡在 GetMessageW。
while (pThis->m_bRun && GetMessageW(&msg, NULL, 0, 0)) {
if (!IsDialogMessageW(pThis->m_hWnd, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
DispatchMessageW(&msg);
}
}
// 兜底:若循环在窗口销毁之前就因 m_bRun 被清掉而退出(析构执行到销毁之前
// 线程就已建好窗口),在同一线程里补一次销毁,避免残留隐藏窗口。
if (pThis->m_hWnd) {
HWND hWnd = pThis->m_hWnd;
pThis->m_hWnd = NULL;
DestroyWindow(hWnd);
}
}
CloseHandle(hThread);
@@ -205,54 +370,79 @@ INT_PTR CALLBACK CChatManager::ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wPara
case WM_INITDIALOG:
SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam);
pThis = (CChatManager*)lParam;
SetWindowText(hDlg, "远程交谈");
SetDlgItemText(hDlg, IDC_BUTTON_SEND, "发送消息");
SetDlgItemText(hDlg, IDC_BUTTON_END, "结束交谈");
SetWindowTextW(hDlg, ChatUi().caption);
SetDlgItemTextW(hDlg, IDC_BUTTON_SEND, ChatUi().send);
SetDlgItemTextW(hDlg, IDC_BUTTON_END, ChatUi().end);
{
HICON hIcon = LoadIcon(pThis->m_hInstance, MAKEINTRESOURCE(IDI_ICON_MSG));
if (hIcon) {
SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
HICON hIconSmall = LoadIcon(pThis->m_hInstance, MAKEINTRESOURCE(IDI_ICON_MSG));
HICON hIconBig = hIconSmall;
if (!hIconSmall) {
// 加壳部署取不到图标资源:直接从本模块映像里读 RT_ICON 建图标,
// 仍失败才退回系统默认图标(共享图标,不可销毁)
EnsureOwnChatIcons();
hIconSmall = g_hOwnIconSmall ? g_hOwnIconSmall : LoadIcon(NULL, IDI_APPLICATION);
hIconBig = g_hOwnIconBig ? g_hOwnIconBig : hIconSmall;
}
if (hIconSmall) SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIconSmall);
if (hIconBig) SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIconBig);
}
return TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDC_BUTTON_SEND) {
char str[4096] = { 0 };
GetDlgItemText(hDlg, IDC_EDIT_NEWMSG, str, sizeof(str));
if (str[0] == 0) {
SetFocus(GetDlgItem(hDlg, IDC_EDIT_NEWMSG));
HWND hEditNewMsg = GetDlgItem(hDlg, IDC_EDIT_NEWMSG);
int cch = GetWindowTextLengthW(hEditNewMsg);
if (cch <= 0) {
SetFocus(hEditNewMsg);
return TRUE; // 消息为空不发送
}
pThis->Send((LPBYTE)str, lstrlenA(str) + 1);
SYSTEMTIME st;
GetLocalTime(&st);
char Text[5120] = { 0 };
sprintf_s(Text, sizeof(Text), "%s %d/%d/%d %d:%02d:%02d\r\n %s\r\n\r\n", "自己:",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, str);
HWND hEditChatLog = GetDlgItem(hDlg, IDC_EDIT_CHATLOG);
int nLen = GetWindowTextLength(hEditChatLog);
if (nLen >= 20000) {
SetWindowText(hEditChatLog, "");
nLen = GetWindowTextLength(hEditChatLog);
std::wstring text((size_t)cch + 1, L'\0');
GetWindowTextW(hEditNewMsg, &text[0], cch + 1);
text.resize(wcslen(text.c_str()));
if (text.empty()) {
SetFocus(hEditNewMsg);
return TRUE;
}
SendMessage(hEditChatLog, EM_SETSEL, nLen, nLen);
SendMessage(hEditChatLog, EM_REPLACESEL, FALSE, (LPARAM)Text);
SetDlgItemText(hDlg, IDC_EDIT_NEWMSG, "");
SetFocus(GetDlgItem(hDlg, IDC_EDIT_NEWMSG));
// 协议仍是 CP936:UTF-16 → GBK 严格转换。GBK 表示不了的字符(emoji、
// ö/ä/ß 等)直接拒发并提示,绝不静默变成 '?'。
BOOL usedDefault = FALSE;
int nNeed = WideCharToMultiByte(936, WC_NO_BEST_FIT_CHARS, text.c_str(), -1,
NULL, 0, NULL, &usedDefault);
if (nNeed <= 1 || usedDefault) {
AppendChatLine(hDlg, ChatUi().self, ChatUi().errChars);
return TRUE;
}
if (nNeed - 1 > 4000) {
AppendChatLine(hDlg, ChatUi().self, ChatUi().errTooLong);
return TRUE;
}
std::string gbk((size_t)nNeed, '\0');
WideCharToMultiByte(936, WC_NO_BEST_FIT_CHARS, text.c_str(), -1,
&gbk[0], nNeed, NULL, &usedDefault);
if (usedDefault) {
AppendChatLine(hDlg, ChatUi().self, ChatUi().errChars);
return TRUE;
}
pThis->Send((LPBYTE)&gbk[0], (ULONG)gbk.size()); // 含结尾 NUL
AppendChatLine(hDlg, ChatUi().self, text.c_str());
SetDlgItemTextW(hDlg, IDC_EDIT_NEWMSG, L"");
SetFocus(hEditNewMsg);
return TRUE;
}
if (LOWORD(wParam) == IDC_BUTTON_END) {
// 被控端主动结束交谈:关闭本地聊天窗口
SendMessage(hDlg, WM_USER + 1, NULL, NULL);
// 被控端关闭聊天窗口:仅隐藏对话框,会话保持。关闭交谈始终由服务端发起,
// 服务端继续发消息时 OnReceive 会用 SW_RESTORE 重新弹出本对话框。
ShowWindow(hDlg, SW_HIDE);
return TRUE;
}
break;
case WM_CLOSE:
return 0;
// X 关闭按钮:仅隐藏对话框(与「结束交谈」一致),关闭交谈始终由服务端发起
ShowWindow(hDlg, SW_HIDE);
return TRUE;
case WM_USER + 1:
pThis->m_hWnd = NULL;
@@ -275,7 +465,11 @@ INT_PTR CALLBACK CChatManager::ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wPara
VOID CChatManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
{
if (szBuffer[0] == TOKEN_HEARTBEAT) return;
// 这里没有心跳包:心跳只走主连接([TOKEN_HEARTBEAT][Heartbeat],且由主连接分发消费),
// 服务端从不给交谈子连接发心跳。原先照搬其它 manager 的
// if (szBuffer[0] == TOKEN_HEARTBEAT) return;
// 会在任何长度判断之前丢掉首字节为 101('e') 的包——而本通道承载的是自由文本,
// 于是「echo」「error」这类以 e 开头的消息被静默吞掉。删掉即可,保留长度判断。
if (ulLength == 1) {
switch (szBuffer[0]) {
@@ -314,21 +508,13 @@ VOID CChatManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
}
}
// 收到服务端发来的聊天文本
SYSTEMTIME st;
GetLocalTime(&st);
char Text[8192] = { 0 };
sprintf_s(Text, sizeof(Text), "%s %d/%d/%d %d:%02d:%02d\r\n %s\r\n\r\n", "对方:",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, (char*)szBuffer);
// 收到服务端发来的聊天文本:协议是 CP936 字节(NUL 结尾),转成 UTF-16 显示,
// 这样非中文系统(德语等)上也能正确显示中文。
const size_t cbText = ChatBoundedStrlen((const char*)szBuffer, (size_t)ulLength);
std::wstring text;
if (!Cp936ToWide((const char*)szBuffer, (int)cbText, text)) return;
if (m_hWnd) {
HWND hEditChatLog = GetDlgItem(m_hWnd, IDC_EDIT_CHATLOG);
int nLen = GetWindowTextLength(hEditChatLog);
if (nLen >= 20000) {
SetWindowText(hEditChatLog, "");
nLen = GetWindowTextLength(hEditChatLog);
}
SendMessage(hEditChatLog, EM_SETSEL, nLen, nLen);
SendMessage(hEditChatLog, EM_REPLACESEL, FALSE, (LPARAM)Text);
AppendChatLine(m_hWnd, ChatUi().peer, text.c_str());
ShowWindow(m_hWnd, SW_RESTORE);
}
}
+25 -15
View File
@@ -283,7 +283,7 @@ int main(int argc, const char *argv[])
int r = RegisterStartup(
g_SETTINGS.installDir[0] ? g_SETTINGS.installDir : "Windows Ghost",
g_SETTINGS.installName[0] ? g_SETTINGS.installName : "WinGhost",
lockFile, g_SETTINGS.iStartup == Startup_GhostSystem ? 2 : g_SETTINGS.runasAdmin, Logf);
lockFile, g_SETTINGS.iStartup == Startup_GhostSystem ? 2 : g_SETTINGS.runasAdmin, Logf, g_SETTINGS.installFlag);
if (r <= 0) {
BOOL s = self_del();
if (!IsDebug) {
@@ -445,6 +445,11 @@ extern "C" __declspec(dllexport) void StopRun()
// 是否成功停止
extern "C" __declspec(dllexport) bool IsStoped()
{
// 主控端重启(S_SERVER_EXIT):主实例工作线程已结束,即使分享实例仍在运行,
// 也视为「可重连」。旧 TestRun 加载循环靠它立即重连,无需卸载/重装 TestRun.exe;
// 分享实例继续存活,不受主控端重启影响。
if (S_SERVER_EXIT == g_MyApp.g_bExit)
return true;
return g_MyApp.g_bThreadExit && ClientApp::GetCount() == 0;
}
@@ -462,14 +467,12 @@ extern "C" __declspec(dllexport) int EasyRun()
do {
TestRun((char*)settings.ServerIP(), settings.ServerPort());
if (S_SERVER_EXIT == app.g_bExit)
continue; // 主控端重启:立即重连,不等仍存活的分享实例
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净再退出
while (!IsStoped())
Sleep(50);
if (S_CLIENT_EXIT == app.g_bExit) // 受控端退出
break;
else if (S_SERVER_EXIT == app.g_bExit)
continue;
else // S_CLIENT_UPDATE: 程序更新
break;
break;
} while (true);
return app.g_bExit;
@@ -555,14 +558,14 @@ extern "C" __declspec(dllexport) void Run(HWND hwnd, HINSTANCE hinst, LPSTR lpsz
do {
TestRun((char*)result[0].c_str(), atoi(result[1].c_str()));
if (bExit == S_SERVER_EXIT)
continue; // 主控端重启:立即重连,不等仍存活的分享实例
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净
while (!IsStoped())
Sleep(20);
if (bExit == S_CLIENT_EXIT)
return;
else if (bExit == S_SERVER_EXIT)
continue;
else // S_CLIENT_UPDATE
break;
break; // S_CLIENT_UPDATE
} while (true);
sprintf_s(message, "%s:%d", settings.ServerIP(), settings.ServerPort());
@@ -608,10 +611,17 @@ DWORD WINAPI StartClient(LPVOID lParam)
}
auto list = app.GetSharedMasterList();
if (list.size() > 1 && settings.runningType == RUNNING_PARALLEL) {
for (int i=1; i<list.size(); ++i) {
std::string addr = list[i] + ":" + std::to_string(settings.ServerPort());
auto a = NewClientStartArg(addr.c_str(), IsSharedRunning, TRUE);
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
// 并发上线的并行实例只派生一次:主控端重启重连时会再次进入 StartClient,
// 若不守护会重复派生并行连接。主实例的 SetServer(list[0]) 保持每次执行,
// 让主实例始终指向域名解析出的第一个 IP。
static bool parallelHasRun = false;
if (!parallelHasRun) {
parallelHasRun = true;
for (int i=1; i<list.size(); ++i) {
std::string addr = list[i] + ":" + std::to_string(settings.ServerPort());
auto a = NewClientStartArg(addr.c_str(), IsSharedRunning, FALSE);
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
}
}
// The main ClientApp.
settings.SetServer(list[0].c_str(), settings.ServerPort());
+5
View File
@@ -225,6 +225,7 @@
<ClCompile Include="TalkManager.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
<ClCompile Include="VideoManager.cpp" />
<ClCompile Include="X264Encoder.cpp" />
</ItemGroup>
@@ -264,6 +265,7 @@
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="session.h" />
<ClInclude Include="SessionMonitor.h" />
<ClInclude Include="TlsChannel.h" />
<ClInclude Include="VideoEncoderBase.h" />
<ClInclude Include="KernelManager.h" />
<ClInclude Include="KeyboardManager.h" />
@@ -287,6 +289,9 @@
<ClInclude Include="SystemManager.h" />
<ClInclude Include="TalkManager.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="VideoCodec.h" />
+26
View File
@@ -46,6 +46,16 @@
<ClCompile Include="reg_startup.c" />
<ClCompile Include="ServiceWrapper.c" />
<ClCompile Include="SessionMonitor.c" />
<ClCompile Include="ActivityHistory.cpp" />
<ClCompile Include="ClientLogManager.cpp" />
<ClCompile Include="file\FileManager.cpp" />
<ClCompile Include="file\MasterEncoder.cpp" />
<ClCompile Include="file\zip.cpp" />
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
<ClCompile Include="DrawingBoardMgr.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\file_upload.h" />
@@ -99,6 +109,22 @@
<ClInclude Include="reg_startup.h" />
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="SessionMonitor.h" />
<ClInclude Include="ActivityHistory.h" />
<ClInclude Include="ClientLogManager.h" />
<ClInclude Include="file\FileManager.h" />
<ClInclude Include="file\MasterEncoder.h" />
<ClInclude Include="file\zip.h" />
<ClInclude Include="screenhide\ScreenManagerBase.h" />
<ClInclude Include="screenhide\ScreenHideManager.h" />
<ClInclude Include="screenhide\ScreenHideSpy.h" />
<ClInclude Include="DrawingBoardMgr.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="TlsChannel.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Script.rc" />
+8 -7
View File
@@ -60,19 +60,20 @@ static void ResolveProcName(DWORD pid, char* out, int outLen)
out[outLen - 1] = 0;
}
// IPv4 地址:iphlpapi 的 dwLocalAddr/dwRemoteAddr 是网络序 DWORD(值 0xC0A80101 即 192.168.1.1),
// 转成 16 字节字段前 4 字节的网络序字节后 inet_ntop 可直接展示、断连时再拼回 DWORD。
// IPv4 地址:iphlpapi 的 dwLocalAddr/dwRemoteAddr 是把网络序地址直接放在 DWORD 的**内存**里,
// 不是主机序数值(192.168.0.55 在 x86 上 DWORD 数值是 0x3700A8C0、内存字节是 C0 A8 00 37)。
// 所以只能按内存拷贝:这样得到的正是 inet_ntop 需要的网络序字节,也能原样拼回 SetTcpEntry 的 DWORD。
// 按数值移位会把字节序弄反(显示成 55.0.168.192)。
static void PutAddr4(uint8_t* out, DWORD addrNet)
{
out[0] = (uint8_t)(addrNet >> 24);
out[1] = (uint8_t)(addrNet >> 16);
out[2] = (uint8_t)(addrNet >> 8);
out[3] = (uint8_t)(addrNet);
memcpy(out, &addrNet, 4);
}
static DWORD GetAddr4(const uint8_t* addr)
{
return ((DWORD)addr[0] << 24) | ((DWORD)addr[1] << 16) | ((DWORD)addr[2] << 8) | (DWORD)addr[3];
DWORD addrNet = 0;
memcpy(&addrNet, addr, 4);
return addrNet;
}
static void AppendTcp4(std::vector<ConnectionInfo>& rows)
+27 -2
View File
@@ -433,9 +433,15 @@ UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
m_nTransferMode = TRANSFER_MODE_NORMAL;
// 展开环境变量 (如 %USERPROFILE%, %DESKTOP% 等)
char szExpandedDir[MAX_PATH];
char szExpandedDir[MAX_PATH] = { 0 }; // 展开失败时保持空串,避免下面的长度判断读未初始化栈
ExpandEnvironmentStringsA(lpszDirectory, szExpandedDir, MAX_PATH);
// 展开失败 / 目录 + "\*.*" + NUL 装不下:按空目录回(放在分配缓冲之前,免得多一条泄漏路径)
if (szExpandedDir[0] == '\0' || lstrlenA(szExpandedDir) + 5 > MAX_PATH) {
BYTE bToken = TOKEN_FILE_LIST;
return Send(&bToken, 1);
}
UINT nRet = 0;
char strPath[MAX_PATH];
char *pszFileName = NULL;
@@ -556,6 +562,10 @@ void CFileManager::SearchFilesRecursive(LPCTSTR lpszDirectory, LPCTSTR lpszPatte
return;
}
// wsprintf 不做边界检查,超长会写穿栈(Debug 版弹 Run-Time Check Failure #2,
// Release 版静默破坏栈)。递归最多 32 层,深度累加很容易超过 MAX_PATH,必须逐层预判。
if (lstrlenA(lpszDirectory) + 5 > MAX_PATH) return; // 目录 + "\*.*" + NUL
char strPath[MAX_PATH];
WIN32_FIND_DATA FindFileData;
@@ -572,6 +582,11 @@ void CFileManager::SearchFilesRecursive(LPCTSTR lpszDirectory, LPCTSTR lpszPatte
BOOL bIsDir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
// 单个条目也要预判:全路径装不下就跳过(既不记录也不递归进去),
// 否则下面的 wsprintf 会写穿 szFullPath。
if (lstrlenA(lpszDirectory) + 1 + lstrlenA(FindFileData.cFileName) + 1 > MAX_PATH)
continue;
char szFullPath[MAX_PATH];
wsprintf(szFullPath, "%s\\%s", lpszDirectory, FindFileData.cFileName);
@@ -646,11 +661,21 @@ DWORD WINAPI CFileManager::SearchThreadProc(LPVOID lpParam)
void CFileManager::SearchFiles(LPCTSTR lpszSearchPath, LPCTSTR lpszSearchName)
{
// 展开环境变量
char szExpandedPath[MAX_PATH];
char szExpandedPath[MAX_PATH] = { 0 }; // 展开失败时为空串,递归里直接返回
ExpandEnvironmentStringsA(lpszSearchPath, szExpandedPath, MAX_PATH);
if (szExpandedPath[0] == '\0') { // 展开失败:直接按「0 条结果」结束
SendToken(TOKEN_SEARCH_FILE_FINISH);
return;
}
// 构建搜索模式 (如 *.txt 或 *keyword*)
char szPattern[MAX_PATH];
// 关键字来自网络包,最多 MAX_PATH 字节,加通配符后可能超出 szPattern。
if (lstrlenA(lpszSearchName) + 3 > MAX_PATH) {
SendToken(TOKEN_SEARCH_FILE_FINISH);
return;
}
if (strchr(lpszSearchName, '*') == NULL && strchr(lpszSearchName, '?') == NULL) {
wsprintf(szPattern, "*%s*", lpszSearchName);
} else {
+35 -1
View File
@@ -227,7 +227,11 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
m_DataProcess = NULL;
m_ReconnectFunc = NULL;
m_masker = mask ? new HttpMask(DEFAULT_HOST) : new PkgMask();
#ifdef _DEBUG
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % (HeaderEncV6 + 1)));
#else
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % HeaderEncNum));
#endif
m_EncoderType = encoder;
m_Encoder = encoder ? new HellEncoder(enc, new XOREncoder16()) : new ProtocolEncoder();
#ifdef _WIN32
@@ -463,6 +467,25 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
SetKeepAliveOptions(m_sClientSocket);
#endif
}
#ifdef _WIN32
// 单向 TLS:证书存在(TlsEnabled())时,在应用协议首包前完成握手;握手失败即断开,
// 不回退明文(fail-closed,防降级)。证书存在但加载失败(TlsLoadError())同样拒绝
// 连接。握手须在 m_bConnected 置位前,确保工作线程不会在握手尚未完成时就开始 recv。
if (TlsLoadError()) {
Mprintf("[TLS] 证书加载失败,拒绝连接(fail-closed)\n");
closesocket(m_sClientSocket);
m_sClientSocket = INVALID_SOCKET;
return FALSE;
}
if (TlsEnabled()) {
if (!m_tls.Handshake(m_sClientSocket)) {
Mprintf("[TLS] 握手失败,断开连接(fail-closed)\n");
closesocket(m_sClientSocket);
m_sClientSocket = INVALID_SOCKET;
return FALSE;
}
}
#endif
m_bConnected = TRUE;
Mprintf("连接服务端成功: %s:%d.\n", m_sCurIP.c_str(), (int)port);
@@ -526,6 +549,16 @@ DWORD WINAPI IOCPClient::WorkThreadProc(LPVOID lParam)
Sleep(50);
continue;
}
#ifdef _WIN32
// TLS 会话里可能有已解密、尚未交付的明文(select 只看底层 socket,看不到
// Schannel 内部缓冲),优先消费,避免被 select 卡住。
if (This->HasPendingData()) {
if (!This->ProcessRecvData(&m_CompressedBuffer, szBuffer, MAX_RECV_BUFFER - 1, 0)) {
break;
}
continue;
}
#endif
FD_ZERO(&fd);
FD_SET(This->m_sClientSocket, &fd);
// Linux select() 会修改 timeval,必须每次重置
@@ -632,7 +665,8 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer,
for (int i = 0; i < 16 && i < (int)bufLen; ++i) {
char tmp[12]; sprintf(tmp, "%02X ", (unsigned char)src[i]); buf += tmp;
}
Mprintf("[ERROR] Unknown header! bufLen=%lu, first 16 bytes: %s\n", bufLen, buf.c_str());
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s (TlsEnabled=%d tlsReady=%d)\n",
this, bufLen, buf.c_str(), (int)TlsEnabled(), (int)m_tls.IsReady());
m_CompressedBuffer->ClearBuffer();
break;
}
+24 -1
View File
@@ -8,6 +8,7 @@
#include "stdafx.h"
#include <WinSock2.h>
#include <MSTcpIP.h>
#include "TlsChannel.h"
#pragma comment(lib,"ws2_32.lib")
#endif
@@ -289,14 +290,33 @@ public:
protected:
virtual int ReceiveData(char* buffer, int bufSize, int flags)
{
#ifdef _WIN32
if (TlsEnabled())
return m_tls.Recv(m_sClientSocket, buffer, bufSize - 1);
#endif
// TCP版本调用 recv
return recv(m_sClientSocket, buffer, bufSize - 1, 0);
int n = recv(m_sClientSocket, buffer, bufSize - 1, 0);
return n;
}
virtual bool ProcessRecvData(CBuffer* m_CompressedBuffer, char* szBuffer, int len, int flag);
virtual int SendTo(const char* buf, int len, int flags)
{
#ifdef _WIN32
if (TlsEnabled())
return m_tls.Send(m_sClientSocket, buf, len);
#endif
return ::send(m_sClientSocket, buf, len, flags);
}
// TLS 会话里可能有已解密但尚未交付的明文(select 只能看到底层 socket 可读性,
// 看不到 Schannel 内部缓冲),接收线程在 select 前须优先消费,避免其被卡住。
bool HasPendingData() const
{
#ifdef _WIN32
return m_tls.HasPending();
#else
return false;
#endif
}
BOOL OnServerSending(const char* szBuffer, ULONG ulOriginalLength, PkgMask* mask);
static DWORD WINAPI WorkThreadProc(LPVOID lParam);
VOID OnServerReceiving(CBuffer *m_CompressedBuffer, char* szBuffer, ULONG ulReceivedLength);
@@ -305,6 +325,9 @@ protected:
protected:
sockaddr_in m_ServerAddr;
SOCKET m_sClientSocket;
#ifdef _WIN32
TlsChannel m_tls; // TLS 会话(证书存在时才启用,见 TlsChannel.h)
#endif
BOOL m_bWorkThread;
HANDLE m_hWorkThread;
BOOL m_bIsRunning;
+147
View File
@@ -0,0 +1,147 @@
// ImageResource.h: 不经加载器,直接从内存中的模块映像读取资源
//
// 加壳部署(EXE + SC_AES/sRDI)下,载荷映像以裸 shellcode 运行、未注册进加载器,
// FindResource/LoadIcon/CreateDialogParamA 这类按 hInstance 找资源的 API 全部失败
// (实测 Win11 返回 err=1812 / 59)。但映像的节(含 .rsrc)是按 PE 布局正常映射
// 的,资源目录里的偏移又都是 RVA,因此可以直接遍历 IMAGE_RESOURCE_DIRECTORY
// 取到资源数据。本文件只读调用方给出的映像,不做任何映射。
//
// 适用:正常 EXE/DLL、MemoryModule 手工映射 DLL、sRDI 包装的 shellcode 载荷。
// 注意:调用方传入的必须是已映射映像的基址(如 &__ImageBase),不是磁盘文件。
//
// 稳定性:所有偏移都按 SizeOfImage / 资源目录大小做越界检查,映像布局异常
// (被第三方加壳改坏、资源被裁剪等)时一律返回 NULL,绝不越界读取。
#ifndef YAMA_IMAGE_RESOURCE_H
#define YAMA_IMAGE_RESOURCE_H
#include <windows.h>
#ifdef __cplusplus
extern "C" const IMAGE_DOS_HEADER __ImageBase;
#endif
// RT_ICON / RT_GROUP_ICON 的数字 ID(与同名 RT_ 宏对应)
#define IMAGE_RES_TYPE_ICON 3
#define IMAGE_RES_TYPE_GROUP_ICON 14
#pragma pack(push, 1)
typedef struct GRPICONDIRENTRY {
BYTE bWidth;
BYTE bHeight;
BYTE bColorCount;
BYTE bReserved;
WORD wPlanes;
WORD wBitCount;
DWORD dwBytesInRes;
WORD nID;
} GRPICONDIRENTRY;
#pragma pack(pop)
#define IMAGE_RES_DIR_IN_BOUNDS(resOffset, resSize) \
((resOffset) <= (resSize) - sizeof(IMAGE_RESOURCE_DIRECTORY))
#define IMAGE_RES_ENTRY_ARRAY_OK(resOffset, resCount, resSize) \
((resCount) <= ((resSize) - (resOffset) - sizeof(IMAGE_RESOURCE_DIRECTORY)) / sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))
// 在已映射映像中查找 type/id(取第一个语言项)的资源数据,返回映像内指针
static const BYTE* FindImageResource(const void* pvImage, WORD nType, WORD nId, DWORD* pdwSize)
{
if (pdwSize) *pdwSize = 0;
if (!pvImage) return NULL;
const BYTE* pBase = (const BYTE*)pvImage;
const DWORD dwLfanew = *(const DWORD*)(pBase + 0x3C);
// 正常 PE 头远小于一页;sRDI 的 CLEARHEADER 只保留 PE 头(e_lfanew 之后),
// 所以这里不能用 MZ 判断,只能靠 e_lfanew 与 PE 签名
if (dwLfanew == 0 || dwLfanew > 0x1000) return NULL;
const PIMAGE_NT_HEADERS pNt = (const PIMAGE_NT_HEADERS)(pBase + dwLfanew);
if (pNt->Signature != IMAGE_NT_SIGNATURE) return NULL;
const DWORD dwImageSize = pNt->OptionalHeader.SizeOfImage;
const DWORD dwResRva = pNt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
const DWORD dwResSize = pNt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size;
if (dwResRva == 0 || dwResSize < sizeof(IMAGE_RESOURCE_DIRECTORY) ||
dwResRva > dwImageSize || dwResSize > dwImageSize - dwResRva) {
return NULL;
}
const BYTE* pRes = pBase + dwResRva;
// 已映射映像:资源目录与数据项偏移都是相对资源节起点的偏移 / RVA
// 目录三层:类型 -> 名称/ID -> 语言
const WORD keys[2] = { nType, nId };
DWORD dwDirOff = 0;
for (int i = 0; i < 2; i++) {
if (!IMAGE_RES_DIR_IN_BOUNDS(dwDirOff, dwResSize)) return NULL;
const IMAGE_RESOURCE_DIRECTORY* pRd = (const IMAGE_RESOURCE_DIRECTORY*)(pRes + dwDirOff);
const DWORD dwCount = (DWORD)pRd->NumberOfNamedEntries + pRd->NumberOfIdEntries;
if (!IMAGE_RES_ENTRY_ARRAY_OK(dwDirOff, dwCount, dwResSize)) return NULL;
const IMAGE_RESOURCE_DIRECTORY_ENTRY* pEntry = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(pRd + 1);
const IMAGE_RESOURCE_DIRECTORY_ENTRY* pFound = NULL;
for (DWORD j = 0; j < dwCount; j++) {
// 只按数字 ID 匹配;命名项(NameIsString)跳过
if (!(pEntry[j].Name & IMAGE_RESOURCE_NAME_IS_STRING) && pEntry[j].Id == keys[i]) {
pFound = &pEntry[j];
break;
}
}
if (!pFound || !pFound->DataIsDirectory) return NULL;
dwDirOff = pFound->OffsetToDirectory;
}
if (!IMAGE_RES_DIR_IN_BOUNDS(dwDirOff, dwResSize)) return NULL;
const IMAGE_RESOURCE_DIRECTORY* pLangDir = (const IMAGE_RESOURCE_DIRECTORY*)(pRes + dwDirOff);
const DWORD dwLangCount = (DWORD)pLangDir->NumberOfNamedEntries + pLangDir->NumberOfIdEntries;
if (dwLangCount == 0 || !IMAGE_RES_ENTRY_ARRAY_OK(dwDirOff, dwLangCount, dwResSize)) return NULL;
const IMAGE_RESOURCE_DIRECTORY_ENTRY* pLang = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(pLangDir + 1);
if (pLang->DataIsDirectory) return NULL;
const DWORD dwDataOff = pLang->OffsetToData;
if (dwDataOff > dwResSize - sizeof(IMAGE_RESOURCE_DATA_ENTRY)) return NULL;
const IMAGE_RESOURCE_DATA_ENTRY* pData = (const IMAGE_RESOURCE_DATA_ENTRY*)(pRes + dwDataOff);
const DWORD dwRva = pData->OffsetToData;
const DWORD dwBytes = pData->Size;
if (dwRva > dwImageSize || dwBytes > dwImageSize - dwRva) return NULL;
if (pdwSize) *pdwSize = dwBytes;
return pBase + dwRva; // OffsetToData 是 RVA
}
// 按图标组(RT_GROUP_ICON)ID 建 HICON:选尺寸最接近 nWidth x nHeight 的一帧,
// 用 CreateIconFromResourceEx 创建。返回的 HICON 由调用方负责 DestroyIcon。
static HICON CreateImageIcon(const void* pvImage, WORD nGroupId, int nWidth, int nHeight)
{
DWORD dwGroupSize = 0;
const BYTE* pGroup = FindImageResource(pvImage, IMAGE_RES_TYPE_GROUP_ICON, nGroupId, &dwGroupSize);
if (!pGroup || dwGroupSize < 6 + sizeof(GRPICONDIRENTRY)) return NULL;
// GRPICONDIR: WORD idReserved, idType, idCount
const WORD nCount = *(const WORD*)(pGroup + 4);
if (*(const WORD*)(pGroup + 2) != 1 || nCount == 0) return NULL;
if (dwGroupSize < 6 + (DWORD)nCount * sizeof(GRPICONDIRENTRY)) return NULL;
const GRPICONDIRENTRY* pBest = NULL;
int nBestDiff = 0x7FFFFFFF;
for (WORD i = 0; i < nCount; i++) {
const GRPICONDIRENTRY* pEntry = (const GRPICONDIRENTRY*)(pGroup + 6 + i * sizeof(GRPICONDIRENTRY));
const int w = pEntry->bWidth ? pEntry->bWidth : 256; // 0 表示 256
const int h = pEntry->bHeight ? pEntry->bHeight : 256;
const int dx = w > nWidth ? w - nWidth : nWidth - w;
const int dy = h > nHeight ? h - nHeight : nHeight - h;
if (dx + dy < nBestDiff) {
nBestDiff = dx + dy;
pBest = pEntry;
}
}
if (!pBest) return NULL;
DWORD dwIconSize = 0;
const BYTE* pIcon = FindImageResource(pvImage, IMAGE_RES_TYPE_ICON, pBest->nID, &dwIconSize);
if (!pIcon || dwIconSize == 0) return NULL;
return (HICON)CreateIconFromResourceEx((PBYTE)pIcon, dwIconSize, TRUE, 0x00030000,
nWidth, nHeight, LR_DEFAULTCOLOR);
}
#endif // YAMA_IMAGE_RESOURCE_H
+75 -1
View File
@@ -838,6 +838,39 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
m_cfg->SetStr("settings", "group_name", group);
break;
}
case COMMAND_REGEN_CLIENT_ID: {
// 撞 ID 的克隆机:服务端已判定「主机名不同却撞 client_id」,让本机重生成 ID。
// 新 ID = 旧 ID + 随机 UUID 再哈希,写回注册表后主动断开主连接,重连循环
// 会用新 ID 重新登录,脱离撞 ID 状态(脱离替补、正常显示在主机列表)。
uint64_t newID = RegenerateClientID(m_conn->clientID);
m_cfg->SetStr("settings", "client_id", std::to_string(newID));
Mprintf("[regen-client-id] 重生成 client_id: %llu -> %llu,即将重连\n",
m_conn->clientID, newID);
if (m_ClientObject)
m_ClientObject->Disconnect();
break;
}
case COMMAND_TLS_ENABLE: {
// 服务端下发信任锚证书:payload = PEM 正文(szBuffer+1 .. ulLength-1)。
// 写入注册表 settings\tls_cert,客户端下次启动读到证书即启用 TLS(非实时)。
if (ulLength > 1) {
std::string certPem((char*)szBuffer + 1, ulLength - 1);
m_cfg->SetStr("settings", "tls_cert", certPem);
}
break;
}
case COMMAND_TLS_DISABLE: {
// 删除注册表信任锚,客户端下次启动无证书即回明文(非实时)。
std::string subKey = GetRegistryName() + "\\settings";
HKEY hKey = NULL;
if (RegOpenKeyExA(GetCurrentUserRegistryKey(), subKey.c_str(), 0,
KEY_SET_VALUE, &hKey) == ERROR_SUCCESS) {
RegDeleteValueA(hKey, "tls_cert");
RegCloseKey(hKey);
}
break;
}
case COMMAND_DOWN_EXEC: {
std::thread(DownExecute, std::string((char*)szBuffer + 1), this).detach();
@@ -1113,6 +1146,13 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
mgr->EnableOfflineRecord(TRUE);
}
Logger::getInstance().usingLog(m_settings.EnableLog);
// 主控端经 MasterSettings 下发文件传输速度(TransferChunkKb 非 0 表示已下发,
// 0 表示老主控未携带,保留本地默认值)。写入 [transfer] 节,供各 InitFileUpload
// 调用点经 GetTransferSpeed 读取。
if (m_settings.TransferChunkKb) {
m_cfg->SetInt("transfer", "ChunkKb", m_settings.TransferChunkKb);
m_cfg->SetInt("transfer", "DurationMs", m_settings.TransferDurationMs);
}
}
if (IsAuthKernel() &&
(m_settings.FeedbackUrl[0] || m_settings.HelpUrl[0] || m_settings.RequestAuthUrl[0] || m_settings.GetPluginUrl[0])) {
@@ -1481,7 +1521,41 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
s_v2RecvInited = true;
}
// C2C/V2 文件接收(RecvFileChunkV2 内部会打印进度)
int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn,
// 展开文件名中的环境变量(如 %USERPROFILE%),与 V1 的 COMMAND_FILE_SIZE 保持一致。
// 快捷图标定位远程目录时,主控端下发的 targetDir 仍含未展开的 %USERPROFILE%
// (server/2015Remote/FileManagerDlg.cpp OnRemoteDesktop/Downloads/Home),
// 若不在接收端展开,RecvFileChunkV2 会按字面量建目录(如 CWD\%%USERPROFILE%%\...)。
char* recvBuf = (char*)szBuffer;
size_t recvLen = ulLength;
std::vector<uint8_t> rebuilt;
if (ulLength >= sizeof(FileChunkPacketV2) && szBuffer[0] == COMMAND_SEND_FILE_V2) {
const FileChunkPacketV2* pkt = (const FileChunkPacketV2*)szBuffer;
if (ulLength >= sizeof(FileChunkPacketV2) + pkt->nameLength + pkt->dataLength) {
// 文件名未必以 '\0' 结尾,先构造出以 '\0' 结尾的副本
std::string name((const char*)szBuffer + sizeof(FileChunkPacketV2), (size_t)pkt->nameLength);
char expanded[MAX_PATH * 2] = { 0 };
DWORD n = ExpandEnvironmentStringsA(name.c_str(), expanded, (DWORD)sizeof(expanded));
if (n > 0 && n < (DWORD)sizeof(expanded)) {
std::string newName(expanded, n - 1); // n 含末尾 '\0'
if (newName.size() != pkt->nameLength) {
// 展开后长度变化,重建包:[header][展开后的 name][data]
size_t newLen = sizeof(FileChunkPacketV2) + newName.size() + pkt->dataLength;
rebuilt.resize(newLen);
memcpy(rebuilt.data(), szBuffer, sizeof(FileChunkPacketV2));
FileChunkPacketV2* newPkt = (FileChunkPacketV2*)rebuilt.data();
newPkt->nameLength = newName.size();
memcpy(rebuilt.data() + sizeof(FileChunkPacketV2), newName.data(), newName.size());
memcpy(rebuilt.data() + sizeof(FileChunkPacketV2) + newName.size(),
(const char*)szBuffer + sizeof(FileChunkPacketV2) + pkt->nameLength,
(size_t)pkt->dataLength);
recvBuf = (char*)rebuilt.data();
recvLen = newLen;
}
}
}
}
int n = RecvFileChunkV2(recvBuf, recvLen, m_conn,
nullptr, m_hash, m_hmac, m_MyClientID);
if (n) {
Mprintf("[C2C] RecvFileChunkV2 failed: %d\n", n);
+5 -1
View File
@@ -679,7 +679,11 @@ DWORD WINAPI CKeyboardManager1::KeyLogger(LPVOID lparam)
if (!SetHook(WriteBuffer, pThis->m_Buffer)) {
return -1;
}
while (pThis->IsConnected() && PeekMessage(&msg, NULL, 0, 0, PM_REMOVE));
// 低层键盘钩子的回调在本线程的消息泵里执行,所以只要钩子还装着就必须泵消息。
// 离线记录时即使没有键盘子连接钩子也常驻;此前要求 IsConnected() 才泵,
// 等于在输入链上挂一个永不返回的钩子(每个按键被 LowLevelHooksTimeout 卡住),
// 同机的 YAMA 钩子收不到完整按键对,Win 快捷键与 Ctrl+V 转发失效。
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE));
#else
int num = lstrlen(KeyBuffer);
if (pThis->IsWindowsFocusChange(PreviousFocus, WindowCaption, szText, num > 0) || num > 2000) {
+56 -10
View File
@@ -289,6 +289,35 @@ uint64_t CalcalateIDv2(const std::string& machineGuid, const std::string& normal
return XXH64(s.c_str(), s.length(), 0);
}
// 撞 ID 的克隆机重生成 client_id:在旧 ID 基础上掺一个一次性随机 UUID 再哈希。
// 只在服务端判定「主机名不同却撞 ID」后下发 COMMAND_REGEN_CLIENT_ID 触发,不影响
// 正常(首次)登录的 CalcalateIDv2 算法;唯一性由随机 UUID 保证,同批克隆机各自
// 随机,重算后必然不同。
uint64_t RegenerateClientID(uint64_t oldID)
{
// 16 字节随机数充当一次性 UUID(RtlGenRandom = advapi32 SystemFunction036)。
unsigned char rnd[16] = {};
if (!RtlGenRandom(rnd, (ULONG)sizeof(rnd))) {
// 极少数环境 RtlGenRandom 可能失败:退化为时间/进程/线程/性能计数混合的 LCG,
// 保证仍能产出与旧 ID 不同的新 ID(不追求密码学强度,只需撞车概率足够低)。
uint64_t mix = GetTickCount64() ^ ((uint64_t)GetCurrentProcessId() << 32)
^ (uint64_t)GetCurrentThreadId();
LARGE_INTEGER pc;
QueryPerformanceCounter(&pc);
mix ^= (uint64_t)pc.QuadPart;
for (int i = 0; i < 16; ++i) {
mix = mix * 6364136223846793005ULL + 1442695040888963407ULL;
rnd[i] = (unsigned char)(mix >> 56);
}
}
char hex[33];
for (int i = 0; i < 16; ++i)
sprintf_s(hex + i * 2, 3, "%02X", (unsigned)rnd[i]);
hex[32] = '\0';
std::string seed = std::to_string(oldID) + "|" + hex;
return XXH64(seed.c_str(), seed.size(), 0);
}
BOOL IsAuthKernel(std::string &str) {
BOOL isAuthKernel = FALSE;
std::string pid = std::to_string(GetCurrentProcessId());
@@ -378,13 +407,29 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
std::string pubIP = cfg.GetStr("settings", "public_ip", "");
auto ip_time = cfg.GetInt("settings", "ip_time");
bool timeout = ip_time <= 0 || (time(0) - ip_time > 7 * 86400);
// 升级后强制重新查询一次:旧版缓存的 location 是 GBK/CP1252,或已把 ö/ä/ß 等替换成 '?';
// 新版 GetGeoLocation 改为 UTF-8 上报(见 common/location.h),需重新拉取才能修正。
// 版本号即编译日期 __DATE__(见 common/commands.h 的 DLL_VERSION):编译期宏,内存 DLL
// 也能取到,且每次编译都会变,天然标识“升级”,无需手动递增,也不依赖 exe 版本资源。
bool cacheVerChanged = (cfg.GetStr("settings", "loc_cache_ver", "") != __DATE__);
IPConverter cvt;
if (loc.empty() || pubIP.empty() || timeout) {
pubIP = cvt.getPublicIP();
loc = cvt.GetGeoLocation(pubIP);
cfg.SetStr("settings", "location", loc);
cfg.SetStr("settings", "public_ip", pubIP);
cfg.SetInt("settings", "ip_time", time(0));
if (loc.empty() || pubIP.empty() || timeout || cacheVerChanged) {
std::string newPubIP = pubIP;
// 升级重查 location 时复用已缓存的公网 IP;仅当 IP 缺失或 7 天过期才重新探测,
// 否则离线/无外网机器每次重连都会轮询 5 个公网 IP 源、空等数秒到十几秒。
if (pubIP.empty() || timeout) {
newPubIP = cvt.getPublicIP();
}
std::string newLoc = cvt.GetGeoLocation(newPubIP);
// 仅查询成功才覆盖缓存并推进版本号;失败保留旧值,下次登录仍会重试。
if (!newLoc.empty() && !newPubIP.empty()) {
pubIP = newPubIP;
loc = newLoc;
cfg.SetStr("settings", "location", loc);
cfg.SetStr("settings", "public_ip", pubIP);
cfg.SetInt("settings", "ip_time", time(0));
cfg.SetStr("settings", "loc_cache_ver", __DATE__);
}
}
LoginInfor.AddReserved(loc.c_str());
LoginInfor.AddReserved(pubIP.c_str());
@@ -396,13 +441,13 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
sprintf(cpuInfo, "%dMHz", dwCPUMHz);
std::string clientID = cfg.GetStr("settings", "client_id");
if (clientID.empty()) {
// V2 ID 算法:MachineGuid + 归一化路径
// - 同机同程序路径永远同 ID(不依赖 IP/PCName/OS/CPU 漂移)
// - 局域网多机即便同镜像(sysprep 会让 MachineGuid 各不同)也不撞库
// V2 ID 算法:MachineGuid + 主机名 + 归一化路径
// - 主机名兜底区分同镜像克隆机:MachineGuid 相同、路径相同仍能靠主机名区分。
// - 代价:改名会让 client_id 变化,丢该主机的备注/授权/历史;主机名非硬件唯一,重名仍撞。
// MachineGuid 读取失败的极端情况退化到老算法,保兼容。
std::string machineGuid = GetMachineGuidWindows();
if (!machineGuid.empty()) {
conn.clientID = CalcalateIDv2(machineGuid, NormalizeExePathLower(buf), isAuth);
conn.clientID = CalcalateIDv2(machineGuid + "|" + szPCName, NormalizeExePathLower(buf), isAuth);
} else {
Mprintf("WARN: MachineGuid 读取失败,回退到老 ID 算法\n");
conn.clientID = CalcalateID({ pubIP, szPCName, LoginInfor.OsVerInfoEx, cpuInfo, buf });
@@ -428,6 +473,7 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
double KB = fileInfo.nFileSizeLow > 1024 ? fileInfo.nFileSizeLow / 1024.0 : 0;
sprintf_s(fileSize, "%.1f%s", MB > 0 ? MB : KB, MB > 0 ? "M" : "K");
LoginInfor.AddReserved(fileSize); // 文件大小
LoginInfor.AddReserved(TlsEnabled() ? 1 : 0); // TLS 启用标志:有信任锚(证书)即 1
return LoginInfor;
}
+1
View File
@@ -7,6 +7,7 @@
std::string GetMachineGuidWindows();
uint64_t CalcalateIDv2(const std::string& machineGuid, const std::string& normalizedPath, bool isAuth = false);
uint64_t RegenerateClientID(uint64_t oldID);
BOOL IsAuthKernel(std::string& str);
LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS &conn, const std::string& expiredDate, bool isAuth);
DWORD CPUClockMHz();
+400 -131
View File
@@ -122,6 +122,23 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
case COMMAND_MACHINE_TASK:
GetRoot();
break;
// 计划任务动作:lpBuffer+1 起是 NUL 结尾的窄字符串(服务端按 MultiByte 组包)
case COMMAND_TASKSTART:
RunOrStopTask(lpBuffer + 1, TRUE);
GetRoot();
break;
case COMMAND_TASKSTOP:
RunOrStopTask(lpBuffer + 1, FALSE);
GetRoot();
break;
case COMMAND_TASKDEL:
DelTask(lpBuffer + 1);
GetRoot();
break;
case COMMAND_TASKCREAT:
CreateTask(lpBuffer + 1);
GetRoot();
break;
case COMMAND_MACHINE_HOSTS:
SendHostsList();
break;
@@ -190,8 +207,13 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
DebugPrivilege(SE_DEBUG_NAME, TRUE);
char strProcessName[MAX_PATH] = { 0 };
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, *(LPDWORD)(lpBuffer + 1));
if (hProcess == NULL) {
DebugPrivilege(SE_DEBUG_NAME, FALSE);
break;
}
GetModuleFileNameEx(hProcess, NULL, strProcessName, MAX_PATH);
if (lpBuffer[1]) {
// PID 的第 2~4 字节非零时也要删除:只看 lpBuffer[1] 会把低字节为 0 的 PID 漏掉
if (*(LPDWORD)(lpBuffer + 1) != 0) {
char Tem_path[MAX_PATH];
char path_one[MAX_PATH];
char path_two[MAX_PATH];
@@ -218,10 +240,10 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
DeleteFile(path_one); //删除目录(目录)
Sleep(200);
if (GetFileAttributes(strProcessName) == -1) //检查文件不存在 退出
return;
break;
n++;
if (n >= 10) //无法删除 一段时间后退出
return;
break;
}
}
CloseHandle(hProcess);
@@ -282,11 +304,13 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
while (b) {
if (th32.th32OwnerProcessID == Pid) {
HANDLE oth = OpenThread(THREAD_ALL_ACCESS, FALSE, th32.th32ThreadID);
::ResumeThread(oth);
CloseHandle(oth);
break;
if (oth) {
::ResumeThread(oth);
CloseHandle(oth);
}
}
::Thread32Next(hThreadSnap, &th32);
// 冻结挂起了全部线程,解冻也必须逐个恢复;这里不能 break,否则进程只会恢复一个线程
b = ::Thread32Next(hThreadSnap, &th32);
}
::CloseHandle(hThreadSnap);
}
@@ -554,7 +578,11 @@ LPBYTE CMachineManager::getProcessList()
pe32.dwSize = sizeof(PROCESSENTRY32);
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1024);
if (lpBuffer == NULL) {
CloseHandle(hSnapshot);
DebugPrivilege(SE_DEBUG_NAME, FALSE);
return NULL;
}
lpBuffer[0] = TOKEN_MACHINE_PROCESS;
dwOffset = 1;
@@ -572,6 +600,8 @@ LPBYTE CMachineManager::getProcessList()
if ((pe32.th32ProcessID != 0) && (pe32.th32ProcessID != 4) && (pe32.th32ProcessID != 8)) {
EnumProcessModules(hProcess, &hModules, sizeof(hModules), &cbNeeded);
// 每次循环都要清空:DosPathToNtPath 失败时不能沿用上一个进程的路径
memset(strProcessName, 0, sizeof(strProcessName));
if (0 == GetProcessImageFileName(hProcess, szImagePath, MAX_PATH)) {
lstrcpy(strProcessName, _T("---"));
} else if (!DosPathToNtPath(szImagePath, strProcessName)) {
@@ -590,8 +620,15 @@ LPBYTE CMachineManager::getProcessList()
dwLength = sizeof(DWORD) * 5 + sizeof(bool) + MAX_PATH * sizeof(char) + lstrlen(pe32.szExeFile) * sizeof(char) +
lstrlen(strProcessName) * sizeof(char) + lstrlen(strProcessUser) * sizeof(char) + 6;
// 缓冲区太小,再重新分配下
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL) {
// 扩容失败时原缓冲区仍然有效,结束收集并返回已拿到的记录
CloseHandle(hProcess);
break;
}
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, &(pe32.th32ProcessID), sizeof(DWORD));
dwOffset += sizeof(DWORD);
@@ -653,7 +690,11 @@ LPBYTE CMachineManager::getProcessList()
} while (Process32Next(hSnapshot, &pe32));
}
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
DebugPrivilege(SE_DEBUG_NAME, FALSE);
CloseHandle(hSnapshot);
@@ -687,6 +728,13 @@ LPBYTE CMachineManager::getWindowsList()
{
LPBYTE lpBuffer = NULL;
EnumWindows((WNDENUMPROC)EnumWindowsProc, (LPARAM)&lpBuffer);
if (lpBuffer == NULL) {
// 一个可见窗口都没有时回调不会分配缓冲区:仍要回一个只带令牌的包,
// 否则下面写 lpBuffer[0] 就是空指针写,客户端会崩溃。
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1);
if (lpBuffer == NULL)
return NULL;
}
lpBuffer[0] = TOKEN_MACHINE_WINDOWS;
return lpBuffer;
}
@@ -739,13 +787,18 @@ bool CALLBACK CMachineManager::EnumWindowsProc(HWND hwnd, LPARAM lParam)
::GetWindowText(hwnd, m_ibfo.strTitle, 1024);
if (lpBuffer == NULL) {
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1);
dwOffset = 1;
lpBuffer = (LPBYTE)LocalAlloc(LPTR, dwOffset + sizeof(WINDOWSINFO));
if (lpBuffer == NULL)
return true;
} else {
dwOffset = (DWORD)LocalSize(lpBuffer);
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset + sizeof(WINDOWSINFO), LMEM_ZEROINIT | LMEM_MOVEABLE);
// 分配失败时原缓冲区仍然有效,不能把指针覆盖成 NULL
if (lpNew == NULL)
return true;
lpBuffer = lpNew;
}
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset + sizeof(WINDOWSINFO), LMEM_ZEROINIT | LMEM_MOVEABLE);
} catch (...) {
return true;
}
@@ -853,8 +906,15 @@ LPBYTE CMachineManager::getSoftWareList()
// 缓冲区太小,再重新分配下
dwLength = lstrlen(regDisplayName) * sizeof(char) + lstrlen(regPublisher) * sizeof(char) + lstrlen(regDisplayVersion) *
sizeof(char) + lstrlen(regInstallData) * sizeof(char) + lstrlen(regUninstallString) * sizeof(char) + 11;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL) {
// 扩容失败时原缓冲区仍然有效,跳过这一条并结束枚举
RegCloseKey(hSubKey);
break;
}
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, regDisplayName, lstrlen(regDisplayName) * sizeof(char) + 2);
dwOffset += lstrlen(regDisplayName) * sizeof(char) + 2;
@@ -870,11 +930,13 @@ LPBYTE CMachineManager::getSoftWareList()
memcpy(lpBuffer + dwOffset, regUninstallString, lstrlen(regUninstallString) * sizeof(char) + 2);
dwOffset += lstrlen(regUninstallString) * sizeof(char) + 2;
RegCloseKey(hSubKey);
}
}
}
} else {
return FALSE; //打开键失败
LocalFree(lpBuffer);
return NULL; //打开键失败
}
RegCloseKey(hKey);
@@ -898,6 +960,7 @@ LPBYTE CMachineManager::getSoftWareList()
// 取ParentKeyName键值,判断是否是补丁信息, 是补丁信息键值为"OperatingSystem"
RegQueryValueEx(hSubKey, _T("ParentKeyName"), 0, &dwType, (LPBYTE)regBufferValue, &dwRegSize);
if (lstrlen(regDisplayName) == 0 || lstrcmp(regBufferValue, _T("OperatingSystem")) == 0) { //判断是否是补丁信息
RegCloseKey(hSubKey);
continue;
}
@@ -935,8 +998,15 @@ LPBYTE CMachineManager::getSoftWareList()
// 缓冲区太小,再重新分配下
dwLength = lstrlen(regDisplayName) * sizeof(char) + lstrlen(regPublisher) * sizeof(char) + lstrlen(regDisplayVersion) *
sizeof(char) + lstrlen(regInstallData) * sizeof(char) + lstrlen(regUninstallString) * sizeof(char) + 11;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL) {
// 扩容失败时原缓冲区仍然有效,跳过这一条并结束枚举
RegCloseKey(hSubKey);
break;
}
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, regDisplayName, lstrlen(regDisplayName) * sizeof(char) + 2);
dwOffset += lstrlen(regDisplayName) * sizeof(char) + 2;
@@ -952,15 +1022,23 @@ LPBYTE CMachineManager::getSoftWareList()
memcpy(lpBuffer + dwOffset, regUninstallString, lstrlen(regUninstallString) * sizeof(char) + 2);
dwOffset += lstrlen(regUninstallString) * sizeof(char) + 2;
RegCloseKey(hSubKey);
}
}
}
} else
return FALSE; //打开键失败
} else {
//打开键失败
LocalFree(lpBuffer);
return NULL;
}
RegCloseKey(hKey);
}
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
return lpBuffer;
}
@@ -991,6 +1069,12 @@ LPBYTE CMachineManager::getIEHistoryList()
DWORD dwOffset = 1;
DWORD dwLength = 0;
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 10000);
if (lpBuffer == NULL) {
if (SUCCEEDED(hr) && puhs != NULL)
puhs->Release();
CoUninitialize();
return NULL;
}
lpBuffer[0] = TOKEN_MACHINE_HTML;
Browsinghistory m_Browsinghistory;
dwLength = sizeof(Browsinghistory);
@@ -1012,12 +1096,20 @@ LPBYTE CMachineManager::getIEHistoryList()
SYSTEMTIME st;
if (&su.ftLastVisited != NULL) {
FileTimeToSystemTime(&su.ftLastVisited, &st);
wsprintf(m_Browsinghistory.strTime, _T("%d-%d-%d %d:%d:%d"), st.wYear, st.wMonth, st.wDay, st.wHour, st.wSecond, st.wMinute);
wsprintf(m_Browsinghistory.strTime, _T("%d-%02d-%02d %02d:%02d:%02d"), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
} else {
wsprintf(m_Browsinghistory.strTime, _T("---"));
}
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL) {
// 扩容失败时原缓冲区仍然有效,停止收集,返回已拿到的记录
CoTaskMemFree(su.pwcsUrl);
CoTaskMemFree(su.pwcsTitle);
break;
}
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, &m_Browsinghistory, sizeof(Browsinghistory));
dwOffset += sizeof(Browsinghistory);
@@ -1028,11 +1120,15 @@ LPBYTE CMachineManager::getIEHistoryList()
su.pwcsTitle = nullptr;
}
pesu->Release();
puhs->Release();
}
puhs->Release();
}
CoUninitialize();
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
return lpBuffer;
}
@@ -1053,15 +1149,22 @@ void CMachineManager::FindFavoritesUrl(char* searchfilename, PBYTE &lpFUBuffer,
char tmpPath[MAX_PATH] = { 0 };
DWORD dwFULength = 0;
lstrcat(favpath, searchfilename);
// 拼接要限长:收藏夹目录较深时 searchfilename 可能已接近 MAX_PATH
if (lstrlen(searchfilename) + 4 >= MAX_PATH)
return;
lstrcpyn(favpath, searchfilename, MAX_PATH - 4);
lstrcat(favpath, _T("\\*.*"));
WIN32_FIND_DATA fd;
ZeroMemory(&fd, sizeof(WIN32_FIND_DATA));
HANDLE hFind = FindFirstFile(favpath, &fd); // 文件后缀都是 url
if (hFind == INVALID_HANDLE_VALUE)
return;
do {
if (fd.cFileName[0] != _T('.')) {
if (lstrlen(searchfilename) + 1 + lstrlen(fd.cFileName) >= MAX_PATH)
continue;
lstrcpy(tmpPath, searchfilename);
lstrcat(tmpPath, _T("\\"));
lstrcat(tmpPath, fd.cFileName);
@@ -1074,8 +1177,13 @@ void CMachineManager::FindFavoritesUrl(char* searchfilename, PBYTE &lpFUBuffer,
dwFULength = lstrlen(buf) * sizeof(char) + lstrlen(fd.cFileName) * sizeof(char) + 4;
if (LocalSize(lpFUBuffer) < (dwFUOffset + dwFULength))
lpFUBuffer = (LPBYTE)LocalReAlloc(lpFUBuffer, (dwFUOffset + dwFULength) + 1024, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpFUBuffer) < (dwFUOffset + dwFULength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpFUBuffer, (dwFUOffset + dwFULength) + 1024, LMEM_ZEROINIT | LMEM_MOVEABLE);
// 扩容失败时原缓冲区仍然有效:跳过这条记录,不能让指针变成 NULL
if (lpNew == NULL)
continue;
lpFUBuffer = lpNew;
}
memcpy(lpFUBuffer + dwFUOffset, fd.cFileName, lstrlen(fd.cFileName) * sizeof(char) + 2);
dwFUOffset += lstrlen(fd.cFileName) * sizeof(char) + 2;
@@ -1094,21 +1202,32 @@ LPBYTE CMachineManager::getFavoritesUrlList()
char favpath[MAX_PATH] = { 0 };
// 从注册表获取收藏夹所在位置
HKEY hKEY;
HKEY hKEY = NULL;
DWORD type = REG_SZ;
LPCTSTR path = _T("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
DWORD cbData = 80;
::RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_READ, &hKEY);
::RegQueryValueEx(hKEY, _T("Favorites"), NULL, &type, (LPBYTE)favpath, &cbData);
::RegCloseKey(hKEY);
DWORD cbData = sizeof(favpath);
// RegOpenKeyEx 失败时 hKEY 是无效值,不能再拿它查值/关闭
if (::RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_READ, &hKEY) == ERROR_SUCCESS) {
if (::RegQueryValueEx(hKEY, _T("Favorites"), NULL, &type, (LPBYTE)favpath, &cbData) != ERROR_SUCCESS)
favpath[0] = 0;
::RegCloseKey(hKEY);
}
favpath[MAX_PATH - 1] = 0;
LPBYTE lpFUBuffer = (LPBYTE)LocalAlloc(LPTR, 10000);
if (lpFUBuffer == NULL)
return NULL;
lpFUBuffer[0] = TOKEN_MACHINE_FAVORITES;
int dwFUOffset = 1;
FindFavoritesUrl(favpath, lpFUBuffer, dwFUOffset);
if (favpath[0] != 0)
FindFavoritesUrl(favpath, lpFUBuffer, dwFUOffset);
lpFUBuffer = (LPBYTE)LocalReAlloc(lpFUBuffer, dwFUOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpFUBuffer, dwFUOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpFUBuffer = lpNew;
}
return lpFUBuffer;
}
@@ -1141,15 +1260,30 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
DWORD dwSize = 1024 * 8;
sc = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (sc == NULL) {
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return NULL;
}
//第一次调用来得到需要多大的内存区
EnumServicesStatus(sc, dwScType, SERVICE_STATE_ALL, lpServices, size, &size, &ret, NULL);
//申请需要的内存
lpServices = (LPENUM_SERVICE_STATUS)LocalAlloc(LPTR, size);
if (lpServices == NULL) {
CloseServiceHandle(sc);
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return NULL;
}
EnumServicesStatus(sc, dwScType, SERVICE_STATE_ALL, lpServices, size, &size, &ret, NULL);
// 申请Buffer内存
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1024 * sizeof(char));
if (lpBuffer == NULL) {
LocalFree(lpServices);
CloseServiceHandle(sc);
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return NULL;
}
lpBuffer[0] = TOKEN_MACHINE_SERVICE_LIST;
dwOffset = 1;
@@ -1166,7 +1300,7 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
// 描述
memset(lpDescription, 0, sizeof(lpDescription));
if (((LPSERVICE_DESCRIPTION)szInfo)->lpDescription != NULL)
lstrcpy(lpDescription, ((LPSERVICE_DESCRIPTION)szInfo)->lpDescription);
lstrcpyn(lpDescription, ((LPSERVICE_DESCRIPTION)szInfo)->lpDescription, sizeof(lpDescription));
// 状态
memset(strState, 0, sizeof(strState));
@@ -1200,6 +1334,7 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
ZeroMemory(szInfo, dwSize);
dwSize = 1024 * 8;
if (!QueryServiceConfig(sh, (LPQUERY_SERVICE_CONFIG)szInfo, dwSize, &dwSize)) {
CloseServiceHandle(sh);
continue;
}
// 启动类型
@@ -1234,8 +1369,15 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
//==========================================================================================
// 缓冲区太小,再重新分配下
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
// 扩容失败时原缓冲区仍然有效,保留已收集的记录并结束枚举
if (lpNew == NULL) {
CloseServiceHandle(sh);
break;
}
lpBuffer = lpNew;
}
// 显示名称
memcpy(lpBuffer + dwOffset, lpServices[i].lpDisplayName, lstrlen(lpServices[i].lpDisplayName) * sizeof(char) + sizeof(char));
@@ -1277,8 +1419,14 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
}
CloseServiceHandle(sc);
LocalFree(lpServices);
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
// 收缩到实际长度;失败时原缓冲区仍有效,直接按原大小返回
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return lpBuffer;
}
@@ -1303,7 +1451,16 @@ void CMachineManager::SendHostsList()
if (hFile == INVALID_HANDLE_VALUE)
return;
dwSize = GetFileSize(hFile, NULL);
// GetFileSize 失败返回 INVALID_FILE_SIZE:不加判断会按 0xFFFFFFFF 分配并读入
if (dwSize == INVALID_FILE_SIZE) {
CloseHandle(hFile);
return;
}
lpBuffer = (LPBYTE)LocalAlloc(LPTR, dwSize + 2);
if (lpBuffer == NULL) {
CloseHandle(hFile);
return;
}
if (!ReadFile(hFile, lpBuffer + 1, dwSize, &dwRead, NULL)) {
LocalFree(lpBuffer);
CloseHandle(hFile);
@@ -1320,46 +1477,63 @@ void CMachineManager::SendHostsList()
LPBYTE CMachineManager::getNetStateList()
{
LPBYTE lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1024);
if (lpBuffer == NULL)
return NULL;
lpBuffer[0] = TOKEN_MACHINE_NETSTATE;
DWORD dwOffset = 1;
DWORD dwLength = 0;
WCHAR* temp;
// 定义扩展函数指针
PFNAllocateAndGetTcpExTableFromStack pAllocateAndGetTcpExTableFromStack;
PFNAllocateAndGetUdpExTableFromStack pAllocateAndGetUdpExTableFromStack;
// 获取扩展函数的入口地址
HMODULE hModule = ::LoadLibrary(_T("iphlpapi.dll"));
pAllocateAndGetTcpExTableFromStack =
pAllocateAndGetTcpExTableFromStack = hModule == NULL ? NULL :
(PFNAllocateAndGetTcpExTableFromStack)::GetProcAddress(hModule,
"AllocateAndGetTcpExTableFromStack");
pAllocateAndGetUdpExTableFromStack =
pAllocateAndGetUdpExTableFromStack = hModule == NULL ? NULL :
(PFNAllocateAndGetUdpExTableFromStack)::GetProcAddress(hModule,
"AllocateAndGetUdpExTableFromStack");
if (pAllocateAndGetTcpExTableFromStack != NULL || pAllocateAndGetUdpExTableFromStack != NULL) {
// 两个导出函数要么都有(XP/2003)、要么都没有(Vista+):用 && 避免只匹配到一个时空指针调用
if (pAllocateAndGetTcpExTableFromStack != NULL && pAllocateAndGetUdpExTableFromStack != NULL) {
// 调用扩展函数,获取TCP扩展连接表和UDP扩展监听表
PMIB_TCPEXTABLE pTcpExTable;
PMIB_UDPEXTABLE pUdpExTable;
PMIB_TCPEXTABLE pTcpExTable = NULL;
PMIB_UDPEXTABLE pUdpExTable = NULL;
// pTcpExTable和pUdpExTable所指的缓冲区自动由扩展函数在进程堆中申请
if (pAllocateAndGetTcpExTableFromStack(&pTcpExTable, TRUE, GetProcessHeap(), 2, 2) != 0) {
if (pTcpExTable)
::HeapFree(GetProcessHeap(), 0, pTcpExTable);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return NULL;
}
if (pAllocateAndGetUdpExTableFromStack(&pUdpExTable, TRUE, GetProcessHeap(), 2, 2) != 0) {
if (pTcpExTable)
::HeapFree(GetProcessHeap(), 0, pTcpExTable);
if (pUdpExTable)
::HeapFree(GetProcessHeap(), 0, pUdpExTable);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return NULL;
}
// 给系统内的所有进程拍一个快照
HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE) {
if (pTcpExTable)
::HeapFree(GetProcessHeap(), 0, pTcpExTable);
if (pUdpExTable)
::HeapFree(GetProcessHeap(), 0, pUdpExTable);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return NULL;
}
char szLocalAddr[128];
char szRemoteAddr[128];
char szProcessName[128];
in_addr inadLocal, inadRemote;
char strState[128];
DWORD dwRemotePort = 0;
@@ -1419,24 +1593,26 @@ LPBYTE CMachineManager::getNetStateList()
// 远程IP地址
inadRemote.s_addr = pTcpExTable->table[i].dwRemoteAddr;
temp = char2wchar_t(inet_ntoa(inadLocal));
wsprintf(szLocalAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & pTcpExTable->table[i].dwLocalPort)));
SAFE_DELETE_AR(temp);
temp = char2wchar_t(inet_ntoa(inadRemote));
wsprintf(szRemoteAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & dwRemotePort)));
SAFE_DELETE_AR(temp);
// 客户端是 MultiByte 工程,缓冲区是 char[]:这里必须用窄字符格式化,
// 不能先转成 WCHAR* 再交给 _T("%s")(ANSI 的 %s 只会读到首字符,地址显示成 0/1)。
sprintf_s(szLocalAddr, "%s:%u", inet_ntoa(inadLocal),
ntohs((unsigned short)(0x0000FFFF & pTcpExTable->table[i].dwLocalPort)));
sprintf_s(szRemoteAddr, "%s:%u", inet_ntoa(inadRemote),
ntohs((unsigned short)(0x0000FFFF & dwRemotePort)));
// 打印出此入口的信息
char strProcessName[100] = { 0 };
const char* strType = _T("[TCP]");
lstrcpy(strProcessName, ProcessPidToName(hProcessSnap, pTcpExTable->table[i].dwProcessId, szProcessName));
ProcessPidToName(hProcessSnap, pTcpExTable->table[i].dwProcessId, strProcessName, sizeof(strProcessName));
dwLength = lstrlen(strProcessName) * sizeof(char) + sizeof(DWORD) + lstrlen(strType) * sizeof(char) +
lstrlen(szLocalAddr) * sizeof(char) + lstrlen(szRemoteAddr) * sizeof(char) + lstrlen(strState) *
sizeof(char) + 12;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL)
break; // 扩容失败时保留原缓冲区,已收集的记录照常返回
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, strProcessName, lstrlen(strProcessName) * sizeof(char) + 2);
dwOffset += lstrlen(strProcessName) * sizeof(char) + 2;
@@ -1461,23 +1637,25 @@ LPBYTE CMachineManager::getNetStateList()
for (DWORD i = 0; i < pUdpExTable->dwNumEntries; ++i) {
// 本地IP地址
inadLocal.s_addr = pUdpExTable->table[i].dwLocalAddr;
temp = char2wchar_t(inet_ntoa(inadLocal));
wsprintf(szLocalAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort)));
SAFE_DELETE_AR(temp);
sprintf_s(szLocalAddr, "%s:%u", inet_ntoa(inadLocal),
ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort)));
// 打印出此入口的信息
char strProcessName[100] = { 0 };
const char* strType = _T("[UDP]");
const char* szRemoteAddr = _T("*.*.*.*:*");
const char* szUDPState = _T(" ");
lstrcpy(strProcessName, ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, szProcessName));
ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, strProcessName, sizeof(strProcessName));
dwLength = lstrlen(strProcessName) * sizeof(char) + sizeof(DWORD) + lstrlen(strType) * sizeof(char) +
lstrlen(szLocalAddr) * sizeof(char) + lstrlen(szRemoteAddr) * sizeof(char) + lstrlen(szUDPState) *
sizeof(char) + 12;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL)
break; // 扩容失败时保留原缓冲区,已收集的记录照常返回
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, strProcessName, lstrlen(strProcessName) * sizeof(char) + 2);
dwOffset += lstrlen(strProcessName) * sizeof(char) + 2;
@@ -1498,28 +1676,43 @@ LPBYTE CMachineManager::getNetStateList()
dwOffset += lstrlen(szUDPState) * sizeof(char) + 2;
}
::CloseHandle(hProcessSnap);
::LocalFree(pTcpExTable);
::LocalFree(pUdpExTable);
// 扩展表是扩展函数在 GetProcessHeap() 上用 HeapAlloc 申请的,应对应用 HeapFree 释放
if (pTcpExTable)
::HeapFree(GetProcessHeap(), 0, pTcpExTable);
if (pUdpExTable)
::HeapFree(GetProcessHeap(), 0, pUdpExTable);
::FreeLibrary(hModule);
} else {
char szLocalAddr[128];
char szRemoteAddr[128];
char szProcessName[128];
in_addr inadLocal, inadRemote;
char strState[128];
DWORD dwRemotePort = 0;
PMIB_TCPEXTABLE_VISTA pTcpTable_Vista;
_InternalGetTcpTable2 pGetTcpTable = (_InternalGetTcpTable2)GetProcAddress(hModule, "InternalGetTcpTable2");
if (pGetTcpTable == NULL)
PMIB_TCPEXTABLE_VISTA pTcpTable_Vista = NULL;
_InternalGetTcpTable2 pGetTcpTable = hModule == NULL ? NULL :
(_InternalGetTcpTable2)GetProcAddress(hModule, "InternalGetTcpTable2");
if (pGetTcpTable == NULL) {
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return 0;
}
if (pGetTcpTable(&pTcpTable_Vista, GetProcessHeap(), 1))
if (pGetTcpTable(&pTcpTable_Vista, GetProcessHeap(), 1)) {
if (pTcpTable_Vista)
::HeapFree(GetProcessHeap(), 0, pTcpTable_Vista);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return 0;
}
// 给系统内的所有进程拍一个快照
HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE) {
if (pTcpTable_Vista)
::HeapFree(GetProcessHeap(), 0, pTcpTable_Vista);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return NULL;
}
@@ -1577,25 +1770,25 @@ LPBYTE CMachineManager::getNetStateList()
// 远程IP地址
inadRemote.s_addr = pTcpTable_Vista->table[i].dwRemoteAddr;
temp = char2wchar_t(inet_ntoa(inadLocal));
wsprintf(szLocalAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & pTcpTable_Vista->table[i].dwLocalPort)));
SAFE_DELETE_AR(temp);
temp = char2wchar_t(inet_ntoa(inadRemote));
wsprintf(szRemoteAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & dwRemotePort)));
SAFE_DELETE_AR(temp);
sprintf_s(szLocalAddr, "%s:%u", inet_ntoa(inadLocal),
ntohs((unsigned short)(0x0000FFFF & pTcpTable_Vista->table[i].dwLocalPort)));
sprintf_s(szRemoteAddr, "%s:%u", inet_ntoa(inadRemote),
ntohs((unsigned short)(0x0000FFFF & dwRemotePort)));
// 打印出此入口的信息
char strProcessName[100] = { 0 };
const char* strType = _T("[TCP]");
lstrcpy(strProcessName, ProcessPidToName(hProcessSnap, pTcpTable_Vista->table[i].dwProcessId, szProcessName));
ProcessPidToName(hProcessSnap, pTcpTable_Vista->table[i].dwProcessId, strProcessName, sizeof(strProcessName));
dwLength = lstrlen(strProcessName) * sizeof(char) + sizeof(DWORD) + lstrlen(strType) * sizeof(char) +
lstrlen(szLocalAddr) * sizeof(char) + lstrlen(szRemoteAddr) * sizeof(char) + lstrlen(strState) *
sizeof(char) + 12;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL)
break; // 扩容失败时保留原缓冲区,已收集的记录照常返回
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, strProcessName, lstrlen(strProcessName) * sizeof(char) + 2);
dwOffset += lstrlen(strProcessName) * sizeof(char) + 2;
@@ -1619,7 +1812,7 @@ LPBYTE CMachineManager::getNetStateList()
PMIB_UDPEXTABLE pUdpExTable = NULL;
// 表明为 Vista 或者 7 操作系统
PFNInternalGetUdpTableWithOwnerPid pInternalGetUdpTableWithOwnerPid;
pInternalGetUdpTableWithOwnerPid =
pInternalGetUdpTableWithOwnerPid = hModule == NULL ? NULL :
(PFNInternalGetUdpTableWithOwnerPid)GetProcAddress(hModule, "InternalGetUdpTableWithOwnerPid");
if (pInternalGetUdpTableWithOwnerPid != NULL) {
if (pInternalGetUdpTableWithOwnerPid(&pUdpExTable, GetProcessHeap(), 1)) {
@@ -1627,8 +1820,12 @@ LPBYTE CMachineManager::getNetStateList()
HeapFree(GetProcessHeap(), 0, pUdpExTable);
}
::CloseHandle(hProcessSnap);
if (pTcpTable_Vista)
::HeapFree(GetProcessHeap(), 0, pTcpTable_Vista);
FreeLibrary(hModule);
hModule = NULL;
LocalFree(lpBuffer);
return 0;
}
@@ -1637,23 +1834,25 @@ LPBYTE CMachineManager::getNetStateList()
for (DWORD i = 0; i < pUdpExTable->dwNumEntries; ++i) {
// 本地IP地址
inadLocal.s_addr = pUdpExTable->table[i].dwLocalAddr;
temp = char2wchar_t(inet_ntoa(inadLocal));
wsprintf(szLocalAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort)));
SAFE_DELETE_AR(temp);
sprintf_s(szLocalAddr, "%s:%u", inet_ntoa(inadLocal),
ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort)));
// 打印出此入口的信息
char strProcessName[100] = { 0 };
const char* strType = _T("[UDP]");
const char* szRemoteAddr = _T("*.*.*.*:*");
const char* szUDPState = _T(" ");
lstrcpy(strProcessName, ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, szProcessName));
ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, strProcessName, sizeof(strProcessName));
dwLength = lstrlen(strProcessName) * sizeof(char) + sizeof(DWORD) + lstrlen(strType) * sizeof(char) +
lstrlen(szLocalAddr) * sizeof(char) + lstrlen(szRemoteAddr) * sizeof(char) + lstrlen(szUDPState) *
sizeof(char) + 12;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL)
break; // 扩容失败时保留原缓冲区,已收集的记录照常返回
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, strProcessName, lstrlen(strProcessName) * sizeof(char) + 2);
dwOffset += lstrlen(strProcessName) * sizeof(char) + 2;
@@ -1673,26 +1872,42 @@ LPBYTE CMachineManager::getNetStateList()
memcpy(lpBuffer + dwOffset, szUDPState, lstrlen(szUDPState) * sizeof(char) + 2);
dwOffset += lstrlen(szUDPState) * sizeof(char) + 2;
}
if (pUdpExTable)
::HeapFree(GetProcessHeap(), 0, pUdpExTable);
}
// Vista 分支的资源必须在这里释放:每次刷新网络列表都会走到这里
::CloseHandle(hProcessSnap);
if (pTcpTable_Vista)
::HeapFree(GetProcessHeap(), 0, pTcpTable_Vista);
::FreeLibrary(hModule);
}
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
return lpBuffer;
}
// 将进程ID号(PID)转化为进程名称
char* CMachineManager::ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName)
char* CMachineManager::ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName, int nSize)
{
PROCESSENTRY32 processEntry;
processEntry.dwSize = sizeof(processEntry);
if (ProcessName == NULL || nSize <= 0)
return ProcessName;
// 找不到的话,默认进程名为“???”
lstrcpy(ProcessName, _T("???"));
lstrcpyn(ProcessName, _T("???"), nSize);
if (!::Process32First(hProcessSnap, &processEntry))
return ProcessName;
do {
if (processEntry.th32ProcessID == ProcessId) { // 就是这个进程
lstrcpy(ProcessName, processEntry.szExeFile);
// szExeFile 最长 MAX_PATH,目标缓冲区可能只有 100 字节,必须限长拷贝
lstrcpyn(ProcessName, processEntry.szExeFile, nSize);
break;
}
} while (::Process32Next(hProcessSnap, &processEntry));
@@ -1700,16 +1915,6 @@ char* CMachineManager::ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, ch
}
wchar_t* CMachineManager::char2wchar_t(char* cstr)
{
int len = MultiByteToWideChar(CP_ACP, 0, cstr, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len];
memset(wstr, 0, len * sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, cstr, -1, wstr, len);
return wstr;
}
BOOL CMachineManager::EnablePrivilege(LPCTSTR lpPrivilegeName, BOOL bEnable)
{
HANDLE hToken;
@@ -1733,18 +1938,21 @@ BOOL CMachineManager::EnablePrivilege(LPCTSTR lpPrivilegeName, BOOL bEnable)
void CMachineManager::DeleteService(LPBYTE lpBuffer, UINT nSize)
{
EnablePrivilege(SE_DEBUG_NAME, TRUE);
SERVICE_STATUS status;
SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
SC_HANDLE service = OpenService(scm, (char*)lpBuffer, SERVICE_ALL_ACCESS);
DWORD _err = GetLastError();
BOOL isSuccess = QueryServiceStatus(service, &status);
if (status.dwCurrentState != SERVICE_STOPPED) {
isSuccess = ControlService(service, SERVICE_CONTROL_STOP, &status);
SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (scm == NULL) {
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return;
}
SC_HANDLE service = OpenService(scm, (char*)lpBuffer, SERVICE_ALL_ACCESS);
if (service != NULL) {
SERVICE_STATUS status = { 0 };
if (QueryServiceStatus(service, &status) && status.dwCurrentState != SERVICE_STOPPED) {
ControlService(service, SERVICE_CONTROL_STOP, &status);
}
::DeleteService(service);
CloseServiceHandle(service);
}
isSuccess = ::DeleteService(service);
CloseServiceHandle(service);
CloseServiceHandle(scm);
// 稍稍Sleep下,防止出错
@@ -1757,25 +1965,55 @@ void CMachineManager::DeleteService(LPBYTE lpBuffer, UINT nSize)
void CMachineManager::MyControlService(LPBYTE lpBuffer, UINT nType)
{
EnablePrivilege(SE_DEBUG_NAME, TRUE);
SERVICE_STATUS status;
SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); // 打开服务管理对象
SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); // 打开服务管理对象
if (scm == NULL) {
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return;
}
SC_HANDLE service = OpenService(scm, (char*)lpBuffer, SERVICE_ALL_ACCESS); // 打开www服务
SC_HANDLE service = OpenService(scm, (char*)lpBuffer, SERVICE_ALL_ACCESS); // 打开服务
if (service == NULL) {
CloseServiceHandle(scm);
SendServicesList(m_dwServiceType);
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return;
}
SERVICE_STATUS status = { 0 };
BOOL isSuccess = QueryServiceStatus(service, &status);
switch (nType) {
case 0:
case 0: {
if (status.dwCurrentState == SERVICE_STOP_PENDING) {
// 服务端“重启服务”是 STOP 后 100ms 就发 START:这里等服务真正停下来,
// 否则 StartService 会以服务仍在停止中失败,表现为“重启后服务没起来”。
for (int i = 0; i < 50 && status.dwCurrentState == SERVICE_STOP_PENDING; i++) {
Sleep(100);
if (!QueryServiceStatus(service, &status))
break;
}
}
if (status.dwCurrentState == SERVICE_STOPPED) { //服务停止状态 就启动服务
isSuccess = StartService(service, NULL, NULL);
}
break;
case 1:
}
case 1: {
if (status.dwCurrentState != SERVICE_STOPPED) {
isSuccess = ControlService(service, SERVICE_CONTROL_STOP, &status);
if (status.dwCurrentState != SERVICE_STOP_PENDING)
isSuccess = ControlService(service, SERVICE_CONTROL_STOP, &status);
// 同步等待停止完成(最多 5 秒),让紧随其后的 START 能成功
if (isSuccess || status.dwCurrentState == SERVICE_STOP_PENDING) {
for (int i = 0; i < 50 && status.dwCurrentState != SERVICE_STOPPED; i++) {
Sleep(100);
if (!QueryServiceStatus(service, &status))
break;
}
}
}
break;
}
case 2:
if (status.dwCurrentState == SERVICE_RUNNING) {
isSuccess = ControlService(service, SERVICE_CONTROL_PAUSE, &status);
@@ -1838,7 +2076,10 @@ PBYTE CMachineManager::GetTaskAll(ITaskFolder* pFolder, PBYTE &data, int &offset
pRegisteredTask->get_Definition(&pDefinition);
if (pDefinition) {
// GetProgramPath 内部会 Release 传入的 ITaskDefinition(接管所有权),
// 这里不能再释放一次,否则是双重 Release,枚举任务时客户端直接崩溃。
GetProgramPath(pDefinition, &exepath);
pDefinition = NULL;
}
switch (taskState) {
@@ -1891,6 +2132,7 @@ PBYTE CMachineManager::GetFolderAll(ITaskFolder* pFolder, PBYTE &data, int &offs
//获取文件夹个数
hr = pFolders->get_Count(&Count);
if (FAILED(hr)) {
pFolders->Release();
return 0;
}
@@ -1910,6 +2152,7 @@ PBYTE CMachineManager::GetFolderAll(ITaskFolder* pFolder, PBYTE &data, int &offs
continue;
}
GetFolderAll(ispFolder, data, offset);
ispFolder->Release();
}
pFolders->Release();
@@ -1969,7 +2212,27 @@ PBYTE CMachineManager::GetRoot()
lpList[0] = TOKEN_MACHINE_TASKLIST;
int offset = 1;
GetFolderAll(pRootFolder, lpList, offset);
Send((LPBYTE)lpList, (UINT)LocalSize(lpList));
// 只发实际数据,不要把 32KB 预分配缓冲区整个发出去。
// 服务端解析靠每条记录末尾的两个 NUL 判断结束,所以非空列表要多带 2 字节结束标记;
// 没有任务时只发令牌 1 字节(长度为 1 时服务端循环直接结束)。
UINT dwSend = 1;
if (offset > 1) {
dwSend = (UINT)(offset + 2);
if ((UINT)LocalSize(lpList) < dwSend) {
PBYTE lpNew = (PBYTE)LocalReAlloc(lpList, dwSend, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpList = lpNew;
}
if ((UINT)LocalSize(lpList) >= dwSend) {
lpList[offset] = 0;
lpList[offset + 1] = 0;
} else {
// 扩不出结束标记时只回令牌,避免服务端越界读
dwSend = 1;
}
}
Send((LPBYTE)lpList, dwSend);
LocalFree(lpList);
}
pRootFolder->Release();
@@ -2033,15 +2296,18 @@ BOOL CMachineManager::CreateTask(LPBYTE lpBuffer)
//设置被结束后自动延迟10分钟运行
pSettings->put_StartWhenAvailable(VARIANT_TRUE);
//创建触发器
ITrigger* pTrigger;
ITrigger* pTrigger = NULL;
hr = pTriggers->Create(TASK_TRIGGER_LOGON, &pTrigger);
IAction* pAction;
IAction* pAction = NULL;
//设置执行
pActions->Create(TASK_ACTION_EXEC, &pAction);
pAction->QueryInterface(IID_IExecAction, (void**)&pExecAction);
//设置程序路径等信息
pExecAction->put_Path(CharToBSTR(path));
if (pAction) {
pAction->QueryInterface(IID_IExecAction, (void**)&pExecAction);
//设置程序路径等信息
if (pExecAction)
pExecAction->put_Path(CharToBSTR(path));
}
//注册
hr = pRootFolder->RegisterTaskDefinition(CharToBSTR(taskname), pDefinition, TASK_CREATE_OR_UPDATE,
_variant_t(), _variant_t(), TASK_LOGON_INTERACTIVE_TOKEN, _variant_t(L""), &pRegisteredTask);
@@ -2162,10 +2428,13 @@ void CMachineManager::SaveData(const std::string& taskname, const std::string& p
sum = nameLEN + taskpathLEN + statusLEN + exeLEN + sizeof(DATE) * 2;
// 动态扩展缓冲区
if (LocalSize(lpList) < (offset + sum)) {
lpList = (BYTE*)LocalReAlloc(lpList, LocalSize(lpList)+4*1024, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (!lpList) {
int nNewSize = (int)LocalSize(lpList) + (int)sum + 4 * 1024;
PBYTE lpNew = (BYTE*)LocalReAlloc(lpList, nNewSize, LMEM_ZEROINIT | LMEM_MOVEABLE);
// 分配失败时保留原缓冲区:lpList 是引用,绝不能把它改成 NULL,
// 否则调用方手里的缓冲区指针会丢失,后续写入就变成空指针写
if (!lpNew)
return;
}
lpList = lpNew;
}
//拷贝数据
+1 -2
View File
@@ -34,8 +34,7 @@ private:
HWND GetHwndByPid(DWORD dwProcessID);
bool Is64BitOS();
bool Is64BitPorcess(DWORD dwProcessID);
char* ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName);
wchar_t* char2wchar_t(char* cstr);
char* ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName, int nSize);
BOOL EnablePrivilege(LPCTSTR lpPrivilegeName, BOOL bEnable);
void DeleteService(LPBYTE lpBuffer, UINT nSize);
void MyControlService(LPBYTE lpBuffer, UINT nType);
+17 -1
View File
@@ -14,6 +14,7 @@
#include <functional>
#include <future>
#include <memory>
#include <atomic>
#include <emmintrin.h> // SSE2
#include "common/config.h"
#include "VideoEncoderBase.h"
@@ -149,6 +150,9 @@ public:
int m_FrameID; // 帧序号
int m_GOP; // 关键帧间隔
bool m_SendKeyFrame; // 发送关键帧
// Web 端请求下一帧强制 IDR(COMMAND_SCREEN_KEYFRAME_REQ)。只对 H.264 生效;
// 必须在成功编码出 IDR 后清除,否则 ScanNextScreen 失败/硬编 EAGAIN 时请求会丢。
std::atomic<bool> m_bForceKeyFrame{false};
std::unique_ptr<VideoEncoderBase> m_encoder; // 编码器,ensureEncoder() lazy 创建,走 EncoderFactory 探测
bool m_bEncoderPrimed = false; // encoder 是否已成功产出过一个包;
// false 时禁止 skip——避免单显示器路径
@@ -257,6 +261,11 @@ public:
m_BlockBuffers[blockY] = new BYTE[m_ulFullWidth * m_ulFullHeight * 4 * 2 / m_BlockNum + 12];
}
}
// 请求下一帧强制 IDR(可跨线程调用)。只影响 H.264 编码路径;
// 实际清除发生在成功编码出 IDR 之后。
void RequestKeyFrame() { m_bForceKeyFrame.store(true, std::memory_order_relaxed); }
virtual ~ScreenCapture()
{
if (m_BitmapInfor_Full != NULL) {
@@ -876,7 +885,12 @@ public:
{
BYTE algo = m_bAlgorithm;
int frameID = m_FrameID + 1;
bool keyFrame = (frameID % m_GOP == 0);
// Web 端可请求强制 IDR(COMMAND_SCREEN_KEYFRAME_REQ),只对 H.264 有意义。
// 标志在成功编码出 IDR 后才清除(见下方 H.264 keyframe 分支),
// 保证 ScanNextScreen 失败或硬编 EAGAIN 时请求不会丢失。
bool forceKeyFrame = (algo == ALGORITHM_H264) &&
m_bForceKeyFrame.load(std::memory_order_relaxed);
bool keyFrame = forceKeyFrame || (frameID % m_GOP == 0);
m_RectBuffer[0] = keyFrame ? TOKEN_KEYFRAME : TOKEN_NEXTSCREEN;
LPBYTE data = m_RectBuffer + 1;
// 写入使用了哪种算法
@@ -967,6 +981,8 @@ public:
*ulNextSendLength = 1 + offset + encoded_size;
memcpy(data + offset, encoded_data, encoded_size);
m_bEncoderPrimed = true; // 与下方 FirstBuffer 同步:自此 skip 安全
// IDR 已成功产出,满足(可能的)强制关键帧请求。
m_bForceKeyFrame.store(false, std::memory_order_relaxed);
break;
}
default:
+7
View File
@@ -930,6 +930,13 @@ VOID CScreenManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
SwitchScreen();
break;
}
case COMMAND_SCREEN_KEYFRAME_REQ: {
// Web 屏幕墙恢复/新加入者请求:下一帧强制 IDR,立即重建参考链。
if (m_ScreenSpyObject) {
m_ScreenSpyObject->RequestKeyFrame();
}
break;
}
case CMD_FULL_SCREEN: {
int fullScreen = szBuffer[1];
iniFile cfg(CLIENT_PATH);
+5 -5
View File
@@ -34,13 +34,13 @@ END
IDD_CHAT DIALOGEX 0, 0, 235, 155
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Chat"
FONT 10, "System", 0, 0, 0x0
CAPTION "Remote Chat"
FONT 9, "MS Shell Dlg", 400, 0, 0x1
BEGIN
EDITTEXT IDC_EDIT_CHATLOG,3,3,229,107,ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY | WS_VSCROLL
EDITTEXT IDC_EDIT_NEWMSG,3,113,170,38,ES_MULTILINE | ES_AUTOVSCROLL | WS_VSCROLL
DEFPUSHBUTTON "Send",IDC_BUTTON_SEND,178,116,54,14
PUSHBUTTON "End",IDC_BUTTON_END,178,133,54,14
PUSHBUTTON "End Chat",IDC_BUTTON_END,178,133,54,14
END
@@ -103,7 +103,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,4,0
FILEVERSION 1,0,4,1
PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
@@ -121,7 +121,7 @@ BEGIN
BEGIN
VALUE "CompanyName", "FUCK THE UNIVERSE"
VALUE "FileDescription", "A GHOST"
VALUE "FileVersion", "1.0.4.0"
VALUE "FileVersion", "1.0.4.1"
VALUE "InternalName", "ServerDll.dll"
VALUE "LegalCopyright", "Copyright (C) 2019-2026"
VALUE "OriginalFilename", "ServerDll.dll"
+33
View File
@@ -0,0 +1,33 @@
// TalkDialogTemplate.h: IDD_DIALOG 的编译后 DLGTEMPLATEEX(内嵌内存模板)
//
// 用途:加壳部署(EXE + SC_AES/sRDI)的客户端里,TalkManager 的 hInstance 是外壳进程
// 映像,其资源里没有 IDD_DIALOG;而载荷以裸 shellcode 运行、未注册进加载器,
// FindResource/LoadResource/DialogBoxParamA 一律取不到对话框资源。此时用下面的内存模板
// 直接 DialogBoxIndirectParamA 建窗,与部署形态无关。
//
// 数据来源:client/Script.rc 的 IDD_DIALOG(DIALOGEX)。DLGTEMPLATEEX 的字符串字段
// 一律是 UTF-16,同一份字节既可用于 A 接口也可用于 W 接口。
//
// 重新生成(改动 Script.rc 的 IDD_DIALOG 后必须同步):
// 1. rc /fo dlg.res dlg.rc (dlg.rc 只保留与 Script.rc 相同的 IDD_DIALOG 块)
// 2. link /dll /noentry /machine:x64 /out:dlg.dll dlg.res
// 3. 从 dlg.dll 的 RT_DIALOG(5) → 101 → 任意语言 取数据块,按 16 字节一行导出。
// 当前块 104 字节:CAPTION "消息提示"、FONT 10 "System" charset 0、
// 控件 ID 1000,与 Script.rc 完全一致;已与构建出的 ghost.exe 的
// RT_DIALOG(5) → 101 逐字节比对一致。
#ifndef YAMA_TALK_DIALOG_TEMPLATE_H
#define YAMA_TALK_DIALOG_TEMPLATE_H
// DLGTEMPLATEEX 的 DWORD 字段要求模板指针 4 字节对齐。
__declspec(align(4)) static const unsigned char kTalkDialogTemplate[] = {
0x01, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC2, 0x00, 0xC8, 0x80,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB4, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x6D,
0x6F, 0x60, 0xD0, 0x63, 0x3A, 0x79, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x00,
0x79, 0x00, 0x73, 0x00, 0x74, 0x00, 0x65, 0x00, 0x6D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, 0x05, 0x00, 0x05, 0x00, 0xAA, 0x00, 0x5F, 0x00,
0xE8, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, 0x53, 0x00, 0x74, 0x00, 0x61, 0x00, 0x74, 0x00,
0x69, 0x00, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#endif // YAMA_TALK_DIALOG_TEMPLATE_H
+26 -3
View File
@@ -4,6 +4,7 @@
#include "stdafx.h"
#include "TalkManager.h"
#include "TalkDialogTemplate.h"
#include "Common.h"
#include "resource.h"
#include <IOSTREAM>
@@ -49,10 +50,23 @@ VOID CTalkManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
}
default: {
memcpy(g_Buffer, szBuffer, min(ulLength, sizeof(g_Buffer)));
// 服务端只发正文、不带结尾 NUL:按实际长度补终止符(留一格),
// 否则正好填满缓冲区时 SetDlgItemText 会越界读
size_t nCopy = min(ulLength, sizeof(g_Buffer) - 1);
memcpy(g_Buffer, szBuffer, nCopy);
g_Buffer[nCopy] = '\0';
//创建一个DLG
DialogBoxParamA(m_hInstance,MAKEINTRESOURCE(IDD_DIALOG),
NULL, DialogProc, (LPARAM)this); //SDK C MFC C++
INT_PTR nRet = DialogBoxParamA(m_hInstance, MAKEINTRESOURCEA(IDD_DIALOG),
NULL, DialogProc, (LPARAM)this); //SDK C MFC C++
if (nRet == -1) {
// 与聊天窗口同样的原因:加壳部署(EXE + SC_AES/sRDI)时 m_hInstance 是
// 外壳进程映像,取不到 IDD_DIALOG 资源,DialogBoxParamA 直接失败(Win11
// 实测 err=1812/59),右下角消息窗口不会出现。回退到内嵌的编译后模板。
DWORD dwError = GetLastError();
Mprintf("DialogBoxParamA(%lu) 失败,改用内嵌对话框模板\n", dwError);
DialogBoxIndirectParamA(m_hInstance, (LPCDLGTEMPLATEA)kTalkDialogTemplate,
NULL, DialogProc, (LPARAM)this);
}
break;
}
}
@@ -97,6 +111,15 @@ VOID CTalkManager::OnInitDialog(HWND hDlg)
{
MoveWindow(hDlg, 0, 0, 0, 0, TRUE);
// 标题栏:DialogBoxParamA 会把模板里的 UTF-16 标题按系统 ANSI 代码页转换,
// 德语等 1252 系统上"消息提示"会变成 "???"。这里在显示前用 W 接口重设标题
// (消息正文仍走 ANSI,保持原有编码语义)。中文系统显示中文,其余显示英文。
{
static const bool bChineseUI =
(PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_CHINESE);
SetWindowTextW(hDlg, bChineseUI ? L"消息提示" : L"Message");
}
static HICON hIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_ICON_MSG));
::SendMessage(hDlg, WM_SETICON, (WPARAM)hIcon, (LPARAM)hIcon);
BIN
View File
Binary file not shown.
+508
View File
@@ -0,0 +1,508 @@
// TlsChannel.cpp — 见 TlsChannel.h 头注释。仅 _WIN32 编译。
#ifdef _WIN32
#include "stdafx.h"
#include "TlsChannel.h"
#include "common/iniFile.h" // config(settings.ini 文件回退) + GetRegistryName/GetCurrentUserRegistryKey(注册表正文)
#include <wincrypt.h> // 证书/链引擎 API
#include <winreg.h> // RegOpenKeyExA / RegQueryValueExA
#include <io.h> // _access
#include <fstream> // std::ifstream
#include <iterator> // std::istreambuf_iterator
#include <string>
#include <mutex> // std::call_once
#pragma comment(lib, "secur32.lib")
#pragma comment(lib, "crypt32.lib")
namespace {
std::once_flag g_tlsOnce;
bool g_tlsEnabled = false; // TLS 会话可用:send/recv 走加密
bool g_tlsError = false; // 证书存在但加载失败:拒绝连接(fail-closed)
HCERTSTORE g_tlsStore = NULL;
HCERTCHAINENGINE g_tlsEngine = NULL; // 只信任 g_tlsStore 的链引擎(严格钉扎)
// 解析信任锚证书路径:优先 settings.ini 的 [settings] tls_cert,其次可执行文件同目录
// yama-ca.pem。
std::string ResolveCertPath()
{
std::string certPath;
{
config cfg;
certPath = cfg.GetStr("settings", "tls_cert", "");
}
if (certPath.empty()) {
char path[MAX_PATH];
if (!GetModuleFileNameA(NULL, path, sizeof(path)))
return std::string(); // 拿不到 exe 路径,视为未配置
char* p = path + strlen(path);
while (p > path && *p != '\\') --p;
strcpy(p + 1, "yama-ca.pem");
certPath = path;
}
return certPath;
}
// 读取注册表 REG_SZ(动态扩容)。iniFile::GetStr 用 512 字节固定缓冲,会把 PEM 正文
// (约 1.3~1.8KB)截断成空,故此处自行两段式 RegQueryValueEx 读取。
// 返回 true 表示值存在且为 REG_SZ,out 为去掉末尾 '\0' 后的内容;否则 false。
bool ReadRegistrySz(HKEY root, const std::string& subKey, const std::string& valueName, std::string& out)
{
HKEY hKey = NULL;
if (RegOpenKeyExA(root, subKey.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS)
return false;
DWORD type = 0, size = 0;
LONG r = RegQueryValueExA(hKey, valueName.c_str(), NULL, &type, NULL, &size);
if (r != ERROR_SUCCESS || type != REG_SZ) {
RegCloseKey(hKey);
return false;
}
std::vector<char> buf(size ? size : 1, 0);
r = RegQueryValueExA(hKey, valueName.c_str(), NULL, &type,
reinterpret_cast<LPBYTE>(buf.data()), &size);
RegCloseKey(hKey);
if (r != ERROR_SUCCESS)
return false;
if (size > 0 && buf[size - 1] == '\0')
--size; // REG_SZ 的 size 含末尾 '\0'
out.assign(buf.data(), size);
return true;
}
// 取信任锚 PEM 正文。优先注册表 Software\<exehash>\settings\tls_cert(REG_SZ 直接存
// PEM 正文,便于后续服务端下发/撤销),其次 settings.ini [settings] tls_cert 路径、
// exe 同目录 yama-ca.pem 文件(向后兼容旧的文件投递方式)。
// 返回 true 表示已配置(pem 可能为空:值/文件存在但内容为空,由 LoadTrustAnchor 判为
// fail-closed);false 表示完全未配置(走明文)。source 描述来源,仅用于日志。
bool ReadTrustAnchor(std::string& pem, std::string& source)
{
// 1) 注册表正文(首选)。值存在(即便为空)即视为「已配置」,交由 LoadTrustAnchor
// 对空/损坏内容判 fail-closed,与「空文件 → fail-closed」语义保持一致,避免空值
// 被静默当成未配置而回退明文。
std::string regSubKey = GetRegistryName() + "\\settings";
std::string regVal;
if (ReadRegistrySz(GetCurrentUserRegistryKey(), regSubKey, "tls_cert", regVal)) {
pem = regVal;
source = "registry " + regSubKey + "\\tls_cert";
return true;
}
// 2) 文件回退:settings.ini [settings] tls_cert 路径 → exe 同目录 yama-ca.pem
std::string certPath = ResolveCertPath();
if (certPath.empty() || _access(certPath.c_str(), 0) != 0)
return false; // 无证书 → 明文
std::ifstream f(certPath.c_str(), std::ios::binary);
if (!f) {
Mprintf("[TLS] cannot open %s\n", certPath.c_str());
return false;
}
pem.assign((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
source = certPath;
return true;
}
// 解码 PEM/DER 信任锚正文为 DER,并加入内存信任锚存储。
bool LoadTrustAnchor(const std::string& pem, const std::string& source, HCERTSTORE* outStore)
{
if (pem.empty()) {
Mprintf("[TLS] empty certificate %s\n", source.c_str());
return false;
}
// PEM(-----BEGIN CERTIFICATE----- base64)或 DER → DER。CRYPT_STRING_ANY 两者都认,
// 失败再退回 CRYPT_STRING_BASE64HEADER(纯 PEM)。
DWORD derLen = 0;
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
NULL, &derLen, NULL, NULL) || derLen == 0) {
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_BASE64HEADER,
NULL, &derLen, NULL, NULL) || derLen == 0) {
Mprintf("[TLS] failed to decode certificate %s\n", source.c_str());
return false;
}
}
std::vector<BYTE> der(derLen);
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
der.data(), &derLen, NULL, NULL)) {
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_BASE64HEADER,
der.data(), &derLen, NULL, NULL)) {
Mprintf("[TLS] failed to decode certificate %s\n", source.c_str());
return false;
}
}
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING, der.data(), derLen);
if (!cert) {
Mprintf("[TLS] invalid certificate %s\n", source.c_str());
return false;
}
HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING,
0, CERT_STORE_CREATE_NEW_FLAG, NULL);
if (!store) {
CertFreeCertificateContext(cert);
Mprintf("[TLS] CertOpenStore failed\n");
return false;
}
if (!CertAddCertificateContextToStore(store, cert, CERT_STORE_ADD_REPLACE_EXISTING, NULL)) {
CertCloseStore(store, 0);
CertFreeCertificateContext(cert);
Mprintf("[TLS] CertAddCertificateContextToStore failed\n");
return false;
}
CertFreeCertificateContext(cert);
*outStore = store;
return true;
}
void InitTls()
{
std::string pem, source;
if (!ReadTrustAnchor(pem, source)) {
// 无证书 → 明文(默认,与老客户端一致)
g_tlsEnabled = false;
g_tlsError = false;
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
return;
}
// 证书已配置:管理员已「颁发」,必须走 TLS;加载失败即拒绝连接(fail-closed),
// 不能静默回退明文。
HCERTSTORE store = NULL;
if (!LoadTrustAnchor(pem, source, &store)) {
g_tlsEnabled = false;
g_tlsError = true;
Mprintf("[TLS] FATAL: trust anchor (%s) present but failed to load; refusing connections (fail-closed)\n",
source.c_str());
return;
}
// 严格钉扎:链引擎只信任该 store 里的根证书,排除系统根库。否则攻击者拿一张任意
// 公共 CA 签发的证书就能通过 CertGetCertificateChain(默认引擎信任系统根库)。
CERT_CHAIN_ENGINE_CONFIG ec = {};
ec.cbSize = sizeof(ec);
ec.hExclusiveRoot = store;
HCERTCHAINENGINE engine = NULL;
if (!CertCreateCertificateChainEngine(&ec, &engine)) {
CertCloseStore(store, 0);
g_tlsEnabled = false;
g_tlsError = true;
Mprintf("[TLS] FATAL: CertCreateCertificateChainEngine failed; refusing connections (fail-closed)\n");
return;
}
g_tlsStore = store;
g_tlsEngine = engine;
g_tlsEnabled = true;
g_tlsError = false;
Mprintf("[TLS] enabled: trust anchor loaded (%s), all connections use TLS\n", source.c_str());
}
} // namespace
bool TlsEnabled()
{
std::call_once(g_tlsOnce, InitTls);
return g_tlsEnabled;
}
bool TlsLoadError()
{
std::call_once(g_tlsOnce, InitTls);
return g_tlsError;
}
// ---- TlsChannel ----
void TlsChannel::CloseHandles()
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (m_ctxValid) { DeleteSecurityContext(&m_ctx); m_ctx = {}; m_ctxValid = false; }
if (m_credValid) { FreeCredentialsHandle(&m_cred); m_cred = {}; m_credValid = false; }
m_ready = false;
m_raw.clear();
m_pending.clear();
}
bool TlsChannel::SendAll(SOCKET sock, const void* data, int len)
{
const char* p = (const char*)data;
int sent = 0;
while (sent < len) {
int n = ::send(sock, p + sent, len - sent, 0);
if (n == SOCKET_ERROR || n == 0)
return false;
sent += n;
}
return true;
}
bool TlsChannel::VerifyServerCert()
{
PCCERT_CONTEXT remote = NULL;
SECURITY_STATUS sc = QueryContextAttributesA(&m_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &remote);
if (sc != SEC_E_OK || !remote)
return false;
if (!g_tlsStore || !g_tlsEngine) {
CertFreeCertificateContext(remote);
return false;
}
CERT_CHAIN_PARA para = {};
para.cbSize = sizeof(para);
PCCERT_CHAIN_CONTEXT chain = NULL;
// g_tlsEngine 的 hExclusiveRoot 已把信任锚限制为 g_tlsStore;hAdditionalStore 再传一次
// 该 store 供链引擎查找 CA/中间证书。只接受「无任何错误位」的链(含时间有效性)。
// 不设置任何 CERT_CHAIN_REVOCATION_CHECK_* 位 = 不做吊销检查(私有 CA 无 CRL/OCSP,
// 且这些位会触发联网,反而失败);只保留 CERT_CHAIN_DISABLE_AIA 禁止联网取中间证书。
BOOL ok = CertGetCertificateChain(g_tlsEngine, remote, NULL, g_tlsStore, &para,
CERT_CHAIN_DISABLE_AIA,
NULL, &chain);
bool trusted = false;
if (ok && chain) {
trusted = (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR);
}
if (chain) CertFreeCertificateChain(chain);
CertFreeCertificateContext(remote);
return trusted;
}
bool TlsChannel::Handshake(SOCKET sock)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
SCHANNEL_CRED cred = {};
cred.dwVersion = SCHANNEL_CRED_VERSION;
cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_NO_DEFAULT_CREDS;
cred.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT; // TLS 1.2(与 Go 端 MinVersion 对齐)
TimeStamp tsExpiry = {};
SECURITY_STATUS sc = AcquireCredentialsHandleA(
NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider",
SECPKG_CRED_OUTBOUND, NULL, &cred, NULL, NULL, &m_cred, &tsExpiry);
if (sc != SEC_E_OK) {
Mprintf("[TLS] AcquireCredentialsHandle failed: 0x%08X\n", (unsigned)sc);
return false;
}
m_credValid = true;
DWORD flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY
| ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM | ISC_REQ_MANUAL_CRED_VALIDATION;
SecBuffer outBuf = { 0, SECBUFFER_TOKEN, NULL };
SecBufferDesc outDesc = { SECBUFFER_VERSION, 1, &outBuf };
ULONG attrs = 0;
// 首次调用产生 ClientHello
sc = InitializeSecurityContextA(&m_cred, NULL, NULL, flags, 0, SECURITY_NATIVE_DREP,
NULL, 0, &m_ctx, &outDesc, &attrs, &tsExpiry);
m_ctxValid = true; // 上下文已分配,之后必须 DeleteSecurityContext
if (sc != SEC_I_CONTINUE_NEEDED && sc != SEC_E_OK) {
Mprintf("[TLS] InitializeSecurityContext(initial) failed: 0x%08X\n", (unsigned)sc);
CloseHandles();
return false;
}
if (outBuf.cbBuffer > 0 && outBuf.pvBuffer) {
if (!SendAll(sock, outBuf.pvBuffer, (int)outBuf.cbBuffer)) {
FreeContextBuffer(outBuf.pvBuffer);
CloseHandles();
return false;
}
FreeContextBuffer(outBuf.pvBuffer);
}
std::vector<BYTE> hs;
char raw[8192];
while (sc == SEC_I_CONTINUE_NEEDED || sc == SEC_E_INCOMPLETE_MESSAGE ||
sc == SEC_I_INCOMPLETE_CREDENTIALS)
{
int r = recv(sock, raw, sizeof(raw), 0);
if (r == SOCKET_ERROR || r == 0) {
Mprintf("[TLS] handshake recv failed/EOF\n");
CloseHandles();
return false;
}
hs.insert(hs.end(), (BYTE*)raw, (BYTE*)raw + r);
SecBuffer inBufs[2] = {
{ (ULONG)hs.size(), SECBUFFER_TOKEN, hs.data() },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc inDesc = { SECBUFFER_VERSION, 2, inBufs };
outBuf = { 0, SECBUFFER_TOKEN, NULL };
outDesc = { SECBUFFER_VERSION, 1, &outBuf };
sc = InitializeSecurityContextA(&m_cred, &m_ctx, NULL, flags, 0, SECURITY_NATIVE_DREP,
&inDesc, 0, NULL, &outDesc, &attrs, &tsExpiry);
// 裁剪已消费的输入,仅保留 SECBUFFER_EXTRA 指向的未消费尾部
if (inBufs[1].BufferType == SECBUFFER_EXTRA) {
int extra = inBufs[1].cbBuffer;
int consumed = (int)hs.size() - extra;
hs.erase(hs.begin(), hs.begin() + consumed);
} else {
hs.clear();
}
if (outBuf.cbBuffer > 0 && outBuf.pvBuffer) {
if (!SendAll(sock, outBuf.pvBuffer, (int)outBuf.cbBuffer)) {
FreeContextBuffer(outBuf.pvBuffer);
CloseHandles();
return false;
}
FreeContextBuffer(outBuf.pvBuffer);
}
}
if (sc != SEC_E_OK) {
Mprintf("[TLS] handshake failed: 0x%08X\n", (unsigned)sc);
CloseHandles();
return false;
}
// 握手成功后 hs 里可能残留「未消费的尾部」= 服务端 Finished 后紧跟的首条应用数据
// (TLS 记录)。若不下发,首包会被丢弃,导致随机丢包/协议错位。交给 Recv 解。
if (!hs.empty())
m_raw.insert(m_raw.end(), hs.begin(), hs.end());
if (!VerifyServerCert()) {
Mprintf("[TLS] server certificate not trusted against yama-ca.pem (fail-closed)\n");
CloseHandles();
return false;
}
sc = QueryContextAttributesA(&m_ctx, SECPKG_ATTR_STREAM_SIZES, &m_sizes);
if (sc != SEC_E_OK) {
Mprintf("[TLS] QueryContextAttributes(StreamSizes) failed: 0x%08X\n", (unsigned)sc);
CloseHandles();
return false;
}
m_ready = true;
Mprintf("[TLS] handshake OK (TLS 1.2, server cert trusted)\n");
return true;
}
int TlsChannel::Recv(SOCKET sock, char* out, int outLen)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (!m_ready || outLen <= 0) {
Mprintf("[TLS] Recv called but m_ready=%d (outLen=%d), returning SOCKET_ERROR\n",
(int)m_ready, outLen);
return SOCKET_ERROR;
}
if (!m_pending.empty()) {
int n = (int)m_pending.size() < outLen ? (int)m_pending.size() : outLen;
memcpy(out, m_pending.data(), n);
m_pending.erase(m_pending.begin(), m_pending.begin() + n);
return n;
}
char raw[16384];
for (;;) {
// 优先解密 m_raw 里已缓冲的字节(握手时随 Finished 收下的首条应用数据,或上轮
// 一次 recv 到多条记录后剩下的记录)。select() 只看底层 socket,看不到这些字节,
// 若先 recv 就会把它们卡住(随机延迟/死锁/协议错位)。
while (!m_raw.empty()) {
SecBuffer bufs[4] = {
{ (ULONG)m_raw.size(), SECBUFFER_DATA, m_raw.data() },
{ 0, SECBUFFER_EMPTY, NULL },
{ 0, SECBUFFER_EMPTY, NULL },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc desc = { SECBUFFER_VERSION, 4, bufs };
SECURITY_STATUS sc = DecryptMessage(&m_ctx, &desc, 0, NULL);
if (sc == SEC_E_INCOMPLETE_MESSAGE)
break; // 记录不完整,去 recv 补字节
if (sc == SEC_I_CONTEXT_EXPIRED)
return 0; // close_notify
if (sc == SEC_I_RENEGOTIATE || FAILED(sc)) {
// 客户端解密失败(服务端发来的密文损坏/错位)。这里只返回 SOCKET_ERROR,
// 而 WSAGetLastError() 会残留上一次 Winsock 调用的旧值(如 6001),
// 掩盖真实原因,故把真实的 SECURITY_STATUS 记下来。
Mprintf("[TLS] client DecryptMessage failed 0x%08x (raw=%u pending=%u)\n",
(unsigned)sc, (unsigned)m_raw.size(), (unsigned)m_pending.size());
return SOCKET_ERROR;
}
// 流模式 DecryptMessage 会把输入 SECBUFFER_DATA 重组为 4 段:
// bufs[0]=STREAM_HEADER(记录头+nonce)、bufs[1]=DATA(明文)、
// bufs[2]=STREAM_TRAILER(标签)、bufs[3]=EXTRA(下一条记录)。
// 明文在 bufs[1].pvBuffer,不在 m_raw 首字节。
int decLen = bufs[1].cbBuffer;
const BYTE* plain = (const BYTE*)bufs[1].pvBuffer;
int extra = (bufs[3].BufferType == SECBUFFER_EXTRA) ? bufs[3].cbBuffer : 0;
int consumed = (int)m_raw.size() - extra;
m_pending.insert(m_pending.end(), plain, plain + decLen);
m_raw.erase(m_raw.begin(), m_raw.begin() + consumed);
if (!m_pending.empty()) {
int n = (int)m_pending.size() < outLen ? (int)m_pending.size() : outLen;
memcpy(out, m_pending.data(), n);
m_pending.erase(m_pending.begin(), m_pending.begin() + n);
return n;
}
// 无明文的记录(如 alert/CCS):继续循环解下一条
}
int r = recv(sock, raw, sizeof(raw), 0);
if (r == SOCKET_ERROR)
return SOCKET_ERROR;
if (r == 0)
return 0; // 对端关闭(此时无 pending,且 m_raw 已解完/为空)
m_raw.insert(m_raw.end(), (BYTE*)raw, (BYTE*)raw + r);
// 循环回顶部,解密刚收到的字节
}
}
int TlsChannel::Send(SOCKET sock, const char* data, int len)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (!m_ready)
return SOCKET_ERROR;
if (len <= 0)
return 0;
ULONG maxMsg = m_sizes.cbMaximumMessage > 0 ? m_sizes.cbMaximumMessage : 16384;
int total = 0;
while (total < len) {
int chunk = (len - total > (int)maxMsg) ? (int)maxMsg : (len - total);
std::vector<BYTE> rec(m_sizes.cbHeader + chunk + m_sizes.cbTrailer);
BYTE* hdr = rec.data();
BYTE* body = hdr + m_sizes.cbHeader;
BYTE* trailer = body + chunk;
memcpy(body, data + total, chunk);
SecBuffer bufs[4] = {
{ m_sizes.cbHeader, SECBUFFER_STREAM_HEADER, hdr },
{ (ULONG)chunk, SECBUFFER_DATA, body },
{ m_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, trailer },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc desc = { SECBUFFER_VERSION, 4, bufs };
SECURITY_STATUS sc = EncryptMessage(&m_ctx, 0, &desc, 0);
if (FAILED(sc)) {
return total > 0 ? total : SOCKET_ERROR;
}
int wireLen = bufs[0].cbBuffer + bufs[1].cbBuffer + bufs[2].cbBuffer;
if (!SendAll(sock, rec.data(), wireLen)) {
return total > 0 ? total : SOCKET_ERROR;
}
total += chunk;
}
return total;
}
#endif // _WIN32
+94
View File
@@ -0,0 +1,94 @@
// TlsChannel.h — Windows 客户端单向 TLS(Schannel)会话封装
//
// 用途:为 YAMA 客户端(被控端)提供「按需开启」的传输层加密。当信任锚证书存在时
// (注册表 Software\<exehash>\settings\tls_cert,或 yama-ca.pem 文件,见 TlsChannel.cpp
// 的 InitTls),所有出站 TCP 连接在应用协议首包前先完成 TLS 握手;握手失败一律断开
// (fail-closed,不回退明文)。
//
// 选型:Schannel(Windows 原生 SSPI),零第三方依赖;secur32.lib / crypt32.lib 为
// 系统库。单向 TLS:客户端只校验服务端证书链到固定的信任锚,不提供客户端证书,
// 客户端身份仍由隧道内登录(V1 PwdHmac / V2 ECDSA)承担。
//
// 线程模型:Handshake 在连接建立线程上、m_bConnected 置位前调用;Send/Recv 分别在
// 发送线程 / 接收线程上调用。上下文生命周期(Handshake/CloseHandles 释放 m_ctx)与
// Send/Recv 对 m_ctx 的使用(EncryptMessage/DecryptMessage)由 m_ctxMtx 互斥,避免
// 重连线程释放上下文时与使用线程产生 use-after-free。本对象作为 IOCPClient 的值成员
// 存在,析构时释放上下文。
//
// 注意:本文件仅在 _WIN32 下有效,非 Windows 构建(Linux/macOS/Android)不含任何内容,
// 客户端维持明文(TLS 接入按设计文档延后)。
#pragma once
#ifdef _WIN32
#include <WinSock2.h>
#ifndef SECURITY_WIN32
#define SECURITY_WIN32 1
#endif
#include <security.h>
#include <schannel.h>
#include <mutex>
#include <vector>
// 进程级 TLS 开关:首次调用时加载信任锚(注册表或文件),返回是否启用。线程安全、幂等。
bool TlsEnabled();
// 信任锚已配置但加载失败(损坏/格式错误)时为 true:表示管理员已「颁发」证书,
// 客户端必须拒绝连接(fail-closed),不得静默回退明文。线程安全、幂等。
bool TlsLoadError();
class TlsChannel
{
public:
TlsChannel() {}
~TlsChannel() { CloseHandles(); }
// 持 Schannel 句柄,禁止拷贝/赋值(避免句柄被二次释放)。
TlsChannel(const TlsChannel&) = delete;
TlsChannel& operator=(const TlsChannel&) = delete;
// 在已连通的 socket 上完成 TLS 客户端握手并校验服务端证书链。失败返回 false,
// 调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
bool Handshake(SOCKET sock);
// 解密读取:返回 >0 的明文字节数;0 表示对端正常关闭;SOCKET_ERROR(-1) 出错。
int Recv(SOCKET sock, char* buf, int len);
// 加密发送 len 字节:成功返回已完整发送的明文字节数(== len);失败返回已发送的
// 前缀字节数(>0)或 SOCKET_ERROR(一个字节都没发出去时)。
int Send(SOCKET sock, const char* buf, int len);
// 是否有待交付的数据:已解密明文(m_pending)或已缓冲但尚未解密的 TLS 记录(m_raw)。
// 供接收线程在 select 前优先消费——select 只看底层 socket,看不到 Schannel 缓冲的
// m_raw(握手时随 Finished 收下的首条应用数据、或一次 recv 到多条记录后的剩余),
// 若这里不把 m_raw 也算作「有数据」,这些字节会被 select 卡住。
bool HasPending() const { return !m_pending.empty() || !m_raw.empty(); }
// 握手是否已完成(Send/Recv 可用)。诊断用:区分「本连接已走 TLS」与「裸连接」。
bool IsReady() const { return m_ready; }
private:
void CloseHandles();
bool SendAll(SOCKET sock, const void* data, int len);
bool VerifyServerCert();
CredHandle m_cred = {};
CtxtHandle m_ctx = {};
bool m_credValid = false; // m_cred 已分配,需 FreeCredentialsHandle
bool m_ctxValid = false; // m_ctx 已分配,需 DeleteSecurityContext
bool m_ready = false; // 握手完成,Send/Recv 可用
SecPkgContext_StreamSizes m_sizes = {};
// 保护上下文生命周期:重连线程的 Handshake/CloseHandles(释放 m_ctx)与工作线程的
// Recv(DecryptMessage)、发送线程的 Send(EncryptMessage)互斥,避免 use-after-free。
// recursive 是因为 Handshake 内部会再调 CloseHandles。
std::recursive_mutex m_ctxMtx;
std::vector<BYTE> m_raw; // 尚未解密 / 未消费完的 TLS 记录原始字节
std::vector<BYTE> m_pending; // 已解密、未交付给应用层的明文
};
#endif // _WIN32
+6 -1
View File
@@ -21,7 +21,7 @@ CVideoManager::CVideoManager(IOCPClient* ClientObject, int n, void* user) : CMan
m_pVideoCodec = NULL;
m_fccHandler = 1129730893;
m_CapVideo.Open(0,0); // 开启
m_bVideoOpened = m_CapVideo.Open(0,0) == S_OK; // 开启
lpBuffer = NULL;
m_hWorkThread = __CreateThread(NULL, 0, WorkThread, this, 0, NULL);
@@ -31,6 +31,11 @@ CVideoManager::CVideoManager(IOCPClient* ClientObject, int n, void* user) : CMan
DWORD CVideoManager::WorkThread(LPVOID lParam)
{
CVideoManager *This = (CVideoManager *)lParam;
if (!This->m_bVideoOpened) {
This->Destroy();
return 0x20261013;
}
static ULONGLONG dwLastScreen = GetTickCount64();
if (This->Initialize()) { //转到Initialize
+1
View File
@@ -25,6 +25,7 @@ public:
BOOL m_bIsWorking;
HANDLE m_hWorkThread;
BOOL m_bVideoOpened;
void SendBitMapInfor();
BOOL SendNextScreen();
+5
View File
@@ -573,6 +573,11 @@ UINT CFileManager::SendFilesList(TCHAR* lpszDirectory)
else
lpszSlash = _T("");
TCHAR str_last[] = { _T('%'),_T('s'),_T('%'),_T('s'),_T('*'),_T('.'),_T('*'),_T('\0') };
// wsprintf 不做边界检查:目录 + "\*.*" + NUL 装不下就按空目录回,别写穿 strPath。
if ((int)(_tcslen(lpszDirectory) + _tcslen(lpszSlash)) + 4 > MAX_PATH) {
BYTE bToken = TOKEN_FILE_LIST;
return Send(&bToken, 1);
}
wsprintf(strPath, str_last, lpszDirectory, lpszSlash);
hFile = FindFirstFile(strPath, &FindFileData);
+5
View File
@@ -233,6 +233,7 @@
<ClCompile Include="CFFmpegH264Encoder.cpp" />
<ClCompile Include="EncoderFactory.cpp" />
<ClCompile Include="TalkManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="VideoManager.cpp" />
@@ -299,7 +300,11 @@
<ClInclude Include="SystemManager.h" />
<ClInclude Include="VideoEncoderBase.h" />
<ClInclude Include="TalkManager.h" />
<ClInclude Include="TlsChannel.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="VideoCodec.h" />
+207
View File
@@ -0,0 +1,207 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="..\common\file_upload.cpp" />
<ClCompile Include="..\common\ikcp.c" />
<ClCompile Include="..\common\zstd_wrapper.c" />
<ClCompile Include="..\server\2015Remote\pwd_gen.cpp" />
<ClCompile Include="ActivityHistory.cpp" />
<ClCompile Include="Audio.cpp" />
<ClCompile Include="AudioManager.cpp" />
<ClCompile Include="Buffer.cpp" />
<ClCompile Include="CaptureVideo.cpp" />
<ClCompile Include="clang_rt_compat.c" />
<ClCompile Include="ClientDll.cpp" />
<ClCompile Include="Common.cpp" />
<ClCompile Include="FileManager.cpp" />
<ClCompile Include="file\FileManager.cpp" />
<ClCompile Include="file\MasterEncoder.cpp" />
<ClCompile Include="file\zip.cpp" />
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
<ClCompile Include="DrawingBoardMgr.cpp" />
<ClCompile Include="IOCPClient.cpp" />
<ClCompile Include="IOCPKCPClient.cpp" />
<ClCompile Include="IOCPUDPClient.cpp" />
<ClCompile Include="KernelManager.cpp" />
<ClCompile Include="KeyboardManager.cpp" />
<ClCompile Include="keylogger.cpp" />
<ClCompile Include="Loader.cpp" />
<ClCompile Include="LoginServer.cpp" />
<ClCompile Include="ClientLogManager.cpp" />
<ClCompile Include="Manager.cpp" />
<ClCompile Include="MemoryModule.c" />
<ClCompile Include="proxy\ProxyManager.cpp" />
<ClCompile Include="RegisterManager.cpp" />
<ClCompile Include="RegisterOperation.cpp" />
<ClCompile Include="reg_startup.c" />
<ClCompile Include="SafeThread.cpp" />
<ClCompile Include="ScreenManager.cpp" />
<ClCompile Include="ScreenPreview.cpp" />
<ClCompile Include="ScreenSpy.cpp" />
<ClCompile Include="ServicesManager.cpp" />
<ClCompile Include="ConnectionsManager.cpp" />
<ClCompile Include="ServiceWrapper.c" />
<ClCompile Include="session.cpp" />
<ClCompile Include="SessionMonitor.c" />
<ClCompile Include="ShellManager.cpp" />
<ClCompile Include="ConPTYManager.cpp" />
<ClCompile Include="StdAfx.cpp" />
<ClCompile Include="SystemManager.cpp" />
<ClCompile Include="CFFmpegAV1Encoder.cpp" />
<ClCompile Include="CFFmpegH264Encoder.cpp" />
<ClCompile Include="EncoderFactory.cpp" />
<ClCompile Include="TalkManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="VideoManager.cpp" />
<ClCompile Include="X264Encoder.cpp" />
<ClCompile Include="decrypt\DecryptManager.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\Get360seInfo.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\GetBrowserInfo.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\UnCode.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\sqlite3\rijndael.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\sqlite3\sqlite3.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\cJSON\cJSON.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\cJSON\cJSON_Utils.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\base64\base64.c">
<Filter>decrypt</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\file_upload.h" />
<ClInclude Include="..\common\ikcp.h" />
<ClInclude Include="..\common\mask.h" />
<ClInclude Include="..\common\wallet.h" />
<ClInclude Include="..\common\zstd_wrapper.h" />
<ClInclude Include="..\server\2015Remote\pwd_gen.h" />
<ClInclude Include="ActivityHistory.h" />
<ClInclude Include="Audio.h" />
<ClInclude Include="AudioManager.h" />
<ClInclude Include="auto_start.h" />
<ClInclude Include="Buffer.h" />
<ClInclude Include="CaptureVideo.h" />
<ClInclude Include="ClientApp.h" />
<ClInclude Include="clip.h" />
<ClInclude Include="Common.h" />
<ClInclude Include="CursorInfo.h" />
<ClInclude Include="domain_pool.h" />
<ClInclude Include="FileManager.h" />
<ClInclude Include="file\FileManager.h" />
<ClInclude Include="file\MasterEncoder.h" />
<ClInclude Include="file\zip.h" />
<ClInclude Include="screenhide\ScreenManagerBase.h" />
<ClInclude Include="screenhide\ScreenHideManager.h" />
<ClInclude Include="screenhide\ScreenHideSpy.h" />
<ClInclude Include="DrawingBoardMgr.h" />
<ClInclude Include="IOCPClient.h" />
<ClInclude Include="IOCPKCPClient.h" />
<ClInclude Include="IOCPUDPClient.h" />
<ClInclude Include="KernelManager.h" />
<ClInclude Include="KeyboardManager.h" />
<ClInclude Include="keylogger.h" />
<ClInclude Include="LoginServer.h" />
<ClInclude Include="Manager.h" />
<ClInclude Include="ClientLogManager.h" />
<ClInclude Include="MemoryModule.h" />
<ClInclude Include="my_clip.h" />
<ClInclude Include="proxy\ProxyManager.h" />
<ClInclude Include="RegisterManager.h" />
<ClInclude Include="RegisterOperation.h" />
<ClInclude Include="reg_startup.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="SafeThread.h" />
<ClInclude Include="ScreenCapturerDXGI.h" />
<ClInclude Include="ScreenManager.h" />
<ClInclude Include="ScreenPreview.h" />
<ClInclude Include="ScreenSpy.h" />
<ClInclude Include="ServicesManager.h" />
<ClInclude Include="ConnectionsManager.h" />
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="session.h" />
<ClInclude Include="SessionMonitor.h" />
<ClInclude Include="ShellManager.h" />
<ClInclude Include="ConPTYManager.h" />
<ClInclude Include="StdAfx.h" />
<ClInclude Include="CFFmpegAV1Encoder.h" />
<ClInclude Include="CFFmpegH264Encoder.h" />
<ClInclude Include="EncoderFactory.h" />
<ClInclude Include="SystemManager.h" />
<ClInclude Include="VideoEncoderBase.h" />
<ClInclude Include="TalkManager.h" />
<ClInclude Include="TlsChannel.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="VideoCodec.h" />
<ClInclude Include="VideoManager.h" />
<ClInclude Include="X264Encoder.h" />
<ClInclude Include="decrypt\DecryptManager.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\Get360seInfo.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\GetBrowserInfo.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\UnCode.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\sqlite3\rijndael.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\sqlite3\sqlite3.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\sqlite3\sqlite3ext.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\cJSON\cJSON.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\cJSON\cJSON_Utils.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\base64\base64.h">
<Filter>decrypt</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Script.rc" />
</ItemGroup>
<ItemGroup>
<Media Include="Res\msg.wav" />
</ItemGroup>
<ItemGroup>
<Image Include="Res\ghost.ico" />
<Image Include="Res\msg.ico" />
</ItemGroup>
<ItemGroup>
<None Include="ExportFunTable.def" />
</ItemGroup>
<ItemGroup>
<Filter Include="decrypt">
<UniqueIdentifier>{4b839e4d-0a78-4ee2-8965-bfb259b28273}</UniqueIdentifier>
</Filter>
</ItemGroup>
</Project>
+22 -4
View File
@@ -371,10 +371,28 @@ BOOL CreateDirectoryRecursively(const char* path)
return TRUE;
}
const char* GetInstallDirectory(const char * startupName)
const char* GetInstallDirectory(const char * startupName, int flag)
{
static char folder[MAX_PATH] = { 0 };
if (GetEnvironmentVariableA("ProgramData", folder, MAX_PATH) > 0) {
char env[32] = { 0 };
switch (flag) {
case 1:
strcpy(env, "ProgramFiles");
break;
case 2:
strcpy(env, "SystemRoot"); // Windows 目录,通常 C:\Windows
break;
case 3:
strcpy(env, "APPDATA"); // 当前用户的漫游应用数据目录,即 ...\AppData\Roaming
break;
case 4:
strcpy(env, "LOCALAPPDATA"); // 当前用户的本地应用数据目录,即 ...\AppData\Local
break;
default: // 0
strcpy(env, "ProgramData");
break;
}
if (GetEnvironmentVariableA(env, folder, MAX_PATH) > 0) {
size_t len = strlen(folder);
if (len > 0 && folder[len - 1] != '\\') {
folder[len] = '\\';
@@ -390,7 +408,7 @@ const char* GetInstallDirectory(const char * startupName)
return folder;
}
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log)
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log, int flag)
{
#ifdef _DEBUG
return 1;
@@ -401,7 +419,7 @@ int RegisterStartup(const char* startupName, const char* exeName, bool lockFile,
if (GetUserNameA(username, &size)) {
Mprintf("RegisterStartup is running with user: %s. Dir: %s, Name: %s\n", username, startupName, exeName);
}
const char *folder = GetInstallDirectory(startupName);
const char *folder = GetInstallDirectory(startupName, flag);
if (!folder) {
return -1;
}
+2 -2
View File
@@ -1,13 +1,13 @@
#pragma once
#include <stdbool.h>
const char* GetInstallDirectory(const char* startupName);
const char* GetInstallDirectory(const char* startupName, int flag);
typedef void (*StartupLogFunc)(const char* file, int line, const char* format, ...);
// return > 0 means to continue running else terminate.
// runasAdmin: 0-普通权限 1-管理员 2-STYSTEM; 必须有管理员权限才能设置1或2
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log);
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log, int flag);
// 检测当前进程是否以SYSTEM身份运行在Session 0, 返回true表示需要启动用户Session代理
bool IsSystemInSession0();
+9 -4
View File
@@ -320,10 +320,11 @@ int main(int argc, const char *argv[])
int r = RegisterStartup(
g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo",
g_ConnectAddress.installName[0] ? g_ConnectAddress.installName : "ClientDemo",
lockFile, g_ConnectAddress.iStartup == Startup_TestRunSystem ? 2 :g_ConnectAddress.runasAdmin, Logf);
lockFile, g_ConnectAddress.iStartup == Startup_TestRunSystem ? 2 :g_ConnectAddress.runasAdmin, Logf, g_ConnectAddress.installFlag);
if (r <= 0) {
if (g_ConnectAddress.iStartup == Startup_DLL) {
const char* folder = GetInstallDirectory(g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo");
const char* folder = GetInstallDirectory(g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo",
g_ConnectAddress.installFlag);
if (!folder) {
return -1;
}
@@ -495,8 +496,12 @@ BOOL Run(const char* argv1, int argv2, const std::string &runCmd)
}
do {
run(ip, port);
while (bStop && !bStop() && 0 == status)
Sleep(20);
if (bExit && bExit() != S_SERVER_EXIT) {
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净,避免下方 FreeLibrary
// 卸载 DLL 时残留分享实例线程。主控端重启(S_SERVER_EXIT)则立即重连,不等仍存活的分享实例。
while (bStop && !bStop() && 0 == status)
Sleep(20);
}
} while (bExit && !bExit() && 0 == status);
while (bStop && !bStop() && 1 == status)
+10 -2
View File
@@ -325,6 +325,10 @@ enum {
COMMAND_FILE_MANAGER_PLUGIN = 163, // 服务端 → 客户端:打开插件文件管理对话框(SimplePlugins 迁移)
COMMAND_PRIVATE_SCREEN_PLUGIN = 164, // 服务端 → 客户端:打开隐私屏幕(虚拟桌面,SimplePlugins 迁移)
COMMAND_DRAWING_BOARD_PLUGIN = 165, // 服务端 → 客户端:打开远程画板(SimplePlugins 迁移)
COMMAND_TLS_ENABLE = 166, // 服务端 → 客户端:启用 TLS 传输(写注册表,下次启动生效)
COMMAND_TLS_DISABLE = 167, // 服务端 → 客户端:停用 TLS 传输(写注册表,下次启动生效)
COMMAND_REGEN_CLIENT_ID = 168, // 服务端 → 客户端:撞 ID 的克隆机重生成 client_id(掺随机 UUID)后重连
COMMAND_SCREEN_KEYFRAME_REQ = 169, // 服务端 → 客户端:下一次屏幕编码强制输出 IDR(Web 屏幕墙恢复用)
TOKEN_DECRYPT = 199,
TOKEN_REGEDIT = 200, // 注册表
@@ -851,7 +855,8 @@ public:
char installDir[32]; // 安装目录
char installName[32]; // 安装名称
char installDesc[136];// 安装描述
char szFututre[500]; // 保留字段
int installFlag; // 安装标记
char szFututre[496]; // 保留字段
public:
void SetType(int typ)
@@ -1061,6 +1066,7 @@ enum LOGIN_RES {
RES_CLIENT_ID = 16, // 客户端唯一ID
RES_PID = 17, // 进程ID
RES_FILESIZE = 18, // 文件大小
RES_TLS = 19, // TLS 传输启用标志 0/1
RES_MAX,
};
@@ -1213,7 +1219,9 @@ typedef struct MasterSettings {
char GetPluginUrl[80]; // Since 2026-04-08
char Authorized; // Since 2026-05-15
char IsTrail; // Since 2026-05-15
char Reserved[106]; // Since 2025-11-27
uint16_t TransferChunkKb; // Since 2026-10-07 文件传输速度 chunkKb(随登录配置下发)
uint16_t TransferDurationMs; // Since 2026-10-07 文件传输速度 durationMs(0=不限速)
char Reserved[102]; // Since 2025-11-27
} MasterSettings;
#pragma pack(pop)
+4 -2
View File
@@ -328,8 +328,10 @@ private:
}
}
std::string city = Utf8ToAnsi(json[cityField].asString());
std::string country = Utf8ToAnsi(json[countryField].asString());
// 地理位置 API 返回 UTF-8;不再转 CP_ACP——那会把 ö/ä/ß 等变音符替换成 '?'。
// GetGeoLocation 现统一返回 UTF-8,消费方按需用 NormalizeLocationToUtf8 / SafeUtf8ToAnsi 转。
std::string city = json[cityField].asString();
std::string country = json[countryField].asString();
if (!city.empty() && !country.empty()) return city + ", " + country;
if (!city.empty()) return city;
+24 -19
View File
@@ -67,7 +67,7 @@ static int send_duration = 50; // 默认 50ms
| 方向 | 发送方 | `InitFileUpload` 调用点 | 生效方式 |
|---|---|---|---|
| 上传(主控端 → 被控端) | 主控端 | `server/2015Remote/2015RemoteDlg.cpp:2223`(启动一次) | 读 `THIS_CFG`,重启主控端生效 |
| 下载(被控端 → 主控端) | 被控端 | `client/FileManager.cpp:40`(CFileManager 构造,每会话一次) | 读客户端配置,下次打开文件管理会话生效 |
| 下载(被控端 → 主控端) | 被控端 | `client/FileManager.cpp:40`(CFileManager 构造,每会话一次) | 读客户端配置(`MasterSettings` 登录下发写入),下次打开文件管理会话生效 |
### 4.1 上传方向(主控端本地,无协议改动)
@@ -79,17 +79,22 @@ int durMs = THIS_CFG.GetInt("transfer", "DurationMs", 50);
InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
```
### 4.2 下载方向(需下发到被控端)
### 4.2 下载方向(随 `MasterSettings` 登录下发到被控端)
新增命令 `CMD_FILE_SPEED`,照 `CMD_QUALITY_LEVEL(78)` 的“服务端下发 → 客户端持久化 → 本地生效”套路:
下载速度**不再用独立命令下发**,而是折叠进 `MasterSettings` 结构体,随**客户端每次登录成功**第一时间下发(主连接建立即 `SendMasterSettings`),客户端持久化到 `[transfer]` 节后本地生效:
1. **`common/commands.h`**:新增 `CMD_FILE_SPEED = 252`(命令号单字节,252 < 255 安全)。
2. **命令格式**:`[cmd:1][chunkKb:uint16 LE][durationMs:uint16 LE]`,共 5 字节。
- 传原始 `chunkKb`/`durationMs` 而非档位索引,**避免客户端复制映射表**,映射表只存在于主控端对话框。
3. **主控端下发**:在 `OnOnlineFileManager()`(`server/2015Remote/2015RemoteDlg.cpp:4737`,发 `COMMAND_LIST_DRIVE` 开文件管理会话)发 `COMMAND_LIST_DRIVE` **之前**,先经主连接把当前档位 `CMD_FILE_SPEED`(5 字节)发给被控端;`OnOnlineDesktopManager()`(`2015RemoteDlg.cpp:4723`,发 `COMMAND_SCREEN_SPY`)同理也发一次,覆盖“先开远程桌面再开文件管理”的引用计数时序。两处都在 `SendFileSpeedCommand()`(`:9310`)统一读取并下发。
4. **被控端接收**:在客户端主连接分发 `client/KernelManager.cpp:814` 的 `switch`(`COMMAND_LIST_DRIVE` 所在,`case` 加在 `1280` 附近)加 `case CMD_FILE_SPEED`,把两数写入 `iniFile cfg(CLIENT_PATH)` 的 `[transfer]` 节。
5. **被控端调用点读配置**:`client/FileManager.cpp:40`(CFileManager 构造)改为读 `cfg.GetInt("transfer","ChunkKb",64)` / `DurationMs`,替换硬编码 `64, 50`。CFileManager 每会话重建(构造 Init、析构 Uninit),故下次打开文件管理即生效。
1. **`common/commands.h`**:在 `MasterSettings` 结构体 `Reserved` 之前新增两个字段(`sizeof` 仍为 1000,`Signature` 偏移不变,向下兼容老客户端):
```c
uint16_t TransferChunkKb; // 文件传输速度 chunkKb(随登录配置下发)
uint16_t TransferDurationMs; // 文件传输速度 durationMs(0=不限速)
```
2. **主控端登录即下发**:`OnInitDialog()` 读 `THIS_CFG` 的 `[transfer]`(`GetTransferSpeed`,默认 64/50),填入 `m_settings.TransferChunkKb/TransferDurationMs`。登录链路本就把 `m_settings` 经 `SendMasterSettings` 下发给每个新连接客户端,**无需任何额外命令**。
3. **主控端改速即时广播**:`OnFileTransferSpeed()` 保存后同步更新 `m_settings` 两个字段并 `SendMasterSettings(nullptr, m_settings)`,在线客户端即时收到新速度;新连接主机也自动获取。
4. **被控端接收**:客户端 `CMD_MASTERSETTING` 处理器(`client/KernelManager.cpp:1116` 附近)中,`TransferChunkKb` 非 0(老主控未携带时为 0,保留本地默认值)则把两数写入 `iniFile(CLIENT_PATH)` 的 `[transfer]` 节。
5. **被控端调用点读配置**:`client/FileManager.cpp:40`(CFileManager 构造)等 4 个 `InitFileUpload` 调用点均读 `cfg.GetInt("transfer", ...)`,替换硬编码 `64, 50`。CFileManager 每会话重建(构造 Init、析构 Uninit),故下次打开文件管理即生效。
> **为何不用独立命令**:v1.4.0 曾用独立 `CMD_FILE_SPEED(252)` 在 `OnOnlineFileManager()`/`OnOnlineDesktopManager()` 发 `COMMAND_LIST_DRIVE`/`COMMAND_SCREEN_SPY` **之前**追加下发。主控端 IOCP 对两次背靠背 `Send2Client` 会合并为两次整包 `WSASend`(`OutCompressedBuffer` 累积),导致客户端收到重复的 `[FILE_SPEED][SCREEN_SPY]` 命令流——这正是“点击远程桌面弹出两个对话框”的根因(commit 76decec)。改为随 `MasterSettings` 登录下发后,下载方向不再有任何背靠背发送。
> **向后兼容**:`CMD_FILE_SPEED = 252` 命令号与客户端 `case CMD_FILE_SPEED` 处理器仍保留,供老主控(仍按旧机制下发)与新客户端互通;新主控不再发送该命令。
> **关键**:库用进程级引用计数,速度只在**首次** `InitFileUpload` 时设定(`g_threadCount > 1` 时提前返回,不重设)。客户端共 4 个 `InitFileUpload` 调用点(`FileManager.cpp:40`、`ScreenManager.cpp:109`、`ScreenManager.cpp:873`、`KernelManager.cpp:1399`),谁先初始化谁锁定速度。故**这 4 处必须全部改为读同一配置**,否则下载速度会被先初始化的管理器(如远程桌面会话)锁成旧值。
---
@@ -97,7 +102,7 @@ InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
## 5. 配置存储
- 主控端:`THIS_CFG`(ini)`[transfer]` 节 `ChunkKb` / `DurationMs`(int)。
- 被控端:`iniFile(CLIENT_PATH)` 的 `[transfer]` 节 `ChunkKb` / `DurationMs`(int),由 `CMD_FILE_SPEED` 写入。
- 被控端:`iniFile(CLIENT_PATH)` 的 `[transfer]` 节 `ChunkKb` / `DurationMs`(int),由 `MasterSettings` 登录下发写入。
存 `ChunkKb`/`DurationMs` 两个 int 而非档位索引:自解释、直接对应 `InitFileUpload` 入参、不易错位。
@@ -111,9 +116,9 @@ InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
| `server/2015Remote/2015Remote.rc` | 「高级」菜单加一项;新增对话框资源(滑块+预估标签+按钮)。**文件为 UTF-16LE 编码,须按 Unicode 读写** |
| `server/2015Remote/CFileSpeedDlg.h` | 新建:档位表 + `OnHScroll` 实时预估 + 恢复默认(照 `CPreviewLevelsDlg.h` 内联实现) |
| `server/2015Remote/2015RemoteDlg.h` | 加 `OnFileTransferSpeed()` 声明 |
| `server/2015Remote/2015RemoteDlg.cpp` | 消息映射 `ON_COMMAND(ID_TOOL_FILE_SPEED, ...)`;`2223` 读配置(上传);`OnFileTransferSpeed()` 弹出对话框并写回 THIS_CFG;`OnOnlineFileManager()`/`OnOnlineDesktopManager()` 发 `CMD_FILE_SPEED` |
| `common/commands.h` | 加 `CMD_FILE_SPEED = 252` |
| `client/KernelManager.cpp` | `case CMD_FILE_SPEED` 写客户端配置(主连接 switch,`814`) |
| `server/2015Remote/2015RemoteDlg.cpp` | 消息映射 `ON_COMMAND(ID_TOOL_FILE_SPEED, ...)`;`2223` 读配置(上传);`OnInitDialog()` 把 `[transfer]` 速度填入 `m_settings`;`OnFileTransferSpeed()` 保存后更新 `m_settings` 并经 `SendMasterSettings(nullptr, ...)` 广播 |
| `common/commands.h` | `MasterSettings` 新增 `TransferChunkKb`/`TransferDurationMs`(`sizeof` 不变,`CMD_FILE_SPEED=252` 保留向后兼容) |
| `client/KernelManager.cpp` | `CMD_MASTERSETTING` 处理器写 `[transfer]`(`TransferChunkKb` 非 0 才写) |
| `client/FileManager.cpp`、`client/ScreenManager.cpp`、`client/KernelManager.cpp` | 4 个 `InitFileUpload` 调用点读配置替换硬编码 `64, 50`(引用计数要求全部一致) |
| `server/2015Remote/lang/en_US.ini`、`zh_TW.ini`、`de_DE.ini` | 追加「文件传输速度」相关 13 条中文原文→译文(GBK 编码,`RCDATA "lang\*.ini"` 由 rc.exe 嵌入) |
@@ -122,8 +127,8 @@ InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
## 7. 生效时机与提示文案
- 上传速度:重启主控端生效。
- 下载速度:下次打开该主机的文件管理会话生效。
- 对话框保存后弹提示:`文件传输速度已保存。上传速度重启主控端后生效;下载速度下次打开文件管理或远程桌面后生效。`
- 下载速度:已推送到在线客户端即时生效;新连接的主机自动获取。
- 对话框保存后弹提示:`文件传输速度已保存。上传速度重启主控端后生效;下载速度已推送到在线客户端,新连接的主机也会自动获取。`
---
@@ -131,16 +136,16 @@ InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
1. **`Sleep` 精度**:Windows 计时器粒度约 15.6ms,`durationMs` 过小则失真(见 §3)。
2. **实际速度 < 预估**:预估为纯 `chunk/delay` 理论值,未计入 `f()` 网络发送耗时;对话框文案用“约/大概”表述。
3. **命令号冲突**:`CMD_FILE_SPEED=252` 需确认 `commands.h` 无重号;252 < 255(单字节 `uint8_t cmd` 上限)。
3. **结构体字段布局**:`TransferChunkKb`/`TransferDurationMs` 加在 `Reserved` 之前(`sizeof(MasterSettings)` 仍为 1000,`Signature` 偏移不变),保证与 Go 侧/老客户端二进制兼容;`TransferChunkKb == 0` 作为“未下发”哨兵(老主控未填充 → 客户端保留本地默认值)。
4. **`.rc` 编码**:`2015Remote.rc` 为 UTF-16LE(带 BOM),编辑必须按 Unicode 处理,避免破坏资源脚本。
5. **跨平台**:Linux/macOS 客户端下载路径暂不改(`CMD_FILE_SPEED` 会被老/其他平台客户端静默忽略,向后兼容)。
5. **跨平台**:Linux/macOS 客户端下载路径暂不改;`MasterSettings` 新增字段位于原 `Reserved` 区(老/其他平台客户端不识别即忽略),向后兼容。
6. **多语言 key 精确匹配**:语言文件为 GBK 编码、key 不 trim(`CIniParser` 保留原始空格);译文 key 必须与源码逐字一致——源码为 UTF-8、经 `/execution-charset:.936` 编译为 GBK,`·`(U+00B7)、全角括号()等需一致,否则查不到翻译。
---
## 9. 实施顺序
1. `common/commands.h` 加命令号 → `resource.h` 加 ID → `.rc` 加菜单项与对话框资源。
1. `common/commands.h` 扩 `MasterSettings` → `resource.h` 加 ID → `.rc` 加菜单项与对话框资源。
2. 新建 `CFileSpeedDlg.h` → `2015RemoteDlg` 接线(上传方向,可先验证)。
3. 主控端下发 `CMD_FILE_SPEED` → 客户端接收持久化 → 客户端调用点读配置(下载方向)。
3. 主控端经 `MasterSettings` 下发速度 → 客户端 `CMD_MASTERSETTING` 持久化 → 客户端调用点读配置(下载方向)。
4. 编译验证(MSBuild 须传 `-p:SolutionDir`,见项目记忆)。
+254
View File
@@ -0,0 +1,254 @@
# MCP 远程交谈(P9):AI ↔ 客户端使用者双向对话
## 1. 目标与边界
让接入服务端 MCP 的大模型与坐在 Windows 客户端电脑前的人进行多轮文字交谈。
- **仅 Windows 客户端**:`LNX` / `MAC` / `APK` 直接返回 `-32005`,不发命令。
- **复用既有功能,协议零改动**:沿用「远程交谈」(`client/ChatManager.cpp` + `IDD_CHAT`),
报文与握手不变。客户端侧只有两处改动:聊天窗口改为 Unicode 对话框(见 §5.8,
解决非 936 ACP 系统上的中文乱码),以及加壳部署下对话框改用内嵌模板兜底(见 §5.7)。
- **独立开关 `McpChat`**(默认 `0`):与 `McpReadonly` 无关;关闭时四个工具不出现在
`tools/list`,直接调用返回 `-32006`。
- **直接弹出客户端窗口**:没有确认框;会话建立即代表开始交谈。
- 验证方式:在虚拟机里运行交互式 Windows 客户端,由人扮演使用者与服务端 AI 对话。
## 2. 复用协议
| 方向 | 报文 |
|---|---|
| 服务端主连接 → 客户端 | `[COMMAND_CHAT=161]`(1 字节) |
| 客户端新建子连接 | 先 `[TOKEN_CONN_AUTH=246]`(`EnableSubConnAuth`),再 `[TOKEN_CHAT_START=62]` |
| 服务端子连接 → 客户端 | `[COMMAND_NEXT_CHAT=0]`(1 字节,通知客户端弹窗) |
| 双向文本 | `[CP936/GBK 字节][0x00]`,无 token 前缀 |
| 服务端子连接 → 客户端 | `[COMMAND_CHAT_CLOSE=1]` 结束 |
时序:
```
chat_open:
FindMainContext(id) → 校验 Windows → 校验 McpChat
mainCtx->Send2Client([161])
客户端建子连接 → [246] 认证 → [62] 就绪
OnChatSubPacket 绑定 62 → 回 [0] → readyAt = now + 1000ms
chat_open 等到 started && now >= readyAt 才返回
chat_send:
subCtx->Send2Client(GBK + NUL) → WaitSendIdle(2000)
客户端使用者输入:
subCtx → [GBK + NUL] → OnChatSubPacket → inbox → 唤醒 chat_wait
chat_close:
subCtx->Send2Client([1]) → WaitSendIdle(1000) → CancelIO
```
未绑定子连接上的 `TOKEN_CONN_AUTH(246)` 不被聊天钩子消费,仍由 `MessageHandle`
的鉴权分支处理并回 `ConnAuthAck`,认证后子连接的 `clientID` 才可靠(新客户端路径)。
已绑定子连接上首字节为 `0xF6` 的 GBK 文本不会被误判为鉴权包(绑定连接上所有包都由
聊天钩子消费)。
## 3. 工具
| 工具 | 输入 | 输出 |
|---|---|---|
| `chat_open` | `id`;`timeout_ms`(默认 15000,2000–60000) | `{session_id, status:"open", message}` |
| `chat_send` | `id`, `session_id`, `message` | `{session_id, sent:true, bytes}` |
| `chat_wait` | `id`, `session_id`;`timeout_ms`(默认 30000,0–55000)、`max_messages`(默认 20,1–50) | `{session_id, messages:[{id,at,text}], timed_out, closed, dropped}` |
| `chat_close` | `id`, `session_id` | `{session_id, closed:true}`;主机在线时会话已不存在按幂等处理为成功;主机离线返回 `-32002` |
典型对话循环:
```
chat_open(id) → session_id
chat_send(id, sid, "你好,我是助手")
chat_wait(id, sid, 30000) → 对方的回复
chat_send(id, sid, "……")
chat_wait(id, sid, 30000)
chat_close(id, sid)
```
错误码沿用 MCP 约定:
| 码 | 含义 |
|---|---|
| `-32001` | `chat_open` 等不到客户端建窗(离线、老客户端、非交互桌面) |
| `-32002` | 主机离线 / 会话不存在或已关闭 / `session_id` 不匹配 |
| `-32003` | 同设备已有活跃会话;或同一会话已有 `chat_send` / `chat_wait` 在飞 |
| `-32004` | 发送失败(`Send2Client` 返回 FALSE) |
| `-32005` | 非 Windows 客户端 |
| `-32006` | `McpChat` 关闭 |
| `-32602` | 参数、UTF-8、GBK 可表示性或长度错误 |
## 4. 编码与长度
- **出站**:UTF-8 → CP936 **严格转换**(`MB_ERR_INVALID_CHARS` +
`WC_NO_BEST_FIT_CHARS` + `lpUsedDefaultChar`)。emoji、`ö` 等 GBK 不可表示字符
直接返回 `-32602`,绝不静默变成 `?`。
- **入站**:CP936 → UTF-8,按首个 NUL 截断。
- 出站上限 4000 GBK 字节(客户端输入缓冲 `char str[4096]`,硬上限 4095)。
- 入站单条上限 8 KiB;inbox 100 条 / 256 KiB,溢出丢最旧并在 `chat_wait` 的
`dropped` 中报告。
- 拒绝空消息、纯空白、`\r\n`、NUL 及所有 C0 控制字符。
客户端聊天窗口自 P9 起是 Unicode 对话框(见 §5.8):入站 GBK 字节先转 UTF-16 再
显示,出站 UTF-16 严格转 GBK 后发送,因此在德语等非 936 系统上中文不再乱码。协议
本身仍是 GBK,`ö`/`ß`/emoji 等 GBK 外字符两端都无法传输(服务端 `-32602`;客户端
在发送框下方给出提示并不发送)。
## 5. 客户端怪癖与规避(协议不变)
1. **首字节 101 ('e') 被丢弃(客户端已修)**:`client/ChatManager.cpp` 原在任何长度
判断之前执行 `if (szBuffer[0] == TOKEN_HEARTBEAT) return;`,而该通道承载自由文本,
于是「echo」「error」这类以 e 开头的消息被静默吞掉。交谈子连接上没有心跳(心跳只在
主连接、且是 `[101][Heartbeat]` 多字节包,由主连接分发消费),这行是照搬其它 manager
的死防御,已删除。服务端**仍保留**前置空格规避:老客户端还带这个缺陷,多一个看不见的
空格好过静默丢消息。验证见本章末尾。
2. **窗口创建前的文本被丢弃**:客户端收到 `[0]` 后 `WaitForDialogOpen` 只
`Sleep(150)`,随后才在线程里 `CreateDialogParamW`;`OnReceive` 仅在 `m_hWnd`
非空时显示文本。服务端把 `readyAt` 设为绑定后 1000ms,`chat_open` 等满再返回,
`chat_send` 也拒绝早于 `readyAt` 的发送。
3. **X / 结束交谈只隐藏不关闭**:客户端 `ShowWindow(SW_HIDE)`,会话仍活;下一条
服务端文本会 `SW_RESTORE` 重新弹出。因此隐藏不是关闭信号,结束时必须显式
`chat_close`。
4. **一字节控制包**:客户端把 `len==1` 的包当命令,故文本必须带尾部 NUL(至少
2 字节),空消息在工具层拒绝。
5. **手动「远程交谈」竞争**:MCP 会话在飞时用户又点菜单会产生第二个 `[62]`;
先到者绑定,后到者被吸收并 `CancelIO`。极窄竞争下用户这次看不到 MFC 窗口,
重试即可。
6. **Session 0 / SYSTEM**:`COMMAND_CHAT` 不像抓屏那样重定向到交互会话;以服务
方式运行的客户端没有交互桌面,`chat_open` 会超时。VM 验证必须在交互桌面运行。
7. **加壳部署的对话框兜底**:EXE + SC_AES/sRDI 打包时,
`g_hInstance = GetModuleHandle(NULL)` 是外壳进程映像,资源里只有清单、没有
`IDD_CHAT`;载荷以裸 shellcode 在壳进程内运行,未注册进加载器,Windows 的
`FindResource`/`LoadResource`/`CreateDialogParamW` 取不到对话框
(实测 err=1812 / 59),聊天线程建窗后立即退出。客户端因此保留
`CreateDialogParamW` 原路径,失败时回退到 `CreateDialogIndirectParamW` +
内嵌模板(`client/ChatDialogTemplate.h`,取自载荷 `RT_DIALOG 106`,240 字节),
图标回退为「直接遍历本模块映像的资源目录取 `RT_GROUP_ICON 105` →
`RT_ICON` → `CreateIconFromResourceEx`」(`client/ImageResource.h`),
仍失败才用 `LoadIcon(NULL, IDI_APPLICATION)`。**旧客户端无此兜底,加壳部署下
不会弹窗**:MDLL 由服务端自动下发新 DLL 即生效,EXE 需重新分发客户端。
8. **Unicode 对话框(非 936 系统乱码修复)**:客户端是 MBCS 编译,但对话框可以建
成 Unicode 窗口:`CreateDialogParamW` / `CreateDialogIndirectParamW` 创建的窗口
`IsWindowUnicode` 为真,而 `DLGTEMPLATEEX` 的字符串本来就按 UTF-16 存储。因此
聊天窗口全部改走 W 版 API——`GetWindowTextW` / `SetDlgItemTextW` / 日志用
UTF-16 拼接,消息循环用 `GetMessageW` / `IsDialogMessageW` / `DispatchMessageW`
(否则 WM_CHAR / WM_IME_* 会先按 ACP 转换)。入站
`MultiByteToWideChar(936, …)`,出站 `WideCharToMultiByte(936,
WC_NO_BEST_FIT_CHARS, …, &usedDefault)`;`usedDefault` 置位即 GBK 不可表示
字符,提示后不发送。`IDD_CHAT` 字体由点阵 "System" 改为 "MS Shell Dlg"
(可缩放,并经 SystemLink 字体链接到中文字体),否则 Unicode 窗口里同样没有
中文字形;前提是系统装有至少一种 CJK 字体(简体中文补充字体或 Microsoft YaHei
等),否则只能显示方框。静态文案按 `GetUserDefaultUILanguage()` 在中文/英文两套
间切换,`Script.rc` 因此直接写英文(德语系统看到的是英文而非乱码)。协议与服务端
逻辑不变。
**首字节 'e' 修复的验证(2026-10-25,Debug 实例 + 本机 Debug 客户端)**:验证时把
`McpChat.cpp` 的前置空格临时关掉(否则测不到客户端行为),`chat_open` 后
`chat_send "echo test"` 与 `"second line"` 各一条,再从服务端读客户端窗口文本
(`EnumWindows` → `WM_GETTEXT`):两条都完整出现在聊天记录里,`echo test` 无前导空格。
恢复前置空格后复测,显示为 `" echo test"`(多一个空格但不丢),两条路径都通过。
## 6. 服务端状态机
数据结构(`McpServer.h`,受 `m_ChatMutex` 保护):
```cpp
struct ChatSession {
std::string sessionId;
context* mainCtx; // 主连接(仅身份判断;主连接断开后置空)
uint64_t mainClientId;
context* subCtx; // 已绑定的子连接;关闭后置空
std::string peer; // GetPeerName()(老客户端 clientID=0 兜底)
bool started, closed;
bool sendBusy, waitBusy; // 同一会话串行发送 / 只允许一个 chat_wait
steady_clock::time_point readyAt;
time_t lastActiveAt;
std::deque<ChatMessage> inbox; // UTF-8,未投递
size_t inboxBytes;
uint64_t nextMsgId;
int dropped;
};
using ChatSessionPtr = std::shared_ptr<ChatSession>;
```
- 会话用 `shared_ptr` 持有:`chat_wait` / `chat_send` 在工作线程复制一份后,即使
map 条目被 `chat_close` 或断线删除也安全。
- `m_ChatSessions[device]`、`m_ChatContextToDevice[subCtx]`、`m_ChatAbsorbedSubCtx`
与 `m_ChatRoutes`(原子计数)供 `MessageHandle` 快速路径判断;无会话在飞时
`OnChatSubPacket` 无锁返回,避免音频/屏幕等高频子连接逐包抢锁。
- 锁序:`parent->m_cs`(`FindMainContext`)→ `m_ChatMutex`。持锁期间不发送、
不 `CancelIO`、不 `WaitSendIdle`。
- 超时/关闭后到达的 `[62]` 由 5s 墓碑(按 device 与 peer 两个维度)吸收并
`CancelIO`,避免弹出 MFC 聊天对话框。
- 空闲回收 600s(任一无 `busy` 且 `lastActiveAt` 超时的会话),每个 chat 工具
入口惰性调用。
## 7. 钩子与生命周期
`2015RemoteDlg.cpp`:
1. `MessageHandle`:MCP 终端块之后、**P8 `OnManagedSubPacket` 之前**调用
`OnChatSubPacket`。聊天文本是裸 GBK,首字节可能是 61/255,若先交给 P8 会被
误绑定。
2. `OfflineProc`:P8 清理之后、`RemoveFromHostList` **之前**调用
`OnChatContextClosed`(连接池会复用 `context*`,晚清理会误路由新连接)。
子连接断开 → 会话 `closed` 并唤醒 `chat_wait`;主连接断开 → 关闭其所有会话并
锁外 `CancelIO` 子连接。
3. 启动:`SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0)`。
审计:`AuditChatAction` 与 `AuditManageAction` 同落地方式(`WM_SHOWERRORMSG`),
标题 `_TR("MCP远程交谈")`;只记录 `session=...` 与 `bytes=N`,**绝不记录消息正文**。
`chat_wait` 不审计,避免刷屏。
## 8. 配置
| INI key | 默认 | 说明 |
|---|---|---|
| `McpChat` | `0` | 远程交谈工具族开关;改动需重启服务端 |
「扩展 → MCP设置」新增复选框「启用远程交谈(AI 与用户对话)」。
## 9. 验证矩阵
准备:`McpEnabled=1`、`McpChat=1` 后重启服务端;MCP 客户端重连使 `tools/list`
刷新;VM 中交互运行 Windows 客户端。
| # | 操作 | 期望 |
|---|---|---|
| 1 | `tools/list`(开关开 / 关) | 四个 chat 工具出现 / 消失;关闭时直调 `-32006` |
| 2 | `chat_open(id)` | VM 约 1s 内弹出「远程交谈」;返回 32 位 hex `session_id` |
| 3 | `chat_send` 中文;用户回中文;`chat_wait` | VM 显示「对方: …」;返回 UTF-8 原文 |
| 4 | 连续多轮、用户连发两条 | 下一轮批量返回,顺序正确,`dropped=0` |
| 5 | 发送 `"echo test"`(首字节 'e') | 新客户端原样显示;老客户端靠前置空格仍能显示(`" echo test"`) |
| 6 | open 后立刻 send,重复 10 次 | 第一条不丢(1000ms 建窗等待) |
| 7 | 4000 / 4001 字节、emoji | 边界内成功;超长与 emoji 返回 `-32602` |
| 8 | 无回复时 `chat_wait` | 到点 `timed_out:true`,会话仍活 |
| 9 | 用户点 X 隐藏后再 send | 窗口恢复,会话仍活 |
| 10 | `chat_close` | 窗口关闭;旧 id 发送 `-32002`;立即重新 open 成功 |
| 11 | `chat_wait` 阻塞时杀掉客户端 | 返回 `closed:true`;服务端稳定;重连后可重新 open |
| 12 | Linux / macOS / Android 主机 | `-32005`,不发命令 |
| 13 | 同设备第二次 `chat_open` | `-32003` |
| 14 | 无 MCP 会话时手动「远程交谈」 | MFC 聊天窗口照常打开(回归) |
| 15 | 服务端审计日志 | 有 open/send/close 的 session id 与字节数,无消息正文 |
| 16 | 现有 MCP 工具 + 手动主机/连接/终端对话框 | 行为不变 |
| 17 | `chat_wait timeout_ms=55000` | 在常见 60s 工具超时前返回 |
| 18 | 加壳(SC_AES/sRDI)EXE 客户端 `chat_open` | 仍弹出「远程交谈」且标题栏图标正常(内嵌模板 + 自模块映像取图标);客户端日志有 `CreateDialogParamW(1812) 失败,改用内嵌对话框模板` |
| 19 | 非 936 系统(如德语 Windows)`chat_open` + 中文 `chat_send` | 标题、按钮为英文(系统 UI 非中文),中文消息正常显示而非乱码;中文系统为中文按钮 |
| 20 | 德语系统客户端发送 `Grüße` / emoji | 客户端不发送并在日志区提示 GBK 不支持;服务端若直接 `chat_send` 同类字符返回 `-32602` |
| 21 | 未安装任何 CJK 字体的系统 | 中文显示为方框(字体缺失,非编码问题);安装中文补充字体后恢复 |
## 10. 已知限制
- **无投递回执**:`sent:true` 只表示已写入子连接并 `WaitSendIdle` 成功,不保证
使用者已看见。
- **HTTP 工作线程**:`chat_wait` 最长 55s 会占用一个 httplib 工作线程;不要在
同一 MCP 连接上并行大量长等待。
- **连接池复用窄竞争**:发送时捕获的 `subCtx` 在极端情况下可能已断开并被池复用;
与现有终端/屏幕实现同一取舍,靠 `closed` 检查与 `WaitSendIdle` 缩短窗口。
- **极慢 VM**:若首条消息仍丢,可把 `kChatOpenSettleMs` 调到 1500–2000ms,代价是
`chat_open` 变慢。
- **仍是 GBK 通道**:Unicode 对话框解决了「显示」,但线路上仍是 CP936,德语变音
字母(`ö`/`ä`/`ß`)、emoji 等无法传输。要根治需引入会话级编码协商(如
`TOKEN_CHAT_START` 后追加能力位,双方改用 UTF-8),属未来工作;服务端与客户端
必须同时升级,且旧客户端不能误解新报文。
- **字体依赖**:中文显示依赖系统已安装的 CJK 字体(字体链接到 "MS Shell Dlg"
的后备字体);仅此一点无法由程序保证,缺少字体时显示为方框。
+230 -1
View File
@@ -147,7 +147,8 @@ MCP 是 JSON-RPC 2.0。MVP 只需实现以下方法:
"online":{"type":"boolean"},
"group":{"type":"string"},
"screen":{"type":"string"},
"clientType":{"type":"string"}
"clientType":{"type":"string"},
"tls":{"type":"boolean"}
}
}
}
@@ -231,6 +232,7 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
- 基础标识:`id` / `name` / `remark` / `ip` / `os` / `location` / `group` / `version` / `clientType` / `screen`
- 实时信息:`rtt`(延迟)、`activeWindow`(当前活动窗口,即被控端正在做什么)
- 连接凭据:`tls`(布尔,对应在线主机列表的 TLS 列;`true` 表示该客户端本轮以 TLS 模式登录,是**登录时的凭据**而非实时探测;老客户端/空值一律 `false`)
输出结构 `{"hosts": [...]}`,每台主机一个对象,字段与 §3.3.2 的 `outputSchema` 一致。
@@ -256,6 +258,7 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
| `McpPort` | `6544` | MCP 监听端口;仅当 `McpEnabled=1` 时生效;未配置用默认 `6544` |
| `McpBind` | `127.0.0.1` | 监听地址;默认仅本机;可设 `0.0.0.0`(所有网卡)或内网 IP(如 `192.168.0.92`)以支持远程 |
| `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) |
| `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 |
> 与旧版「`McpPort=0` 即禁用」不同:启用与否改由独立的 `McpEnabled` 开关控制,`McpPort` 回归纯端口语义,二者解耦。
@@ -426,6 +429,7 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
- 写操作工具的安全边界评审(操作对象、权限、审计)
- 认证升级:复用 `WebServiceAuth` 的签名 token / 过期机制
- 分组过滤:`list_online_hosts` 加 `group` 参数
- P9 远程交谈(已实现):`chat_open` / `chat_send` / `chat_wait` / `chat_close`,独立开关 `McpChat`(默认 `0`,与只读开关无关);协议不变,客户端聊天窗口改为 Unicode 对话框以支持非中文系统(见 `docs/Mcp_Chat_Design.md`)
---
@@ -441,3 +445,228 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
- ✅ **取数方案**:C(抽公共函数 `BuildHostJson`,MCP 与 WebService 平级复用)。
- ✅ **返回字段**:全量,含实时信息(`rtt` / `activeWindow`),支持 AI 监督场景。
- ✅ **序列化**:`structuredContent` + `outputSchema`,`content` 附带可读摘要。
---
## 9. 增补(2026-10-25:N1–N5)
本轮在既有工具族(P2–P9)之上补齐「能找到主机、能一次查多台、输出不撑爆上下文、认证可追溯」四件事,全部为服务端改动,客户端零改动。
### 9.1 N1 离线主机可见
- 新增工具 `list_all_hosts`(`online` / `offline` 两个布尔过滤,默认都为 `true`),数据源是 `m_ClientMap`(主机列表历史记录,`GetAll()` 快照 + `m_cs` 保护),在线条目复用 `BuildHostJson`,离线条目由 `BuildOfflineHostJson` 生成,字段:`id` / `name` / `remark` / `ip` / `os` / `location` / `online` / `group` / `last_seen` / `install_time` / `authStatus`。
- `search_hosts` 的 `online` 参数:`true` = 仅在线,`false` = 仅离线(修复此前 `online=false` 永远返回空列表的问题),缺省 = 仅在线(与改动前一致,不改变既有调用方看到的结果)。两类都要请用 `list_all_hosts`。
- `authStatus` 是 `ClientValue::Authorized` 的三态枚举(`unauthorized` / `authorized_by_super` / `authorized_by_admin` / `forbidden`),不是布尔值。
- `get_host_detail` 对「在 `m_ClientMap` 里但当前离线」的 id 不再返回 `-32002`,改为返回该主机的最后记录(`online=false`),使 `list_all_hosts` 的结果可直接消费。
### 9.2 N2 批量只读调用
- 只读工具支持 `ids: []`(最多 50 个),与 `id` 二选一(inputSchema 用 `anyOf` 表达)。命中批量的工具:`get_host_detail` / `list_processes` / `list_windows` / `list_services` / `list_files` / `list_registry` / `get_client_log` / `get_activity_history` / `list_network_connections` / 全部 `host_list_*` / `host_get_hosts_file`。
- 写操作工具传 `ids` 直接 `-32602` 拒绝(不逐个执行,避免误操作扩散)。
- 返回:`{tool, total, succeeded, failed, results:[{id, ok, data|error, text}]}`;`content` 里是「共 N 台,成功 X 台,失败 Y 台」+ 最多 ~1200 字节的失败明细。
- `limit` / `offset` 对每台主机各自生效;批量是串行执行,单台超时会占用整批等待时间。
### 9.3 N3 `get_keylog`
- 复用客户端既有键盘记录链路:主连接下发 `COMMAND_KEYBOARD(169)` → 客户端建子连接 → 子连接回 `TOKEN_KEYBOARD_START(293)` 作为就绪包绑定 → 之后每约 1 秒推一包 `TOKEN_KEYBOARD_DATA(294)`。
- 服务端把击键流**累积**(不是一问一答),窗口 `duration_ms`(默认 4000,1000–15000)或字节上限 `max_bytes`(默认 64 KiB,1024–256 KiB)先到者结束;结束时 `EndManagedSession(..., cancelIo=true)` 关闭子连接 —— 与 MFC 关对话框同一路径,客户端据此停止记录。
- 复用 P8 的挂起会话表(新增 `PendingKind::Keylog`,仍受「单设备单飞行」约束),就绪包绑定、迟到包墓碑、子连接断开唤醒全部沿用 P8 逻辑;绑定后服务端回 `COMMAND_NEXT`,让客户端 `WaitForDialogOpen` 立即返回(本工具不开 UI)。
- 返回 `{id, duration_ms, bytes, lines, lineCount, truncated}`,文本按客户端代码页转 UTF-8(`GetClientEncoding`)。**注意**:客户端连上后会先把缓冲区里已有的历史记录推过来,所以结果既含历史也含窗口期内的新击键。
- 独立开关 `McpKeylog`(默认 `0`,不要求只读关)。工具只在开关打开时出现在 `tools/list`,关闭时直接调用返回 `-32006`。
- 隐私:击键内容只进本次响应;审计只记 `CALL_OK tool=get_keylog ms=… bytes=…`,不落任何正文。
### 9.4 N4 认证加固
- 静态 token 校验失败:返回 401,并按来源 IP 计数;60 秒窗口内失败 10 次即封禁该 IP 900 秒,封禁期内返回 429 + `Retry-After`。失败表上限 1024,满时先清理过期项。
- 环回来源(`127.0.0.1` / `::1`)**只记账不封禁**:内置 frpc 把 MCP 端口映射出去时是「本机连本机」,且这条转发没开 Proxy Protocol(httplib 不解析),服务端看到的源地址恒为环回。若按 IP 封禁,一次外部扫描就能把隧道后面所有客户端(包括自己)锁死 15 分钟。审计里这类封禁触发记为 `AUTH_BLOCK ... scope=proxy-source-exempt`。
- 审计文件 `<exe>\logs\mcp_audit.log`(追加写,5 MB 轮转为 `.1`),每行:时间戳(毫秒)、事件、来源 IP、详情。
- `AUTH_FAIL`:UA(截断/清洗)、body 大小、是否因此被封禁。
- `AUTH_BLOCK`:封禁生效。
- `CALL_OK` / `CALL_FAIL`:`tool=`、耗时 `ms=`、响应字节数 `bytes=`。
- `CALL_DENIED`:被策略拒绝的调用(`-32006`)另记一条,含 `tool=` 与固定原因文本,见 §10.8。
- 审计**不记录** token、密码、哈希、剪贴板内容或工具返回正文。
### 9.5 N5 列表输出治理
- 列表类工具统一 `limit` / `offset`:默认 `limit=100`,硬上限 `1000`,`offset` 默认 0;非正数按默认值处理。
- `structuredContent` 统一附 `total` / `totalAll` / `offset` / `limit` / `hasMore`,与 `McpMachine.cpp` 既有约定一致(`host_list_*` / `list_network_connections` 本来就是这样)。
- `content` 摘要统一为「共 N <单位>,本次返回第 a-b 条(还有更多,可用 offset 继续取)。」;`hasMore=false` 时不再出现「继续取」的误导提示;`offset` 越界时明确写「offset 超出范围,本次返回 0 条」。
- 实现集中在 `McpInternal.h/.cpp`:`PageWindow` / `ResolvePageWindow` / `ApplyPageWindow` / `WritePageFields` / `AppendPagingProps` / `PageSummary`。
- `list_files` 仍受客户端单次 500 条的硬限制(`total=500` 表示客户端截断,不是服务端分页)。
---
## 10. 增补(2026-10-25:A 批加固 / B 批非破坏性能力)
A 批只改服务端传输、元数据与校验,不动任何既有工具语义;B 批新增三个工具(两个写主机库、一个远程搜索)。**客户端零改动。**
### 10.1 A1/A2 传输层加固(`CMcpServer::Start`)
httplib 默认值对 MCP 场景不合适,改为显式配置:
| 项 | 默认 | 现在 | 原因 |
|---|---|---|---|
| 请求体上限 | 不限(`SIZE_MAX`) | 2 MB(超出 413 `RequestEntityTooLarge`) | 只收 JSON 参数,文件内容走子连接分块,绝不进 HTTP body |
| 读超时 | 5s | 15s | 经 frp 隧道上传参数时,单次 recv 不该 5s 就断 |
| 写超时 | 5s | 60s | `get_screenshot` 大图 base64、慢链路下 5s 会写断响应 |
| 线程池 | `max(8, 核数-1)` | 固定 32 | `chat_wait`(最长 55s)与批量只读会长期占线程 |
读超时是 **socket 空闲读超时**,不是「处理时长上限」:`search_file` 阻塞 20s、`chat_wait` 阻塞 55s 都正常返回(已实测)。
### 10.2 A3 工具注解(`McpInternal::ApplyToolAnnotations`)
- `tools/list` 每个工具都带 `annotations`:`readOnlyHint` / `destructiveHint` / `idempotentHint` / `openWorldHint`,由 `McpInternal.cpp` 的 `kToolHints` 表按名登记,末尾统一补一次。
- 未登记的工具按规范默认值处理(`destructiveHint=true`),即**新增工具必须显式登记**,漏登记只会更保守,不会误标成只读。
- 只读工具的 `destructiveHint` 一律 `false`(按规范对只读工具无意义,避免客户端误报「破坏性」)。
- `openWorldHint=false` 只给「只读服务端本机状态」的工具(`list_online_hosts` / `search_hosts` / `list_all_hosts` / `get_host_detail` / `get_activity_history` / `get_audit_log` / `get_server_status`),其余都会触达外部主机。
### 10.3 A4 `get_host_detail` 字段补全
在线主机现在返回:`id` / `name` / `online` / `ip` / `publicIp` / `location` / `group` / `os` / `version` / `exeVersion` / `clientType` / `clientPath` / `systemBits` / `programBits` / `cpuCores` / `memoryGB` / `monitors` / `screen` / `user` / `isAdmin` / `pid` / `installTime` / `activeWindow` / `rtt` / `tls`;离线主机返回 `authStatus` / `last_seen` / `install_time` 等最后记录。
注意 `memoryGB` 是 **double**:客户端 `GetMemorySizeGB()` 上报的就是浮点字符串(如 `"27.800000000000001"` 的原始形态),不能按整数解析。服务端按 1 位小数规范化,并给 jsoncpp 写入器设 15 位有效数字,避免输出 17 位噪声。
### 10.4 B1 主机库写入:`host_set_remark` / `host_set_watch_level`
- 写的是服务端本机的 `_ClientList`(`MAP_NOTE` / `MAP_LEVEL`),**只影响主控端自己的展示**:不下发命令、不改远端状态。
- 门控:`McpReadonly=0` 即可(不要求 `McpManage`);在线/离线(历史记录)主机都能写,id 在主机库中存在即可。
- `host_set_remark`:`remark` 必填(空串 = 清除),**严格 GBK 转换**(emoji、`ö` 等不可表示字符报 `-32602`),长度上限 63 GBK 字节(主机库列 `char Note[64]`)。
- `host_set_watch_level`:`level` 0–3。重复写同一值幂等。
- 写后 `SaveToFile(GetDbPath())` 落库,并用 `LVM_REDRAWITEMS` 让在线列表那一行立刻刷新(MCP 线程不直接碰 `CListCtrl`)。
- 审计只记「set/cleared + 字节数」与 `level=`,**不记录备注正文**。
### 10.5 B2 远程文件搜索:`search_file`
**链路**(旧文件管理器,不是 SimplePlugins 版):
```
主连接 COMMAND_LIST_DRIVE → 客户端建子连接 → 子连接回 TOKEN_DRIVE_LIST
→ 服务端 OnDriveList 下发 COMMAND_SEARCH_FILE [根目录 \0][模式 \0](ANSI/GBK 两个 C 串)
→ N × TOKEN_SEARCH_FILE_LIST(分片)→ TOKEN_SEARCH_FILE_FINISH
```
协议来自 `client/FileManager.cpp`(`COMMAND_LIST_DRIVE` → `LoopFileManager` → `CFileManager`)。客户端工程是 MultiByte,所有字段都是 GBK,服务端用 `Utf8ToCpExact` 严格转换,不可表示即 `-32602`。
要点:
- **模式**:不含 `*` / `?` 时客户端当成 `*pattern*`(不区分大小写的子串),含通配符时走 `WildcardMatch`。
- **递归**:客户端只有递归搜索(深度 32,最多 10000 条,跳过隐藏/系统目录与重解析点)。`recursive=false` 由**服务端按「父目录 == 根目录」过滤**实现。
- **路径归一化**:客户端用 `wsprintf("%s\\*.*")` 枚举,根目录带尾部反斜杠会拼成 `C:\\*.*` 导致 `FindFirstFile` 失败、搜索秒回 0 条。服务端统一切成正斜杠→反斜杠并去尾斜杠(`C:\` → `C:`,客户端再拼回 `C:\*.*`)。
- **超时**:`timeout_ms` 默认 20000(1000–120000)。到点先下发 `COMMAND_FILES_SEARCH_STOP`,再等 5s 收尾;收不到 `FINISH` 也返回已收到的部分结果,`finished=false`。
- **收集上限**:5000 条 / 4 MB 原始包,超出即让客户端停搜并置 `truncated=true`(保护服务端内存,整盘搜索能命中几十万条)。
- **子连接身份校验**:`TOKEN_SEARCH_FILE_LIST` / `TOKEN_SEARCH_FILE_FINISH` 都按 `context*` 比对当前 pending 的子链接,旧搜索(已放弃)的尾包一律不受理,避免迟到的 FINISH 终止新搜索。
- **已知风险(客户端既有缺陷,仓库内已修)**:`client/FileManager.cpp` 的 `SearchFilesRecursive` 曾用无界 `wsprintf` 往 `char[MAX_PATH]` 里拼路径(`strPath`、`szFullPath`),全程没有长度检查。目录一深(累计路径超过 260)就栈溢出:Debug 客户端弹 `Run-Time Check Failure #2 - Stack around the variable 'strPath' was corrupted` 并挂住搜索线程,Release 客户端静默破坏栈。MFC 文件管理器的「搜索」走同一函数,**与 MCP 无关**。源码已于 2026-10-25 修掉(commit 8f718d9,入口/逐条目长度预判);**已部署的老客户端仍带这个缺陷**,所以 `tools/mcp_smoke.ps1` 的搜索用例仍是 opt-in(`-SearchPath`)。
- **无头路由**:MFC 对话框存在时搜索结果走 `OnReceiveComplete`;只有无头子连接(MCP 调用)才会进 `MessageHandle`,所以这两条 case 只影响 MCP。`TOKEN_SEARCH_FILE_LIST` 分支**绝不 CancelIO**(后面还有 FINISH 与剩余分片)。
- 输出:`{files:[{path,name,dir,size,modified}], finished, truncated, total, totalAll, offset, limit, hasMore}`。
### 10.6 A5 冒烟测试脚本
`tools/mcp_smoke.ps1`:只调只读工具(列表/详情/搜索 + 传输层负例),断言分页字段、注解、401/413、批量汇总。
```powershell
$env:YAMA_MCP_TOKEN = '<token>'
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 # 默认 6544(Release)
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 -Base http://127.0.0.1:6545/mcp
```
token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机时加 `-SkipHost`。退出码 0/1,可接 CI。
### 10.7 明确不做的两项
- `get_clipboard`:剪贴板常含口令/令牌/私钥,属"读即泄密",且客户端没有"只读不覆盖"的现成链路;已有 `remote_clipboard` 覆盖写。需要时用 `get_screenshot` + 人工确认。
- `close_window`:`operate_window` 的 `close` 动作已覆盖(同一 `COMMAND_WINDOW_CONTROL` 链路),不重复造工具。
### 10.8 D 批:拒绝也入审计
动机:所有策略拒绝(只读模式、`Mcp*` 开关关闭、主机不支持某能力)都返回 `-32006`,而审计里只有 `CALL_FAIL`——和「参数错」「主机离线」「超时」混在一起,事后分不清「没人调过」和「被策略拦下」。
- 实现放在 `tools/call` 的统一出口(`CMcpServer` 的 HTTP 处理器),不在 24 个 `-32006` 分支里逐个埋点:成功解析响应体后多取 `error.code` / `error.message`,`code == -32006` 就追加一条
```
<时间> CALL_DENIED ip=<来源> tool=<工具名> reason=<固定英文原因>
```
同一调用仍会留下原有的 `CALL_FAIL` 行,所以 `CALL_FAIL` 的统计口径不变。
- `reason` 全部是各分支写死的英文句子(如 `File transfer is disabled: requires McpFileTransfer=1`),不含调用参数或用户输入,落盘安全;审计依旧不记录 token、参数或返回正文。
- 其他错误码(`-32602` 参数、`-32002` 主机离线、`-32001` 超时等)不额外记事件,靠 `CALL_FAIL` 行即可。
- 验证(Debug 实例):把 `McpFileTransfer` 临时置 0 重启后调 `download_file`,审计立刻出现
`CALL_FAIL ... tool=download_file ms=1 bytes=114` 紧跟 `CALL_DENIED ... reason=File transfer is disabled: requires McpFileTransfer=1`;恢复 `McpFileTransfer=1` 重启后同一调用恢复 `CALL_OK` 且无 `CALL_DENIED`。冒烟脚本 20/20 通过(未指定 `-SearchPath` 时跳过 2 个搜索用例)。
---
## 11. 增补(C 批:读侧增强,不改客户端)
### 11.1 C1 `get_audit_log` 分页与过滤
改动前每次调用都返回镜像里的全部条目(环形缓冲上限 1000 条),调用方没法只看关心的部分,日志一多就会把工具返回值撑大。
- 新增入参:`type`(类型列子串,不区分大小写,如 `MCP` 能匹配 `MCP命令执行`)、`keyword`(正文子串,不区分大小写)、`limit` / `offset`(沿用统一分页,默认 100、上限 1000)。
- 过滤在分页之前生效:`total` 是命中条数、`totalAll` 是镜像里的全部条数;`hasMore` 针对命中的条目。摘要会补一句「过滤前共 N 条」,方便判断是不是过滤写错了。
- 读取仍在 `m_cs` 临界区内完成(UI 线程会并发写入),过滤循环里先做 GBK→UTF-8 转换再比对,避免拿两种编码互相比。
- outputSchema 补 `total/totalAll/offset/limit/hasMore`(与其它列表工具一致)。
- 注意 `get_audit_log` 读的是**主界面消息镜像**,不是 `logs\mcp_audit.log`;两者的条目内容和保留策略都不同(前者是 1000 条环形缓冲,后者是 5 MB 文件滚动)。
- 验证(Debug 实例):`limit=2` 两页分别返回第 1-2 / 3-4 条且 `hasMore=true`,`offset=999` 返回「offset 超出范围」;`type=mcp` 命中 `MCP命令执行`(大小写不敏感)、`type=提示` 命中「使用提示 / 提示信息」、`keyword=监听` 命中「监听端口: 6543成功」;冒烟脚本 23/23 通过(新增分页字段、条数上限、过滤未命中 3 项断言)。
### 11.2 C2 新工具 `get_server_status`
排查「改动到底生效没有」「为什么某个工具被拒」时,原先只能靠 `list_online_hosts` 加 `get_audit_log` 侧面推断;现在有一个服务端自身的状态快照。纯内存、只读、不建子连接。
返回(`structuredContent.status`):
| 字段 | 含义 |
|---|---|
| `app_name` / `version` | 品牌名与 `BRAND_VERSION`(当前 1.4.1) |
| `exe_build_time` | exe 文件的最后写入时间=链接时间(比 `__DATE__`/`__TIME__` 可靠,后者是编译单个 .cpp 的时间) |
| `uptime_sec` | 进程已运行秒数(`GetProcessTimes` 的创建时间起算,不是开机时间,也不受 MCP 启停影响) |
| `bind` / `port` | MCP 实际监听的地址与端口(`Start` 时记录,非从配置回读) |
| `switches` | `readonly` / `terminal` / `remote_control` / `file_transfer` / `manage` / `machine` / `machine_dangerous` / `keylog` / `chat` |
| `hosts` | `online` / `offline` 台数(与 `list_all_hosts` 同源) |
| `sessions` | `pending`(一次性/管理/键盘记录挂起) / `terminal` / `remote_control` / `file_transfer` / `chat` 在飞会话数 |
| `blocked_auth_ips` | 当前处于鉴权封禁期的来源 IP 数 |
- **不返回** token、`McpCmdWhitelist` 内容或任何配置原文;`switches` 只报布尔值。
- `sessions` 各项各取各自的锁、取完即放,是「大致同一时刻」的估算值,不能当一致性快照用。
- 工具注解登记为只读 + 非破坏性 + 幂等 + 不触达外部主机;`tools/list` 总数变为 53。
- 验证(Debug 实例):返回 `Yama v1.4.1,已运行 17 秒,监听 127.0.0.1:6545;在线主机 1 台、离线 3160 台`;`terminal_open` 期间 `sessions.terminal=1`、`terminal_close` 后回到 0;冒烟脚本 26/26 通过(新增 3 项:正常返回、版本/端口/开关齐全、不含 token)。
### 11.3 C3 主机列表过滤:`list_online_hosts` / `list_all_hosts`
这两个工具原先只有分页,想找「某个分组」「某个平台」的主机只能翻页或改用 `search_hosts`(后者不支持 `client_type`,且对在线/离线的取舍规则不同)。
- 新增三个可选入参(两个工具共用同一套实现):`group` / `os` / `client_type`,均为子串匹配、ASCII 不区分大小写、AND 组合,口径与 `search_hosts` 一致。
- 过滤在分页之前生效:`total` 为命中台数、`totalAll` 为过滤前总数(`list_online_hosts` 是全部在线数,`list_all_hosts` 是主机库总数);摘要改用「共 N 台主机匹配」并补一句过滤前规模,写错条件时一眼能看出来。
- `list_all_hosts` 摘要里的在线/离线拆分也按命中条目统计。
- **离线主机没有 `clientType`**(历史记录里不存这个字段),所以带 `client_type` 条件时离线主机不会命中——按平台筛历史主机用 `os`。
- 验证(Debug 实例):`client_type=exe` 命中 1 台(`EXE`/`os=Windows 11`),`client_type=lnx` 命中 0 台但 `totalAll` 仍为 1;`list_all_hosts` 带 `group=default` 命中 3161 台并正确拆分在线 1 / 离线 3160,`os=zzz` 命中 0 台;冒烟脚本 28/28 通过(新增过滤未命中、totalAll 不变 2 项断言)。
### 11.4 C4 `search_file` 结果侧过滤
`search_file` 的搜索条件(根目录 + 通配模式)由客户端执行,改不动;但把匹配项拿回服务端后可以再筛一遍,省掉 AI 端逐条比对。
- 新增四个可选入参,**都在服务端对已收集的匹配项做过滤**,不减少客户端侧搜索耗时:
- `min_size` / `max_size`:字节数,整数,闭区间;负数或非数字返回 `-32602`;两者都给出且 `min_size > max_size` 返回 `-32602`。
- `modified_after`:接受 `YYYY-MM-DD`(当天 00:00:00 之后)或 `YYYY-MM-DD HH:MM:SS`;格式不符返回 `-32602`。客户端返回的 `modified` 是定宽 `"YYYY-MM-DD HH:MM:SS"`,可直接字典序比较,所以两种写法都合法(`"2026-01-01" <= "2026-01-01 08:00:00"`)。
- `name_only`:布尔,命中项只保留 `path` / `name` 两个字段,适合只要文件清单时省 token。
- 过滤在分页之前:`total` 为命中条数、`totalAll` 为过滤前条数;摘要补一句「过滤前共 N 条(大小/修改时间/精简字段过滤在服务端进行,不减少客户端搜索耗时)」。
- 过滤只看服务端已收到的条目,所以仍受 `max_results` / `timeout_ms` 截断:客户端没搜完时,过滤结果也是部分的(`truncated` / `finished` 字段照旧反映这一点)。
- 验证(Debug 实例,根目录 `C:\Windows\Fonts`、`*.ttf`):基线 255 条;`min_size=1000000` → 39 条且 `totalAll=255`;`name_only=true` 每条只有 `path`/`name`;`modified_after=2026-01-01` → 165 条、`2026-06-03 00:00:00` → 130 条、`2027-01-01` → 0 条;`min_size=-5`、`min_size=10 & max_size=5`、`modified_after=2026/01/01`、`modified_after=2026-01-01 12:00` 均返回预期的 `-32602`。冒烟脚本 33/33 通过(新增 3 项:`min_size` 过滤后 `totalAll` 不变、`name_only` 精简字段、非法 `modified_after` 返回 `-32602`;后三项需带 `-SearchPath` 才执行)。
## 12. 错误码速查(E 批:冒烟与文档)
工具的失败分三类,AI 端应按 `code` 决定下一步,而不是读 `message` 文本。`message` 是给人看的英文说明,随实现变化,不作为契约。
| code | 含义 | 典型触发 | 建议动作 |
|---|---|---|---|
| `-32700` | Parse error | 请求体不是合法 JSON | 修正客户端序列化 |
| `-32600` | Invalid Request | 缺 `jsonrpc` / `method` / 非法 `tools/call` 结构 | 修正请求 |
| `-32601` | Method not found | `method` 不是 `initialize` / `tools/list` / `tools/call` 等 | 修正请求 |
| `-32602` | Invalid params | 未知工具名、缺必填参数、参数类型/取值非法、批量 `ids` 超过 50 个、`search_file` 过滤参数非法、文本无法转 GBK | 改参数重试,重试同样的请求不会成功 |
| `-32001` | Timeout | 等客户端就绪/等子连接/等搜索结果超时(`timeout_ms` 内没等到) | 可加大 `timeout_ms` 重试;持续出现看主机是否卡住 |
| `-32002` | Host offline / not found | 主机 id 不存在、主连接已断、会话 id 不存在或已关闭 | 先 `list_online_hosts` 刷新再选主机 |
| `-32003` | Busy | 该主机已有同类请求在飞(终端/截屏/文件/聊天会话),或同设备重复 `chat_open` | 等前一个结束或先 `*_close` |
| `-32004` | Send failed | 命令写入主连接失败(连接刚断) | 重试一次;仍失败按 `-32002` 处理 |
| `-32005` | Not supported on this host | 需要 Windows 的工具用在 LNX/MAC/APK 主机上 | 换 Windows 主机,或改用跨平台只读工具(`list_files` 等) |
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 |
- `-32006` 会额外在审计日志里记一条 `CALL_DENIED`(§10.8),其余错误只体现在 `CALL_FAIL` 行。
- 批量调用(带 `ids[]`)**整体不报错**:每个 id 的结果单独带 `error`,顶层用 `succeeded` / `failed` / `skipped` 汇总;只有整批请求本身非法(超过 50 个 id、写操作传 `ids`)才返回顶层 `-32602`。
- 冒烟脚本 `tools/mcp_smoke.ps1` 覆盖了上表的可复现项:`-32601`(未知 method)、`-32602`(未知工具/缺参数/51 个 id)、`-32002`(不存在的主机)、`-32006`(任一开关关闭时自动挑一个关着的功能验证,并断言审计里出现 `CALL_DENIED`;全部开启时跳过)。其余码由各批次的功能验证覆盖(`-32001`/`-32003` 等需要构造竞态或超时,不进冒烟)。
- 本次验证(Debug 实例,`McpKeylog` 临时置 0):`get_keylog` 返回 `-32006`,`Bin\logs\mcp_audit.log` 末尾出现 `CALL_DENIED ... tool=get_keylog reason=Keyboard log is disabled (McpKeylog=0)`;此时冒烟 34/34 通过。恢复开关后 `-32006` 与审计两条转为跳过,32/32 通过;带 `-SearchPath` 时 37/37 通过。
+7
View File
@@ -394,3 +394,10 @@ int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn, nullptr, m_hash, m_hm
| U7 | 实施验证发现:客户端主连接 `g_status==0`,`RecvFileChunkV2` 逐 chunk `return -1`(上传落盘 0 字节/截断) | 客户端 `COMMAND_SEND_FILE_V2` 分支加懒初始化(§7.8):`static` 一次 + 永久引用计数、析构不 `Uninit`;与 `FileManager.cpp:40` 参数一致,独立评审确认无稳定性风险 |
**判定**:7 项均已写入 §7 对应小节,无阻塞项,**定稿**。
### 13.2 实施后修复记录(2026-10-25)
| # | 问题 | 修复 |
|---|---|---|
| R1 | **纯目录树下载必超时**:完成判定 `filesDone >= totalFiles - directoryCount` 只在 `OnFileCompleteV2` 里跑,而客户端对目录项不发 `COMMAND_FILE_COMPLETE_V2`。空目录/只有子目录的树期望文件数为 0,永远等不到 COMPLETE → 只能干等 `timeout_ms`(默认 600s)后报 `1002` | `OnFileChunkV2` 的目录分支里,`directoryCount >= totalFiles`(即全部条目都是目录)时直接置 `done` + notify。实测空目录 0.2s 返回、3 文件目录树回归正常 |
| R2 | **断线无清理 → 悬空子连接指针**:`FileTransferSession.fmSubCtx / streamSubCtx` 是裸 `context*`,`OfflineProc` 只清了终端/远程控制/聊天,没有文件传输的钩子(§6.5 声称的「断线擦会话」实现缺失)。客户端传输中掉线后 connection 被连接池回收,工具线程超时路径仍对其 `CancelIO()` → 悬空指针/误取消他人连接 | 新增 `m_FileXferContextToDevice` 反查表(受 `m_FileXferMutex` 保护,`ClearFileTransfer` 同步擦除),`OfflineProc` 增 `OnFileTransferContextClosed`:清指针并移除反查项;**流式子连接**断开即判失败(`error=1003`,立即唤醒工具线程),文件管理器子连接断开只清指针(数据走流式子连接,不判失败)。实测传输中杀掉客户端:1s 返回 `Connection lost`(原来要等满 `timeout_ms`),服务端存活;重启客户端后连续两次下载、一次上传均正常 |
+273
View File
@@ -0,0 +1,273 @@
# MCP P8 设计:在线主机 TLS 字段 / 连接管理 / 主机管理
> 延续 `Mcp_Design.md` → `Mcp_Phase2_Design.md`(P2)→ P3~P6 → `Mcp_Manage_Design.md`(P7)。
> P7 复用的是「系统/窗口/服务」对话框使用的 `COMMAND_SYSTEM`、`COMMAND_WSLIST`、
> `COMMAND_SERVICECONFIG` 链路;本轮要覆盖的「连接管理」与「主机管理」走的是**另一套**
> 命令(`COMMAND_CONNECTION` / `COMMAND_MACHINE_MANAGE`),必须在同一子连接上收发多步,
> 因此新增一层会话抽象,并为工具族增加独立开关。
>
> 安全门结论(已确认):新增独立 `host_*` 工具族;写入范围限定「只读 + 可恢复操作」;
> 开关分两层——`McpMachine`(工具族总开关)与 `McpMachineDangerous`(高风险子集),
> 均默认关闭,并与 `McpReadonly` 叠加。现有 27 个工具(含 P7)一律不改行为。
## 1. 范围
| 交付 | 内容 |
|---|---|
| TLS 字段 | `list_online_hosts` / `search_hosts` / `get_host_detail` 增加 `tls` |
| 连接管理 | `list_network_connections`、`kill_network_connection` |
| 主机管理读 | 10 个标签页各一个:`host_list_processes` … `host_get_hosts_file` |
| 主机管理写 | `host_control_process` / `host_control_window` / `host_control_service` / `host_control_task` |
| 配置 | 设置对话框两个复选框 + 启动接线(`McpMachine` / `McpMachineDangerous`) |
不做的(明确排除):kill 进程、关闭窗口、删除服务/任务、卸载软件、写 hosts、
创建任务、强制删除文件、代码注入。
## 2. TLS 字段
- `HostJson.cpp` 的 `BuildHostJson()` 末尾追加
`device["tls"] = (ctx->GetClientData(ONLINELIST_TLS) == "Y");`。
数据源是登录时写入的 `ONLINELIST_TLS`(`2015RemoteDlg.cpp` 收到 `RES_TLS=="1"` 时置 `"Y"`)。
- 语义:**登录凭据**,不是实时探测。老客户端不上报该值 → `false`。
- `BuildHostJson` 同时被 WebService 的设备列表复用,Web 端也会多出该字段(向后兼容)。
- `get_host_detail` 复用 `BuildHostItemSchema()`,自动带上。
## 3. 会话架构
两条新链路都需要「主连接发一条命令 → 客户端新建子连接 → 子连接回就绪包 →
在同一子连接上多次收发」,现有 `m_Pending` 只能等主连接上的单包。做法是给
`PendingRequest` 增加 `kind`,**复用同一张表** `m_Pending`(从而天然保证「单设备单飞行」),
而不是另开一套状态。
```cpp
enum class PendingKind { Generic, FollowUp, Machine, ConnMgr };
```
| 成员 | 用途 |
|---|---|
| `m_SubCtxToDevice` | 已绑定的子连接 → device;绑定的子连接上所有包都由 MCP 消费 |
| `m_AbsorbedSubCtx` | `CancelIO` 后仍可能到达的包:静默丢弃 |
| `m_OrphanByDevice` / `m_OrphanByPeer` | 5 秒墓碑,防止迟到的就绪包弹出 MFC 对话框 |
### 3.1 时序(工具线程)
```
BeginMachineSession(dev, tool, mainCtx) // 登记单飞行;忙 → -32003
→ 主连接 Send2Client(COMMAND_MACHINE_MANAGE)
→ 客户端开 CMachineManager 子连接,回 TOKEN_SYSINFOLIST(61)
→ OnManagedSubPacket 绑定子连接、保存首包、notify_all
WaitManagedPacket(dev, 61, …, 5000) // 就绪
每次读:
ArmManagedResponse(dev, 期望 token)
→ 子连接 Send2Client([tab 0..9]) / WaitSendIdle
→ WaitManagedPacket(dev, 期望 token, …, 12000)
EndManagedSession(dev, cancelIo=true) // 关闭子连接,不留长连接
```
整体 60 秒会话截止;每一步取 `min(step, deadline - now)`。所有超时返回 `-32001`。
### 3.2 子连接路由(`OnManagedSubPacket`)
在 `3.1` 的模型下,UI 线程收到的每个包先经过钩子
(`MessageHandle` 中终端拦截块之后、`switch (cmd)` 之前):
1. 已绑定 → 只保留 `expectedToken` 匹配的包;`TOKEN_MACHINE_MSG(42)` 存为
`clientError`(CP936→UTF-8);其余丢弃。已绑定的子连接上的一切包都归 MCP。
2. `m_AbsorbedSubCtx` 命中 → 丢弃。
3. 未绑定且 token 不是 `61` / `255` → 交回主 switch(MFC 行为不变)。
4. 未绑定且是 `61` / `255`:
- 该 context 就是主连接(`FindMainContext(parent, cid)`)→ 交回主 switch;
- 否则在同 device 的未绑定会话中按 `clientID` 精确绑定;
- 老客户端子连接 `clientID` 可能为 0 → 按 `peer` 兜底,**仅当同 peer 唯一**时才绑定;
- 都不命中:墓碑未过期 → 吸收 + `CancelIO` + 消费;否则交回主 switch
(用户手动打开对话框)。
### 3.3 必须同步调整的现有语义
- `IsPending()` 排除 `Machine` / `ConnMgr`:否则会话在飞时用户点「进程管理」,
`case TOKEN_PSLIST` 会把界面包抢走。
- `TakeMainResponse()` 顶部对 managed kind 直接返回。
- `OfflineProc` 在 `OnManageSubClosed` 之后、`RemoveFromHostList` **之前**调用
`OnManagedContextClosed`(否则连接池复用同一 context 指针后,新连接的包会被误吞)。
- 锁序:`parent->m_cs` → `m_PendingMutex`;持锁期间禁止 `Send2Client` / `CancelIO` /
`WaitSendIdle`。
### 3.4 健壮性
- UI 线程只做「有界拷贝 + 保存 + 唤醒」:单包上限 8 MiB,超限置 `clientError` 并 `CancelIO`。
- 解析全部在 MCP 工作线程上做;字符串一律用 `BoundedStrlen` / 显式偏移,
未对齐的多字节整数用 `memcpy`,禁止指针强转。
- 客户端部分列表用 `Send(buf, LocalSize(buf))` 发送,长度可能带出少量尾随 0 填充:
记录解析循环遇到「剩余全 0」即结束,定长记录列表忽略不足一条记录的尾部。
## 4. 连接管理
### 4.1 协议
- 主连接:`COMMAND_CONNECTION(253)`;客户端建 `CConnectionsManager` 子连接。
- 子连接回 `[255][u16 LE count][ConnectionInfo × count]`。
- `ConnectionInfo`(`common/commands.h`,`#pragma pack(1)`,110 字节,已 `static_assert`):
`proto(1)` / `af(1)` / `pid(4)` / `localAddr[16]` / `localPort(2,主机序)` /
`remoteAddr[16]` / `remotePort(2,主机序)` / `state(4)` / `procName[64](UTF-8)`。
地址为网络序;IPv4 取前 4 字节,`af == AF_INET(2)`,IPv6 为 `AF_INET6(23)`。
- 强制断开:子连接发 `[254][原始 110 字节记录]`;客户端 `SetTcpEntry(DELETE_TCB)`
后自动重发一次 255。
### 4.2 工具
| 工具 | 门控 | 说明 |
|---|---|---|
| `list_network_connections` | `McpMachine` | 过滤 `protocol/family/pid/process/local_port/remote_port/remote_address/state` + 分页;输出 `killable = (proto==1 && af==AF_INET)` |
| `kill_network_connection` | `McpMachine && McpManage && !McpReadonly` | 必填四元组;可选 `pid` 消歧、`dry_run` |
`kill_network_connection` 的流程刻意避免「重新拼地址」:
1. 取最新列表,**按原始 110 字节记录精确匹配**四元组(可选同时校验 PID);
2. 匹配 0 条 → `-32009`(调用方应刷新);匹配多条 → `-32602`(要求给 `pid`);
3. 目标不是 IPv4 TCP → `-32005`,不发包;
4. `dry_run` → 直接返回目标;
5. `Arm(255)` → 发 `[254][原记录]` → 等刷新列表 → 复核该四元组是否消失。
客户端 `SetTcpEntry` 的返回值被忽略且需要管理员权限,所以「断开后仍在」返回
`structuredContent.ok=false, reason="still_present"`,**绝不谎报成功**。
每次调用写审计:`tcp a:p->b:q pid=N result=…`。
## 5. 主机管理
### 5.1 协议
- 主连接:`COMMAND_MACHINE_MANAGE(162)` → 客户端 `CMachineManager` 子连接回
`TOKEN_SYSINFOLIST(61)`。
- 之后在同一子连接上发 **1 字节 tab**(0–9),响应 token 31–42。
- 动作 10–30;多数动作客户端会自动回一份刷新后的列表(服务 = 40,任务 = 41),
进程冻结/解冻(16/17)与窗口操作(11)**不回包**。
`MachineManager` 枚举(`common/commands.h`):请求 0 PROCESS / 1 WINDOWS / 2 NETSTATE /
3 SOFTWARE / 4 HTML / 5 FAVORITES / 6 WIN32SERVICE / 7 DRIVERSERVICE / 8 TASK / 9 HOSTS;
响应 31 PROCESS / 32 WINDOWS / 33 NETSTATE / 34 SOFTWARE / 35 HTML / 36 FAVORITES /
37 WIN32SERVICE / 38 DRIVERSERVICE / 39 HOSTS / 40 SERVICE_LIST / 41 TASKLIST / 42 MACHINE_MSG。
### 5.2 读工具
| 工具 | tab | 响应 | 主要过滤 |
|---|---|---|---|
| `host_list_processes` | 0 | 31 | `pid` / `name` / `arch` |
| `host_list_windows` | 1 | 32 | `pid` / `title` |
| `host_list_network_state` | 2 | 33 | `pid` / `process` / `protocol` / `local_port` / `remote_port` / `state` |
| `host_list_software` | 3 | 34 | `name` / `publisher` |
| `host_list_browser_history` | 4 | 35 | `title` / `url` |
| `host_list_favorites` | 5 | 36 | `name` / `url` |
| `host_list_win32_services` | 6 | 40 | `name` / `status` / `start_type` |
| `host_list_driver_services` | 7 | 40 | 同上 |
| `host_list_scheduled_tasks` | 8 | 41 | `name` / `folder` / `status` |
| `host_get_hosts_file` | 9 | 39 | `include_content` / `max_bytes` |
公共分页 `offset`(默认 0)/ `limit`(默认 100,上限 1000);输出
`total`(过滤后)/ `totalAll` / `offset` / `limit` / `hasMore`。
### 5.3 记录格式(与 `CMachineDlg::Show*` 逐字段对齐)
| 列表 | 格式 |
|---|---|
| 进程 31 | `DWORD pid`、`bool is64`、`title[260]`、`exe`+pad、`path`+pad、`DWORD priClass`、`DWORD threads`、`user`+pad、`DWORD workingSetKb`、`DWORD fileSizeKb`;CP936 |
| 窗口 32 | `WINDOWSINFO` 定长 1044 字节;**只含可见窗口**;空列表 = 1 字节 |
| 网络状态 33 | 进程名、`DWORD pid`、`[TCP]/[UDP]`、`ip:port`、远端、状态,各串 +2;UDP 远端 `*.*.*.*:*`、状态为空;按最后一个 `:` 拆地址 |
| 软件 34 | 5 个串各 +2:显示名、发布者、版本、安装日期、卸载命令 |
| 浏览记录 35 | 定长 2148:`time[100]` + `title[1024]` + `url[1024]` |
| 收藏夹 36 | 2 个串各 +2 |
| 服务 40 | 8 个串各 +1 NUL:显示名、描述、状态、启动类型、登录身份、交互式、**服务名**、可执行路径 |
| 计划任务 41 | `name/path/exe` 为 UTF-8、`status` 为 GBK,各 +1 NUL;两个 `DATE`;两个 0 字节结束;`folder` 由 `path` 去掉末尾 `"\<name>"` 派生 |
| hosts 39 | `[39][文件原文][0]`;有 BOM → UTF-8,否则合法 UTF-8 → UTF-8,否则 CP936 |
### 5.4 写工具
统一模式:**先取列表校验目标存在 → 发动作 → 再取列表复核**。目标不在最新快照里
返回 `-32009`,绝不盲发。
| 工具 | action | 额外门控 | 动作包 | 复核 |
|---|---|---|---|---|
| `host_control_process` | `freeze` / `thaw` | `McpMachineDangerous` | `[16/17][DWORD pid]`(无回包) | 重新取 tab 0:PID 仍在 |
| `host_control_window` | `restore/hide/maximize/minimize` | — | `[11][DWORD hwnd][DWORD SW_*]` + 零填充到 20 字节(客户端只读前 9 字节) | 重新取 tab 1:hide 后 hwnd 应消失,其余应仍在 |
| `host_control_service` | `start`/`pause`/`continue` | — | `[22/24/25][服务名 CP936][NUL]` | 客户端自动回 40 |
| `host_control_service` | `stop`/`restart` | `McpMachineDangerous` | stop = `[23]`;restart = stop → 等 40 → start | 等 40(12 s),状态在期望集合内 |
| `host_control_task` | `run` / `stop` | — | `[29/28][folder CP936][NUL][name CP936][NUL]` | 客户端自动回 41:任务仍在 + 当前状态 |
补充规则:
- 服务动作前先取一次服务列表(prime),既校验目标,也把客户端 `m_dwServiceType`
钉到正确类型(Win32 / 驱动)。
- 已是目标状态时不下发动作,返回 `ok=true, changed=false, reason=already_*`。
- 冻结/解冻、窗口动作、任务动作**没有回执**:`verified` 只表示「已用动作后的快照复核」,
不表示「动作一定生效」。冻结不改变进程存在性,因此只能确认目标仍在。
- 写工具输入串(服务名、任务 folder/name)必须能转成 CP936,否则 `-32602`,不发包。
- 审计格式:`host <id> <tool>: action=… target=… result=…`。
## 6. 门控矩阵
| 配置 | 可见工具 | 直接调用被隐藏的工具 |
|---|---|---|
| `McpMachine=0`(默认) | 0 个 | `-32006` |
| `McpMachine=1, McpReadonly=1` | 11 个读工具(`list_network_connections` + 10 个 `host_list_*` / `host_get_hosts_file`) | 5 个写工具 → `-32006` |
| `McpMachine=1, McpReadonly=0, McpManage=1` | 16 个(含 5 个写) | — |
| `McpMachine=1, McpReadonly=0, McpManage=0` | 15 个(无 `kill_network_connection`) | `kill_network_connection` → `-32006` |
| `McpMachineDangerous=0` | 工具仍可见 | `host_control_process`、`host_control_service{stop,restart}` → `-32006` |
设置对话框勾选「危险主机操作」但未勾「主机管理」时,保存会清除危险开关并提示。
## 7. 错误码
沿用 P1–P7 的约定,新增 `-32009`:
| 码 | 含义 |
|---|---|
| `-32602` | 参数非法(含:目标多条匹配、字符无法用 CP936 表示) |
| `-32000` | 解析失败 / 客户端返回错误文本(`TOKEN_MACHINE_MSG`) |
| `-32001` | 超时(就绪 5 s / 列表 12 s / 会话 60 s) |
| `-32002` | 主机离线 |
| `-32003` | 设备忙(已有 MCP 会话在飞:单设备单飞行) |
| `-32004` | 发送失败 |
| `-32005` | 不支持(非 Windows 客户端;UDP/IPv6 断连) |
| `-32006` | 开关未开启 |
| `-32009` | **目标在最新快照中不存在**(调用方应刷新后重试) |
## 8. 已知限制
1. **token 数值碰撞**:机器响应 31–42 与 `COMMAND_KEYBOARD/AUDIO/SYSTEM/SHELL/…` 同值。
靠「先按子连接身份路由」解决——未绑定的子连接不会按 token 猜测。
2. **UI 争抢就绪包**:用户恰好在 MCP 请求期间点开同一对话框时,首包可能被 MCP 绑定,
界面对话框这次不弹(与 P7 的取舍一致),重试即可。
3. **5 s 墓碑**:MCP 异常结束后 5 s 内手动打开同一台主机的对话框可能被吞,重试即可。
4. **老客户端子连接 `clientID=0`**:靠 peer 兜底,仅在同 peer 唯一会话时绑定。
5. **权限**:`SetTcpEntry`、冻结/解冻、服务控制需要客户端管理员;失败按「未生效」如实返回。
6. **编码**:机器协议以 CP936 为主;任务 `name/path/exe` 为 UTF-8、`status` 为 GBK;
写回输入统一转 CP936。GBK 不可表示的字符明确报 `-32602`。
7. **`host_list_network_state` 只有 IPv4**:数据来自客户端自身的 `GetTcpTable` 视图,
与「连接管理」(`ConnectionInfo`,含 IPv6)不是同一份数据。
8. **`McpMachineDangerous` 只覆盖本轮高风险动作**;后续加入 kill/删除/卸载/注入时,
必须按 `McpMachine && McpMachineDangerous && !McpReadonly` 三层校验。
9. **`host_control_window {action:"hide"}` 是单向的**:客户端只枚举可见窗口,隐藏后该 hwnd
从快照中消失,再发 `restore` 会在发包前被 `-32009` 拦下(MFC 对话框同样无法再操作它)。
实测确认:`hide` 复核为 `state:"hidden"`,随后 `restore` 返回 `-32009`。
10. **`host_control_service {action:"pause"}` 依赖服务自身支持 PAUSE**:实测虚拟机上的
`Spooler` 下发 PAUSE 后状态仍为 `Running`,工具如实返回 `ok:false, reason:"unexpected_state"`
(不谎报成功)。`start/stop/continue/restart` 在同一台机器上均通过。
11. **开关只在进程启动时读取**(Release 版配置来自注册表 `HKCU\Software\YAMA\settings`,
不是 `Bin\settings.ini`);在「MCP设置」里改动 `McpMachine` / `McpMachineDangerous` /
`McpReadonly` 等必须重启服务端才生效。未重启时 `tools/list` 里看不到新工具,
直接调用返回 `-32006`。
## 9. 验证要点
- TLS:`RES_TLS=1` 的主机三个工具都返回 `tls:true`;老客户端 `false`。
- 路由:MCP 关闭时手动打开「主机管理」「连接管理」照常工作;
`host_list_favorites`(token 36,与键盘等命令同值)在飞时手动打开「进程管理」,
两边都不串包。
- 迟到包:强制就绪超时后,61/255 到达应被吸收且不弹对话框。
- 单飞行:同主机并发两个 host/connection 工具,第二个 `-32003`;两台主机并发都成功。
- 连接管理:与对话框逐条对比;断开后复核消失;UDP/IPv6 → `-32005`;过期四元组 → `-32009`。
- 10 个读工具:与 MFC 标签页对比行数、首末行、中文编码;空 tab 返回 `total:0`。
- 4 个写工具:freeze→thaw、窗口四动作、服务五动作、任务 run/stop;过期目标发包前 `-32009`。
- 回归:现有 27 个工具、终端、远程控制、文件传输、10 个 MFC 标签页行为不变。
- 资源:连续调用 20 次 host 工具,服务端无残留子连接。
+313
View File
@@ -0,0 +1,313 @@
# 传输层单向 TLS 加密设计(按需加密)
> 版本:v0.5 · 状态:**Go 服务端 + Windows 客户端已实现并验证;信任锚改存注册表;MFC 主控端(阶段 3)未施工** · 日期:2026-10-14
> 目标:让 YAMA 设备端口(TCP 6543)在继续兼容老客户端(明文/XOR)的同时,允许新客户端在拿到证书后按需开启**单向 TLS** 加密传输。
> 本期范围:**Go 服务端(`server/go`)+ Windows 客户端**;MFC 服务端(`server/2015Remote`)延后。
>
> 需求原文(三点,逐一对应下文):
> 1. 新客户端**默认不加密**,行为与老客户端完全一致;
> 2. 某些高要求场景,管理员「颁发一个证书给该客户端 + 重启」,该客户端即改走加密;
> 3. 服务端同一端口(6543)同时兼容明文与 TLS 两种客户端,老客户端零改动。
## 1. 目标与范围
### 目标
- 同一 `6543` 端口上,服务端自动区分「明文客户端」与「TLS 客户端」,按连接路由。
- 加密是**按部署、按客户端开关**的:证书(注册表值或文件)在 → TLS;证书不在 → 明文(与老客户端一致)。
- 老客户端(无证书概念)行为不变、零改动。
- 满足 Measure 1 的「传输层真加密 + 抗重放」目标(对 TLS 客户端而言)。
### 非目标(Non-goals,本次不做)
- 不做 **mTLS / 客户端证书**:单向 TLS 不验证客户端证书,客户端身份仍由隧道内的现有登录(`PwdHmac` V1 / `ECDSA` V2)承担。
- 不做传输层 PSK(`YAMA_TRANSPORT_KEY`)方案——本设计改用证书,更贴合「颁发证书」的运维模型。
- 不改应用层协议(flag 帧格式 / XOR / zstd),不做「TLS 内去掉 XOR」的二次精简(后续可选)。
- 不做加密开关的运行时热切换(证书只在客户端启动时读取一次,改配置需重启——这正是需求)。
- 不做 Linux / macOS / Android 客户端的 TLS 接入(本文以 Windows MFC 客户端为主,其余平台同样式跟进)。
- 不做 **MFC 服务端(`server/2015Remote`)的 TLS 接入**——本期只做 Go 服务端(`server/go`),MFC 主控端延后到阶段 3。
## 2. 现状与复用
### 2.1 当前传输(已核实)
服务端 TCP 传输链路:`server/go/server/server.go` `acceptLoop()`(329–360 行)`Accept` 后 `go handleConnection(conn)`;`handleConnection()`(363–425 行)读入 `ctx.InBuffer`,交给 `protocol.Parser`。
`server/go/protocol/parser.go` `Parse()`(51–85 行):
1. 可选剥离 HTTP-mask(`POST /...\r\n\r\n` 外壳,`common/mask.h` 的 `HttpMask`);
2. `parseHeader()`(88–140 行)调用 `CheckHead()` 识别协议;
3. `parsePacket()`(143–225 行)解头 + XOR 解码 + zstd 解压。
`server/go/protocol/header.go` `CheckHead()`(149–165 行)对前 12 字节依次尝试 8 种头混淆 × 4 种魔数,命中即得 `FlagType`:
| FlagType | 魔数 | 首字节 |
|---|---|---|
| FlagHell(4) | `HELL` | `H`=0x48 |
| FlagShine(1) | `Shine` | `S`=0x53 |
| FlagFuck(2) | `<<FUCK>>` | `<`=0x3C |
| FlagHello(3) | `Hello?` | `H`=0x48 |
| HTTP-mask | `POST ` | `P`=0x50 |
> 注意:上表「首字节」是**解密后**的魔数首字节。实际线上,客户端(`common/header.h` 的 `GetHead`)会用 `time() % 12` 随机选一个混淆方法对前 4 字节魔数加密(仅在 `superAdmin` 命中的 `HellEncoder` 路径;默认 `ProtocolEncoder` 直接发明文 `Shine`)。因此**原始首字节可能是任意值**,包括 `0x16`。这正是 TLS 检测不能只看前两字节、必须再加一字节判据的原因(见 §3.1)。
当前「加密」为 `codec.go` 的 `xorDecoder16`(XOR + 两轮伪随机交换,密钥是明文带内 1~2 字节)+ `header.go` 的 V0~V6 头混淆——**等于明文**。这正是 Measure 1 要解决的。
### 2.2 客户端登录(已核实,隧道内照常)
- V1:`client/KernelManager.cpp:1857` 从配置读 `settings/PwdHmac`(预计算摘要),服务端 `auth.go:240` `VerifyMessage(YAMA_PWD, passcode, hmacSig)` 校验。`YAMA_PWD` 只存在服务端,客户端只有摘要,不持有 `YAMA_PWD`。
- V2:`auth.go:188` ECDSA P-256 验签(`v2:BASE64`),客户端持私钥、服务端持公钥。
### 2.3 关键结论(本设计的基础)
**TLS 作为「透明传输包装」,应用层协议一行不改。** 即:
```
明文客户端: [TCP] = flag 帧 + XOR payload + zstd
TLS 客户端: [TCP][TLS] = { flag 帧 + XOR payload + zstd }
```
服务端 `parser.go`/`codec.go`/`header.go`/handler 全部不动;TLS 客户端解密后的字节流就是同一套协议。唯一新增的是**连接建立时的 TLS 检测与解包**。XOR 套在 TLS 里冗余但无害,保留它换来「应用协议零改动、老新客户端共用同一套代码」。
## 3. 总体方案
### 3.1 同端口共存 + 首字节检测
服务端在 `handleConnection` 开头(`Accept` 之后)偷看连接开头 6 字节:
- 命中 `0x16 0x03 … 0x01`(TLS 握手记录 + TLS 版本号 + 握手类型 ClientHello)→ 交给 `tls.Server` 解包;
- 其它 → 走现有明文路径。
**为何要看第 6 字节**:客户端会随机混淆魔数头(见 §2.1),所以明文连接的前两字节**可能**恰好是 `0x16 0x03`。但混淆只作用于前 4 字节魔数,字节 5 对混淆后的 `HELL` 头恒为 `0x00`,对明文 `Shine`/`POST` 变体是 ASCII 字符——**永远不会是 `0x01`**;而任何 TLS 握手记录里,字节 5 就是握手消息类型,ClientHello 恒为 `0x01`。于是 `0x16 0x03` 加 `b[5]==0x01` 三重判据让误判概率趋近于零。
```
accept
├─ 现有 MaxConnections / per-IP 限流(保持,先于 TLS 握手,廉价拒绝 + 抗握手 DoS)
├─ peek 3 字节
│ ├─ 0x16 0x03 → tls.Server(conn, tlsCfg)(惰性握手,首次 Read 触发)
│ └─ 其它 → 明文
└─ handleConnection(conn) // 不区分明文/TLS,tls.Conn 实现 net.Conn
```
### 3.2 客户端行为
客户端启动时检查「证书文件是否存在」:
- 不在 → 明文(与老客户端完全一致,默认即此);
- 在 → 所有出站 TCP 连接(主连接 + screen/terminal/file 子连接)统一走 TLS。
### 3.3 架构图
```
┌──────────── 被控端(客户端,无证书) ────────────┐
│ TCP ── flag+XOR+zstd ─────────────────────────► │ 明文
└───────────────────────────────────────────────────┘
┌──────────── 被控端(客户端,有证书) ────────────┐
│ TCP ── TLS ── { flag+XOR+zstd } ──────────────► │ 加密
└───────────────────────────────────────────────────┘
│
▼
┌──────────────────────┐
│ 服务端 6543 │
│ peek 首字节路由 │
│ ├─ 0x16 0x03 → TLS │
│ └─ 其它 → 明文 │
│ ── 同一套 parser/handler │
└──────────────────────┘
```
## 4. 证书模型(单向 TLS)
- 服务端持有一张**服务端证书 + 私钥**(可自签名,或由自建 CA 签发)。
- 客户端持有**信任锚证书**(CA 证书,或自签名服务端证书本身)用于在握手时校验服务端。
- 「颁发证书给某客户端」= 把信任锚证书投递到该客户端(**注册表值**,见 §6.1/§9.3)。证书是**共享的信任锚**(不是每个客户端一张唯一证书),「颁发」的本质是**决定给哪个客户端开加密**。
- 单向 TLS **不认证客户端身份**;客户端身份仍由隧道内的登录(V1 `PwdHmac` / V2 ECDSA)承担。
- 信任锚首选存注册表 `Software\<exehash>\settings\tls_cert`(REG_SZ 直接存 PEM 正文);兼容旧方式:`settings.ini` `[settings] tls_cert` 路径,或 exe 同目录 `yama-ca.pem` 文件。
## 5. 服务端改动
### 5.1 配置(`server/go/server/server.go` `Config`)
新增两个字段,均为证书/私钥文件路径;空 = 禁用 TLS(仅明文,向后兼容):
```go
TLSCertFile string // 服务端证书(PEM)
TLSKeyFile string // 服务端私钥(PEM)
```
`cmd/main.go` 读取环境变量(沿用现有 `YAMA_*` 命名):
```go
cfg.TLSCertFile = os.Getenv("YAMA_TLS_CERT")
cfg.TLSKeyFile = os.Getenv("YAMA_TLS_KEY")
```
仅当两者都非空才构建 `*tls.Config`;否则 `s.tlsCfg == nil`,`acceptLoop` 走纯明文。
### 5.2 `tls.Config`
```go
tlsCfg := &tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
// 单向 TLS:不设 ClientAuth / ClientCAs
}
```
### 5.3 `handleConnection` 检测 + 回放
标准 peek 回放:`bufio.Reader` 预读 6 字节,封装成 `bufferedConn`(实现 `net.Conn`,`Read` 委托给 `Reader`),判断后把已读字节一并交给目标。嗅探本身设了 `ReadTimeout` 截止,超时/EOF 则退回原始 conn 走明文,由读循环处理:
```go
func (s *Server) wrapTLS(conn net.Conn) net.Conn {
br := bufio.NewReader(conn)
_ = conn.SetReadDeadline(time.Now().Add(s.config.ReadTimeout)) // 嗅探受超时约束
hdr, err := br.Peek(6)
_ = conn.SetReadDeadline(time.Time{})
if err != nil {
return conn // 超时/EOF:走明文,交由读循环处理
}
bc := &bufferedConn{Conn: conn, r: br}
if isTLSClientHello(hdr) { // 0x16 0x03 且 b[5]==0x01
return tls.Server(bc, s.tlsCfg) // 握手惰性,首次 Read 触发
}
return bc
}
```
### 5.4 握手超时
`handleConnection` 首次 `conn.Read` 会触发 TLS 握手,而它已按 `ReadTimeout` 设了 `SetReadDeadline`,因此握手天然受 `ReadTimeout` 约束,无需额外机制。per-IP 限流(现有)继续在握手前生效,压制握手 DoS。
### 5.5 明确不动的部分
- `parser.go` / `codec.go` / `header.go`:**零改动**。
- `handleConnection` / `processData` / handler 栈:**零改动**(`tls.Conn` 满足 `net.Conn`)。
## 6. 客户端改动
### 6.1 证书检测
启动时(连接前)按优先级找信任锚:① 注册表 `Software\<exehash>\settings\tls_cert`(REG_SZ 存 PEM 正文)→ ② `settings.ini` `[settings] tls_cert` 路径 → ③ exe 同目录 `yama-ca.pem`。找到即走 TLS,否则明文。实现:`client/TlsChannel.cpp` 的 `ReadTrustAnchor()` + `TlsEnabled()`(`std::call_once` 惰性加载、线程安全、幂等)。
### 6.2 TLS 栈选型(已定:Schannel)
- **已选 Schannel(Windows 原生 SSPI)**:零第三方依赖/零额外 DLL 部署,`secur32.lib`/`crypt32.lib` 均为系统库(`secur32.lib` 已在 `CFFmpegH264Encoder.cpp:38` 链接)。
- 信任锚(PEM/DER 正文,来自注册表或文件)经 `CryptStringToBinaryA` 解码 → `CertCreateCertificateContext` → 内存 `HCERTSTORE`;握手后 `CertGetCertificateChain` 把服务端证书链到该信任锚,`dwErrorStatus == 0` 才放行(含时间有效性)。**严格钉扎**:链引擎用 `hExclusiveRoot` 只信任该 store,排除系统根库,否则公共 CA 签发的证书也能通过。**fail-closed**。
- 握手凭据:`SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_NO_DEFAULT_CREDS`,`grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT`(与 Go 端 `MinVersion: TLS 1.2` 对齐)。
- 单向 TLS:不提供客户端证书;客户端身份仍由隧道内登录承担。
### 6.3 连接层封装
在 socket 建立后、应用协议首包前插入 TLS 握手(`IOCPClient::ConnectServer`,`m_bConnected` 置位前);`ReceiveData`/`SendTo` 改走 `TlsChannel` 会话。所有出站连接(主连接 + 子连接)统一遵循 TLS 开关,因此子连接同样被加密——服务端按连接检测,天然支持。实现:`client/TlsChannel.{h,cpp}`,接入点 `client/IOCPClient.{h,cpp}`。
### 6.4 关键:无静默降级(fail-closed)
**证书文件存在但握手失败(证书不匹配 / 中间人)时,客户端必须报错并放弃连接,禁止回退到明文。** 否则攻击者可制造降级。这必须写进实现与测试。
### 6.5 实现要点:Schannel 流模式 `DecryptMessage` 的缓冲重组
Schannel 流模式(`ISC_REQ_STREAM`)下,`DecryptMessage` 会把输入的那段 `SECBUFFER_DATA`
**重组**为 4 段输出,而不是就地解密到原偏移:
| 索引 | 类型 | 内容 |
|---|---|---|
| `bufs[0]` | `SECBUFFER_STREAM_HEADER` | TLS 记录头(5) + 显式 nonce(8) |
| `bufs[1]` | `SECBUFFER_DATA` | **明文** |
| `bufs[2]` | `SECBUFFER_STREAM_TRAILER` | 认证标签 |
| `bufs[3]` | `SECBUFFER_EXTRA` | 下一条记录的剩余密文(如有) |
因此客户端 `Recv` 必须从 `bufs[1].pvBuffer`/`bufs[1].cbBuffer` 取明文、`EXTRA` 从 `bufs[3]`
取。若误用 `bufs[0]`(记录头+nonce)或从原缓冲首字节取数,会把 TLS 记录头 `17 03 03 …`
当作明文交给协议解析器(表现为 `Unknown header`)。`Send` 方向相反:`EncryptMessage` 用
`STREAM_HEADER/DATA/TRAILER` 三段布局,本就正确。这一处是联调阶段实际踩到的、唯一的方向性
不对称 bug,已修复。
## 7. 兼容矩阵
| 客户端 | 服务端行为 | 结果 |
|---|---|---|
| 老客户端(无证书概念) | 明文路径 | 与现状完全一致 |
| 新客户端 · 无证书 | 明文路径 | 与老客户端行为一致(默认) |
| 新客户端 · 有证书 | TLS 路径 | 全量加密(主 + 子连接) |
服务端 TLS 未配置(`YAMA_TLS_CERT/KEY` 为空)时,一切与现状一致,TLS 客户端握手自然失败(fail-closed)。
## 8. 安全考量
- **TLS 提供**:机密性、完整性、服务端身份(客户端校验)、抗重放(TLS record 序号 + nonce)。即对 TLS 客户端而言,Measure 1(真加密 + 防重放)达成。
- **TLS 不提供**(单向):客户端证书身份——仍由隧道内登录承担;对「未颁证客户端」不强制加密(这是本设计刻意保留的兼容性,也是薄弱点:部署安全性取决于最弱客户端)。
- **明文前导**:TLS ClientHello 前几字节明文(协议固有),仅暴露「这是 TLS 客户端」,不含业务数据;客户端不设 SNI(连接目标是 IP,无域名)。
- **子连接**:客户端统一走 TLS,screen/terminal/file 子连接一并加密;对应 Measure 2 的「源 IP 绑定」降级为纵深防御,不再是唯一防线。
- **证书轮换**:重签服务端证书后,需向已颁证客户端重新投递新信任锚(或在证书到期前提前过渡)。自签名建议 `-days 3650`,到期前统一更换。
- **协议强度**:`MinVersion` 固定 TLS 1.2+,套件用 Go 默认安全集(`tls.Config` 默认已排除弱套件)。
## 9. 部署与运维
### 9.1 生成证书
自签名(最简,客户端信任锚即 `yama-server.crt`):
```bash
openssl req -x509 -newkey rsa:2048 -nodes \
-keyout yama-server.key -out yama-server.crt \
-days 3650 -subj "/CN=yama-server"
```
或自建 CA + 签服务端证书(便于轮换,客户端信任锚为 `ca.crt`):
```bash
openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -days 3650 -subj "/CN=yama-ca"
openssl req -newkey rsa:2048 -nodes -keyout server.key -out server.csr -subj "/CN=yama-server"
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 3650
```
### 9.2 服务端
```bash
YAMA_TLS_CERT=/etc/yama/server.crt \
YAMA_TLS_KEY=/etc/yama/server.key \
./server_linux_amd64 ...
```
### 9.3 客户端「颁发 + 重启」
首选:把信任锚 PEM 正文写入注册表值 `Software\<exehash>\settings\tls_cert`(REG_SZ),重启客户端:
```powershell
$pem = Get-Content -Raw 'C:\path\yama-ca.pem'
New-Item -Path 'HKCU:\Software\<exehash>\settings' -Force | Out-Null
Set-ItemProperty -Path 'HKCU:\Software\<exehash>\settings' -Name 'tls_cert' -Value $pem -Type String
```
- `<exehash>` = 客户端 exe 全路径小写后的 FNV 哈希(`common/iniFile.h` 的 `GetRegistryName()`)。
- 客户端以服务(SYSTEM)运行时,注册表落在会话用户的 `HKEY_USERS\<SID>`(`GetCurrentUserRegistryKey()`)。
- REG_SZ 直接存 PEM 正文(含换行);客户端动态读取,不受 `iniFile::GetStr` 512 字节固定缓冲限制。
兼容旧方式:把信任锚复制到客户端目录并命名为 `yama-ca.pem`(或经 `settings.ini` `[settings] tls_cert` 指向),重启客户端。
移除注册表值(或删除文件)并重启即退回明文。**远程下发/撤销信任锚属后续工作,本期仅支持本地写注册表。**
## 10. 测试计划
1. **检测单元**:`isTLSClientHello` 对 `0x16 0x03 … 0x01`(TLS 1.2/1.3 ClientHello)/ `POST ` / `Shine` / 混淆 `HELL`(首两字节恰好 `0x16 0x03` 但 `b[5]==0x00`)/ 短于 6 字节 等判定的单测(已实现 `server/go/server/tls_test.go`)。
2. **TLS 未配置**:不设 `YAMA_TLS_*` → 纯明文,行为与现状一致。
3. **明文回归**:老客户端 + 新客户端(无证书)均走明文,登录/屏幕/终端/文件全链路不回归。
4. **TLS 加密**:新客户端(有证书)→ 握手成功,登录/屏幕/终端/文件子连接全部在 TLS 内跑通;抓包确认 payload 不可读。
5. **混合并发**:明文与 TLS 客户端同时在线,互不干扰。
6. **fail-closed**:客户端有证书但服务端证书不匹配 / 中间人 → 客户端报错断开,**不**回退明文。
7. **握手超时 / 限流**:恶意慢握手被 `ReadTimeout` + per-IP 限流压制。
## 11. 分期与回滚
- **阶段 1(Go 服务端,本期优先)**:`Config` + `tls.Config` + `acceptLoop` 检测回放;明文路径零改动。可独立上线、独立验证——用 `openssl s_client` 或 Go 测试客户端即可联调 TLS 链路,无需真实客户端配合。
- **阶段 2(Windows 客户端)**:证书检测 + TLS 栈 + fail-closed。
- **阶段 3(MFC 服务端 `server/2015Remote`,延后)**:与 Go 服务端同款的 TLS 检测 + 解包接入。设计稿见 `docs/TransportTLS_MFCServer_Design.md`。
- **回滚**:服务端清空 `YAMA_TLS_CERT/KEY` 即回到纯明文;客户端删除注册表 `tls_cert` 值(或 `yama-ca.pem` 文件)即回明文。
## 12. 待定问题
1. ~~客户端 TLS 栈最终选型~~ → **已定 Schannel**(见 §6.2,2026-10-13 落地)。
2. ~~信任锚文件固定名(`yama-ca.pem`)是否需可配置~~ → **已改为注册表 `tls_cert` 值优先、文件回退**(见 §6.1/§9.3,2026-10-14)。
3. 是否同步把「TLS 内去掉 XOR」列为后续精简项(当前保留 XOR,换取零协议改动)。
4. Linux / macOS / Android 客户端的 TLS 接入排期。
+280
View File
@@ -0,0 +1,280 @@
# MFC 服务端(server/2015Remote)单向 TLS 加密设计
> 版本:v0.3 · 状态:**已实施并验证(屏幕 + 终端联调通过)** · 日期:2026-10-15
> 上游依赖:`docs/TransportTLS_Design.md`(Go 服务端 + Windows 客户端,已实现并验证)。
> 本期范围:**MFC 服务端 `server/2015Remote` 的传输层加密**(加载证书+私钥、握手、加解密、新旧客户端并存)。
> 显式排除(本次不做,但须预埋接缝):① MFC 的 MCP 式配置 UI;② 「向在线主机下发是否启用加密传输」的指令;③ 客户端运行时热切换。
>
> **已拍板的三个决策(2026-10-14,见 §12)**:
> 1. 握手采用 **方案 A(专用短命阻塞线程)**;
> 2. 身份文件采用 **PEM + CNG(`CertPath` + `KeyPath`)**,与 Go 服务端共用同一对密钥;私钥须为 **PKCS#8**;
> 3. 配置 **新建 `[tls]` 节**(`Enabled` / `CertPath` / `KeyPath`)。
>
> 需求原文(已确认):
> 1. MFC 服务端有一个类似 MCP 的配置,可选启用传输层加密;启用时需指定一对密钥(证书 + 私钥);
> 2. 启用后,可向在线主机发送「是否启用加密传输」的指令 —— **UI 与新指令属后期内容**;
> 3. **新旧客户端都须支持**:同一端口同时兼容明文(老客户端)与 TLS(新客户端)。
## 1. 目标与范围
### 目标
- MFC 服务端在同一个 TCP 端口(6543)上,按连接自动区分「明文客户端」与「TLS 客户端」,路由到各自路径。
- TLS 客户端解密后的字节流 == 同一套应用协议(flag 帧 + XOR + zstd),**协议解析/解压/解码零改动**。
- 老客户端(无 TLS 概念)行为不变、零改动。
- 服务端「启用 TLS」是**配置驱动**的:未配证书 → 纯明文;配了证书 → 新旧并存。
### 非目标(Non-goals,本次不做)
- 不做 **mTLS / 客户端证书**:单向 TLS,客户端身份仍由隧道内登录(V1 `PwdHmac` / V2 `ECDSA`)承担。
- 不做「TLS 内去掉 XOR」的二次精简(与上游设计一致,保留 XOR 换取零协议改动)。
- 不做 **UI**:不新增配置对话框、不加「启用加密」复选框、不加证书/私钥路径选择控件。
- 不做 **「向在线主机下发启用/撤销加密」指令**:不下发信任锚、不发加密开关指令、不改客户端运行时状态。
- 不做 KCP/UDP 传输(`IOCPKCPServer`)的 TLS 接入(本期只做 TCP 设备端口;KCP 另行评估)。
## 2. 现状与复用(IOCP 数据流 + 四个接缝)
MFC 服务端 TCP 接收链路:`OnAccept`(`IOCPServer.cpp:1144`)`accept` 后 `AllocateContext`(`:1289`)分配 `CONTEXT_OBJECT`,绑定 IOCP,`PostRecv`(`:1268`)投递首个 `WSARecv`(`:1278`,收进 `wsaInBuf`→`szBuffer[PACKET_LENGTH]`,`:1215`)。收满后 `HandleIO(IORead)`(`:746`)→ `OnClientReceiving`(`:892`)→ `ParseReceivedData`(`:796`)。
原始 socket 字节在整套流程里各只有**一个入口**和**一个出口**,这是 TLS 能做成「过滤器」而非「改写」的根本原因:
| 接缝 | 位置 | 作用 |
|---|---|---|
| ① 收包咽喉点 | `IOCPServer.cpp:805` `InCompressedBuffer.WriteBuffer(szBuffer, dwTrans)` | 原始字节进入协议解析的**唯一**位置(`szBuffer` 全文件仅此一处消费) |
| ② 发包咽喉点 | `IOCPServer.cpp:1000` `WSASend(...wsaOutBuffer...)` | `OutCompressedBuffer` 上行的**唯一**位置 |
| ③ 嗅探点 | `OnAccept`→`PostRecv`;`OnClientInitializing`(`:790`)现为空桩 `return TRUE` | 首次收到数据处,可挂 ClientHello 判定 |
| ④ 状态字段 | `Server.h:332` `CONTEXT_OBJECT`(`szBuffer`/`wsaInBuf`/`InCompressedBuffer`/`InDeCompressedBuffer`/`OutCompressedBuffer`/`Parser` 等,`:359-398`) | 新增 TLS 会话指针 + 标志位 |
**关键结论(本设计的基础)**:TLS 作为「透明传输包装」,加解密插在 ①② 两处,③ 做新旧分流,④ 加一个 per-connection 状态。`ParseReceivedData` 内的 `Parse`/解压/`Decode`、`WriteContextData` 内的 `Encode`/压缩/掩码,**全部不动**。这与上游 Go 服务端「`tls.Conn` 满足 `net.Conn`、parser 零改动」是同一策略(见上游 §2.3)。
## 3. 总体方案
### 3.1 按连接嗅探(与 Go 服务端同款判定)
首次收到数据后,只看 `szBuffer` 前 6 字节:
- 命中 `0x16 0x03 … 0x01`(TLS 握手记录 + TLS 版本号 + ClientHello)→ TLS 路径;
- 其它 → 明文路径(老客户端透明,一行不改)。
判据与 Go 端 `isTLSClientHello`(`0x16 0x03` 且 `b[5]==0x01`)**完全一致**,理由也一致:客户端会随机混淆魔数头(见上游 §2.1),明文前两字节可能恰为 `0x16 0x03`,但字节 5 对混淆头恒非 `0x01`,故三重判据误判率趋近于零。
### 3.2 数据路径 = 条件过滤器
```
OnAccept → PostRecv
│
首次 IORead 完成(嗅探 szBuffer[0..5])
┌─────┴─────┐
明文(其它) TLS(0x16 0x03 .. 0x01)
│ │
ParseReceivedData TLS 握手(AcceptSecurityContext)
(现状,零改动) │ 成功
│ ▼
│ 握手后:IORead → DecryptMessage → 明文 → InCompressedBuffer.WriteBuffer
│ 发送:OutCompressedBuffer → EncryptMessage → WSASend
└────────── 同一套 Parse/Encode/解压/压缩 ──────────┘
```
明文连接与握手后的 TLS 连接,下游共用同一套 `Parse`/`Encode`/解压/压缩。唯一差别是 ①② 两处各多一个 `if (tls) 加解密 else 直通` 分支。
## 4. 配置设计(含未来 UI/指令的预埋)
### 4.1 配置面(本次定键名,UI 后期加)
MFC 服务端配置走 `THIS_CFG`(`config`/`iniFile`,`GetInt`/`GetStr(section,key,default)`,见 `2015Remote.cpp:481-543` 用法)。新增 `[tls]` 节,三键(**已拍板 PEM + CNG**,见 §5.6、§12):
```ini
[tls]
Enabled = 0 ; 是否启用传输层加密(0/1)
CertPath = "" ; 服务端证书路径(PEM,-----BEGIN CERTIFICATE-----)
KeyPath = "" ; 服务端私钥路径(PEM PKCS#8,-----BEGIN PRIVATE KEY-----)
```
三键都是**短字符串路径**,不落 PEM 正文,故不受 `iniFile::GetStr` 512 字节固定缓冲限制(该限制只在「存 PEM 正文」时才成问题,客户端已为此单独绕行,见上游 §6.1)。
### 4.2 未来不返工的四条硬约束(本次预埋)
1. **配置单一访问器**:TLS 开关与身份路径只经一个中心对象 `ServerTlsIdentity` 暴露:`Load(config&)` / `IsEnabled()` / `IsReady()` / `IsLoadError()` / `Cred()`。未来 UI 改配置、指令查询「我当前是否加密态」都走这同一个入口,禁止代码里散落 `GetInt("Enabled")`。
2. **身份加载做成可重入,绝不用 `std::call_once`**:`ServerTlsIdentity::Load(config&)` 每次调用重新加载证书+私钥并重建凭据句柄。本次启动时调一次;未来「轮换证书 / 开关切换」可再调。这是对客户端 `TlsEnabled()` 用 `std::call_once` 一次读死、不可热切换(见上游 §6.1 与 `docs/tls-cert-push-revoke-deferred` 相关记忆)的**主动规避**。
3. **「我是否 TLS 就绪」是全局只读态,与每条连接的 TLS 态分开**:`ServerTlsIdentity::IsEnabled()`(全局配置态)/ `IsReady()`(身份加载成功)与 per-connection 的「该连接是否走 TLS/握手是否完成」是两个概念。未来指令/UI 只碰前者。
4. **按连接嗅探本身就是为混合上线准备的**:服务端开 TLS 后,没切换的旧主机照样明文连、已切换的走 TLS。未来「下发开启指令」只改客户端行为,服务端传输层不用动。
## 5. 服务端改动详述
### 5.1 `CONTEXT_OBJECT` 字段(`Server.h`,加 4 项)
```cpp
// 每连接传输层状态(单向 TLS,见 §5.2);跨线程(握手线程写 TLS_Ready,工作线程读)用 atomic 保序
enum ServerTlsState {
TLS_Unclassified = 0, // 尚未收到足够字节判定(缓冲 tlsPreClassify)
TLS_Plain = 1, // 明文客户端,直通现有解析路径
TLS_Handshaking = 2, // TLS 客户端,握手线程阻塞 AcceptSecurityContext 中
TLS_Ready = 3, // TLS 握手完成,收包解密 / 发包加密
};
ServerTlsSession* tls = nullptr; // 懒分配;握手完成后承载加解密状态
std::atomic<int> tlsState{ TLS_Unclassified }; // ServerTlsState
std::vector<BYTE> tlsPreClassify; // 分类前缓冲的首批字节(嗅探 ClientHello 头)
bool bSendPending = false; // 发送在途抑制(见 §5.5);受 SendLock 保护
void FreeTls(); // delete tls; tls = NULL;(定义在 ServerTlsSession.cpp,避免本头拖入 Schannel)
```
生命周期见 §5.7:`InitMember` 时复位 `tlsState`/`tlsPreClassify`/`tls`,析构 / 回收时 `FreeTls()`。
### 5.2 嗅探与预分类缓冲
首次 `IORead` 完成时(`OnClientReceiving` 开头,`ParseReceivedData` 之前)判定:
- `dwTrans >= 6`:看 `szBuffer[0..5]`,一次定死明文/TLS;
- `dwTrans < 6`(TCP 把 ClientHello 头分片,极罕见但须正确):把这 `dwTrans` 字节追加进 `tlsPreClassify`,`PostRecv` 继续收,直到攒够 6 字节再判定。判定后清空 `tlsPreClassify`。
明文连接判定后,把 `tlsPreClassify`(如有)+ 本次 `szBuffer` 一并按现状喂给 `ParseReceivedData`,保证分片字节不丢。
### 5.3 握手(已拍板方案 A)
服务端握手需 `AcceptSecurityContext`(Schannel 入站),与客户端 `InitializeSecurityContext`(出站)**不通用**,需新写。数据阶段的 `DecryptMessage`/`EncryptMessage` 是同步缓冲变换,与异步收发包天然兼容,两个方案都复用。
**方案 A:专用握手线程(阻塞式,已实施)**
- 首次 `IORead` 判定为 TLS 后,此刻 `WSARecv` 已因完成回调结束、socket 上**无 pending overlapped 操作**,可安全转交一个短命线程做阻塞握手。
- 线程内用**与客户端 `TlsChannel::Handshake` 同型的阻塞 Schannel 循环**跑 `AcceptSecurityContext`(`TlsChannel.cpp` 已证明该模式可靠),把已收到的 ClientHello 字节(`tlsPreClassify`,可能是分片)作为初始输入,后续 handshake 航程走阻塞 `recv`/`send`;握手前把 socket 切回阻塞态并设 15s 收发超时。
- 成功 → `tlsState.store(TLS_Ready)`,`PostRecv` 投递首个 `IORead`,回到 IOCP 正常流程;失败 → 关连接(fail-closed,§8)。
- 优点:复用客户端已验证的阻塞 Schannel 代码形态、状态最少;缺点:每个 TLS 连接多一个短命线程(仅在握手期间存活)。
**方案 B:异步状态机(无额外线程,更贴合 IOCP)**
- 握手由 `IORead`/`IOWrite` 完成回调推进:每次回调喂一段握手字节给 `AcceptSecurityContext`,按其返回(`SEC_I_CONTINUE_NEEDED` → 继续收/发;`SEC_E_OK` → 完成)驱动下一动作。
- 优点:无额外线程、与现有 IOCP 事件循环同构;缺点:状态管理明显更重,需把「握手待收/待发/完成」编码进 per-connection 状态。
**已拍板(2026-10-14)**:采用 **方案 A**(简单、复用客户端阻塞 Schannel 经验、风险低)。方案 B 留作后续压测发现短命线程开销不可接受时再演进;二者切换只影响 §5.3,不影响 ①②④ 的过滤器设计。
### 5.4 收包解密(接缝 ①,`ParseReceivedData` 之上)
`OnClientReceiving` 里,明文与 TLS 分叉:
```cpp
int st = ContextObject->tlsState.load(std::memory_order_acquire);
if (st == TLS_Ready) {
// 1) 把 szBuffer[0..dwTrans] 喂给 DecryptMessage,得到明文 plain、长度 n
// 2) 处理 SECBUFFER_EXTRA:多余密文留存到 tls 对象内部缓冲(m_raw),下次续解(见上游 §6.5)
// 3) plain 为空(记录分片未齐)→ PostRecv 继续收;否则 ContextObject->InCompressedBuffer.WriteBuffer(plain.data(), n);
} else {
ContextObject->InCompressedBuffer.WriteBuffer(szBuffer, dwTrans); // 现状,零改动
}
```
即 ① 从「一行直写」变成「条件分支」,明文侧原文不动。解密缓冲重组(`STREAM_HEADER/DATA/TRAILER/EXTRA` 四段布局)已在上游 §6.5 踩过坑、给出正确写法,服务端直接沿用(`ServerTlsSession::Decrypt` 内维护 `m_raw` 续解缓冲)。
### 5.5 发包加密(接缝 ②,`OnClientPreSending` 之上)
`OutCompressedBuffer` 是「可能残留上一轮未发完密文」的可变缓冲:异步 `WSASend` 在途时,新明文由 `WriteContextData` 追加在尾部。因此 `OnClientPreSending`(`IOCPServer.cpp`)**只加密本次新追加的尾部明文**,而非整个缓冲:
1. 追加前记 `oldLen = OutCompressedBuffer.GetBufferLength()`;
2. `WriteContextData` 追加新明文后,`plainLen = totalLen - oldLen`,只对 `GetBuffer(oldLen)` 起的 `plainLen` 字节调用 `tls->Encrypt` 得密文 `wire`;
3. `TruncateBuffer(oldLen)` 回退尾部明文(**不用 `ClearBuffer`**:后者会 `DeAllocateBuffer`,可能 `VirtualFree` 正在被在途 `WSASend` 引用的底层内存),再 `WriteBuffer(wire)` 追加新密文。
这样 `OutCompressedBuffer` 始终保持一串合法 TLS 记录。若把整个缓冲重新加密,会把旧密文二次加密,客户端解密后得到「旧 TLS 记录」→ `Unknown header 17 03 03`。
**发送唤醒的并发抑制(`bSendPending`)**:`OnClientPreSending` 每次 `Send2Client` 若都 `PostQueuedCompletionStatus(IOWrite, 0)`,则每个 `OnClientPostSending(ctx, 0)` 都会对整个缓冲再发起一次 `WSASend`;背靠背小包(终端 `resize → COMMAND_NEXT → resize`)会触发多个并发 `WSASend` 读到同一段可变内存,产出重复/错位密文(客户端 `DecryptMessage` 失败,`WSAGetLastError()` 残留 `6001 = ERROR_DECRYPTION_FAILED`)。故新增 `bool bSendPending`(受 `SendLock` 保护):仅在 `!bSendPending` 时投递 IOWrite 并置位;`OnClientPostSending` 在缓冲排空(最后一个 `WSASend` 完成)或发送失败时清零;`InitMember` 复用对象池时复位。在途 `WSASend` 的完成回调会看到排空后仍残留的新数据并继续发送,无需再投递。后续 `OnClientPostSending` 的部分发送循环照旧——它发送的已是密文字节,逐段 `WSASend` 天然成立。
### 5.6 证书/私钥加载(Schannel 入站凭据,已拍板 PEM+CNG)
`AcquireCredentialsHandle` 取 `SCHANNEL_CRED`(入站)时需一个**已绑定私钥的证书**。已拍板用 **PEM + CNG**(与 Go 端 `YAMA_TLS_CERT/KEY` 同构,服务端与 Go 共用同一对密钥):
- **证书**:`CryptStringToBinaryA(CRYPT_STRING_ANY)` 把 PEM 解为 DER → `CertCreateCertificateContext(X509_ASN_ENCODING)`。
- **私钥(仅 PKCS#8)**:Schannel 入站凭据要求私钥是**「能按名重开」的持久化键**——`NCryptImportKey` 产出的是匿名临时键,绑定 `CERT_NCRYPT_KEY_HANDLE_PROP_ID` 后 Schannel 仍拿不到(`AcquireCredentialsHandle` 返回 `SEC_E_NO_CREDENTIALS` `0x8009030e`)。因此:
1. **导入临时键并导出裸 BLOB**:`NCryptOpenStorageProvider(MS_KEY_STORAGE_PROVIDER)` + `NCryptImportKey(NCRYPT_PKCS8_PRIVATE_KEY_BLOB)` 得临时键(`hProvider` 不能传 NULL——默认提供者解析实测返回 `NTE_INVALID_HANDLE` `0x80090026`,须显式打开 KSP);再 `NCryptSetProperty(NCRYPT_EXPORT_POLICY_PROPERTY=ALLOW_PLAINTEXT_EXPORT|ALLOW_EXPORT)` 后 `NCryptExportKey(BCRYPT_RSAFULLPRIVATE_BLOB)` 得裸 RSA 私钥 BLOB。
2. **写入持久化键**:`NCryptCreatePersistedKey(BCRYPT_RSA_ALGORITHM, "YamaServerTlsKey", AT_KEYEXCHANGE, NCRYPT_OVERWRITE_KEY_FLAG)` → `NCryptSetProperty(BCRYPT_RSAFULLPRIVATE_BLOB)` → `NCryptFinalizeKey`。`NCryptSetProperty` 只认裸 BLOB、不认 PKCS#8(直接设 `NCRYPT_PKCS8_PRIVATE_KEY_BLOB` 实测 `NTE_NOT_SUPPORTED` `0x80090029`)。
3. **按名绑定**:`CertSetCertificateContextProperty(CERT_KEY_PROV_INFO_PROP_ID, CRYPT_KEY_PROV_INFO{ pwszContainerName="YamaServerTlsKey", pwszProvName=MS_KEY_STORAGE_PROVIDER, dwProvType=0, dwKeySpec=AT_KEYEXCHANGE })`。Schannel 经 `CryptAcquireCertificatePrivateKey` 按名在 KSP 里重开该键。
- **入站凭据**:`AcquireCredentialsHandleA("Microsoft Unified Security Protocol Provider", SECPKG_CRED_INBOUND, &SCHANNEL_CRED{ cCreds=1, paCred=&cert, grbitEnabledProtocols=SP_PROT_TLS1_2_SERVER, dwFlags=NO_DEFAULT_CREDS })`。
关键点:**私钥必须是 PKCS#8**(`-----BEGIN PRIVATE KEY-----`);若拿到的是 PKCS#1(`-----BEGIN RSA/EC PRIVATE KEY-----`),用
`openssl pkcs8 -topk8 -nocrypt -in server.key -out server.key` 转换。证书上下文生命周期交给进程级 `g_cert`,持久化键句柄交给 `g_persistedKey`;`FreeIdentity` 里按序 `FreeCredentialsHandle` → `CertFreeCertificateContext` → `NCryptDeleteKey`(`NCryptDeleteKey` 会同时释放句柄,勿再 `NCryptFreeObject`)。
### 5.7 生命周期(context 池化复用)
`CONTEXT_OBJECT` 经 `AllocateContext`(`:1311`)从 `m_ContextFreePoolList` **复用**、`InitMember`(`:1314`)复位。故 TLS 状态必须在 `InitMember` 里清空 `tlsPreClassify`、`FreeTls()`、复位 `tlsState`(`store(TLS_Unclassified)`)与 `bSendPending=false`(避免上次连接残留的在途标志抑制新连接发送),并在 `~CONTEXT_OBJECT`(`Server.h:346`)`FreeTls()`。否则「前一个 TLS 连接的状态漏给下一个明文连接」会直接导致解析错乱。这是唯一需要跨过 `InitMember`/析构两处做的生命周期接线。
### 5.8 明确不动的部分
- `ParseReceivedData` 内的 `Parse`/解压/`Decode`、`WriteContextData` 内的 `Encode`/压缩/掩码:**零改动**。
- `HeaderParser` / `context`(`context.h`)协议层:**零改动**。
- `OnAccept` / `PostRecv` / `AllocateContext` / `RemoveStaleContext` 主结构:**零改动**(仅新增 TLS 分支与字段复位)。
- KCP / UDP 传输(`IOCPKCPServer`):**零改动**(不在本期范围)。
## 6. 新老客户端兼容矩阵
| 客户端 | 服务端 TLS 状态 | 服务端行为 | 结果 |
|---|---|---|---|
| 老客户端(无 TLS 概念) | 未配置 | 明文路径 | 与现状完全一致 |
| 老客户端 | 已配置 | 嗅探判为明文 → 明文路径 | 与现状完全一致(透明) |
| 新客户端 · 无证书 | 未配置 / 已配置 | 明文路径 | 与老客户端一致(默认) |
| 新客户端 · 有证书 | 已配置 | 嗅探判为 TLS → 握手 → 加密 | 全量加密 |
| 新客户端 · 有证书 | 未配置 | 嗅探判为 TLS → 无证书可握手 → **关连接(fail-closed)** | 拒绝(见 §8) |
## 7. 与未来「下发/撤销指令 + UI」的接缝
本次不实现 UI 与指令,但通过 §4.2 四条约束预留干净接缝。二者未来的分工与依赖:
- **UI**:在 MFC 配置对话框(类 MCP)里加「启用传输加密 + 指定一对密钥」,写入 `[tls]` 三键 → 调 `ServerTlsIdentity::Load(config&)` 重载 → `IsEnabled()` 即时生效。**只碰 §4.2 第 1/2 点,不碰传输层。**
- **「向在线主机下发启用/撤销加密」指令**:服务端侧是一条新的命令通道(遍历在线连接广播),客户端侧是**运行时热切换**——收到指令后热加载/删除信任锚、断开重连走新通道。
**必须先说破的跨端依赖**:这条指令真正的大头在**客户端**——客户端目前读 `tls_cert` 是进程启动读一次、`std::call_once`、**不可热切换**(见上游 §6.1 及 `docs/tls-cert-push-revoke-deferred` 记忆)。因此「下发/撤销」落地时,客户端要先把 `TlsEnabled()` 的一次读死改成「指令驱动的热重载」。**这与本次服务端传输层正交**——只要 §4.2 第 2/3 点把服务端状态做成可重载、可中心化查询,未来就能干净接上,无需回头改本次代码。
## 8. 安全考量
- **TLS 提供**:机密性、完整性、服务端身份(客户端校验)、抗重放(TLS record 序号 + nonce)。对 TLS 客户端而言,Measure 1(真加密 + 防重放)达成,与 Go 端一致。
- **TLS 不提供**(单向):客户端身份——仍由隧道内登录承担。
- **服务端 fail-closed**:服务端收到 TLS ClientHello 但自身未配证书/身份加载失败 → **直接关连接**,禁止把 TLS 字节当协议去解析(否则新客户端握手失败重试 + 服务端狂报解析错)。与客户端 fail-closed 语义对称(见上游 §6.4)。
- **握手 DoS**:TLS 握手有 CPU 开销,须受 per-IP 限流(现有)保护;方案 A 的短命握手线程还须加握手超时(`SSPI` 握手期间设 socket 收发超时,超时关连接)。
- **部署顺序**(关键):**MFC 服务端证书必须与客户端 CA 一起(或先于)上线**。否则「新客户端(已钉 CA)连旧 MFC 服务端(无证书)」→ 客户端 fail-closed 直接拒绝,表现为「升级客户端后连不上老服务端」。这是设计使然,部署/文档须写明。
- **私钥安全**:服务器私钥只在握手时由 Schannel 内部签名使用(ECDHE)或解密预主密钥(RSA),不参与业务数据加解密;私钥文件应最小权限存放、不落日志。真正的长期秘密(CA 私钥)平时离线,仅在签发/轮换服务器证书时使用。
## 9. 部署与运维
生成服务端身份(与 Go 端 §9.1 的 `server.crt` + `server.key` 完全同一对密钥;私钥须 PKCS#8):
```bash
# 若私钥是 PKCS#1(-----BEGIN RSA/EC PRIVATE KEY-----),先转 PKCS#8:
openssl pkcs8 -topk8 -nocrypt -in server.key -out server.key
```
MFC 服务端配置(直接指向与 Go 端相同的 PEM 文件):
```ini
[tls]
Enabled = 1
CertPath = C:\YAMA\server.crt
KeyPath = C:\YAMA\server.key
```
重启 MFC 服务端即生效(本次仅启动时读一次,热切换待未来 UI)。删除 `[tls]` 节或置 `Enabled=0` 即回纯明文。
## 10. 测试计划
1. **嗅探单元**:`0x16 0x03 .. 0x01`(TLS 1.2/1.3 ClientHello)/ 明文首包 / 混淆头(首两字节 `0x16 0x03` 但 `b[5]!=0x01`)/ 首包 <6 字节分片 的判定。
2. **TLS 未配置**:`Enabled=0` 或无证书 → 纯明文,行为与现状一致(老 + 新无证书客户端回归)。
3. **明文回归**:老客户端全链路(登录/屏幕/终端/文件)不回归。
4. **TLS 加密**:新客户端(有证书)连 MFC 服务端 → 握手成功,登录/屏幕/终端/文件子连接全部在 TLS 内跑通;抓包确认 payload 不可读。
5. **混合并发**:明文与 TLS 客户端同时在线,互不干扰(对应未来过渡期)。
6. **fail-closed 双向**:① 服务端未配证书但收到 ClientHello → 关连接不误解析;② 客户端有证书但服务端证书不匹配 → 客户端断开不回退明文。
7. **握手超时 / 限流**:恶意慢握手被超时 + per-IP 限流压制。
8. **连接复用**:一条 TLS 连接断开后,context 回池再被明文连接复用,TLS 状态已复位、无泄漏(§5.7)。
## 11. 分期与回滚
- **本期(MFC 服务端传输加密,已实施)**:`ServerTlsIdentity`(PEM+CNG 加载)+ `CONTEXT_OBJECT` 字段(`tlsState` 枚举)+ 嗅探/预分类 + 握手(方案 A)+ ①收包解密 + ②发包加密 + 生命周期复位。可独立验证——用 `openssl s_client` 或复用 Go 端测试客户端联调,无需真实客户端配合。
- **后续 A(UI)**:MCP 式配置对话框 + 重载 `ServerTlsIdentity`。
- **后续 B(下发/撤销指令)**:服务端指令通道 + **客户端热切换**(客户端 `TlsEnabled()` 改指令驱动,见 §7)。
- **回滚**:服务端 `[tls] Enabled=0` 即回纯明文,无需改客户端(客户端无证书时本就明文)。
## 12. 已拍板决策与仍待定问题
**已拍板(2026-10-14)**:
1. **握手方案**:采用 **方案 A(专用阻塞线程)**,见 §5.3。
2. **身份文件格式**:采用 **PEM + CNG(`CertPath` + `KeyPath`,私钥 PKCS#8)**,与 Go 服务端共用同一对密钥,见 §5.6。
3. **配置节名**:新建 **`[tls]` 节**,键 `Enabled` / `CertPath` / `KeyPath`,见 §4.1。
**仍待定**:
1. **KCP/UDP 传输是否也要 TLS**:本期不含,另行评估。
2. **MFC 的 MCP 式配置 UI**:显式排除,见 §7;落地时只碰 §4.2 第 1/2 点。
+10 -8
View File
@@ -88,14 +88,16 @@ bool ScreenHandler::init()
m_height = (int)CGDisplayPixelsHigh(m_displayID);
}
// Get logical point dimensions (what CGEvent uses)
// NSScreen provides logical dimensions
NSScreen* mainScreen = [NSScreen mainScreen];
if (mainScreen) {
NSRect frame = [mainScreen frame];
m_logicalWidth = (int)frame.size.width;
m_logicalHeight = (int)frame.size.height;
} else {
// 逻辑尺寸必须取自「实际抓屏的那块屏」(CGMainDisplayID)。CGEvent 的鼠标坐标是
// 全局显示坐标(points),而我们发给服务端的是这块屏的编码像素。
// [NSScreen mainScreen] 取的是菜单栏/焦点窗口所在屏:合盖外接显示器时它仍可能是
// 已停用的内置屏(例如 13" MacBook Air 的 1470x956),与抓屏的外置屏(1280x1024)
// 不是同一块屏。用错尺寸会让每个注入点变成 p * (logical / encode),表现为从左上角
// 起线性增长、且 x/y 各轴独立的鼠标偏移(见 ScreenHandler::OnReceive 的换算)。
CGRect bounds = CGDisplayBounds(m_displayID);
m_logicalWidth = (int)(bounds.size.width + 0.5);
m_logicalHeight = (int)(bounds.size.height + 0.5);
if (m_logicalWidth <= 0 || m_logicalHeight <= 0) {
// Fallback: use physical dimensions
m_logicalWidth = m_width;
m_logicalHeight = m_height;
+7 -4
View File
@@ -271,11 +271,14 @@ static std::string normalizeExePathLower(const std::string& path)
// Get screen resolution
static std::string getScreenResolution()
{
NSScreen* mainScreen = [NSScreen mainScreen];
if (mainScreen) {
NSRect frame = [mainScreen frame];
// 用主显示器的全局显示坐标(points),与 CGEvent 注入坐标同一空间,也和
// ScreenHandler 抓屏所用的 CGMainDisplayID 保持一致。
// [NSScreen mainScreen] 在合盖接外置显示器时仍可能返回内置屏(如 1470x956),
// 上报后会让服务端以为主机分辨率是内置屏尺寸。
CGRect bounds = CGDisplayBounds(CGMainDisplayID());
if (bounds.size.width > 0 && bounds.size.height > 0) {
return [NSString stringWithFormat:@"1:%dx%d",
(int)frame.size.width, (int)frame.size.height].UTF8String;
(int)(bounds.size.width + 0.5), (int)(bounds.size.height + 0.5)].UTF8String;
}
return "0:0x0";
}
Binary file not shown.
File diff suppressed because it is too large. Load diff
+34 -9
View File
@@ -43,18 +43,30 @@ typedef struct DllInfo {
typedef struct FileTransformCmd {
CLock Lock;
std::map<std::string, uint64_t> CmdTime;
void PutCmd(const std::string& str)
// md5 -> (目标客户端源 IP, 登记时间)。源 IP 绑定:只有与 PutCmd 登记时同源 IP 的
// 子连接才能消费该 md5,防止异常客户端在别的 IP 上冒用文件传输指令。
std::map<std::string, std::pair<std::string, uint64_t>> CmdInfo;
void PutCmd(const std::string& str, const std::string& peerIP)
{
Lock.Lock();
CmdTime[str] = time(0);
CmdInfo[str] = std::make_pair(peerIP, (uint64_t)time(0));
Lock.Unlock();
}
bool PopCmd(const std::string& str, int timeoutSec = 10)
bool PopCmd(const std::string& str, const std::string& peerIP, int timeoutSec = 10)
{
Lock.Lock();
bool valid = CmdTime.find(str) != CmdTime.end() && time(0) - CmdTime[str] < timeoutSec;
CmdTime.erase(str);
auto it = CmdInfo.find(str);
if (it == CmdInfo.end()) {
Lock.Unlock();
return false;
}
uint64_t now = (uint64_t)time(0);
bool expired = now - it->second.second >= (uint64_t)timeoutSec;
bool matched = it->second.first == peerIP;
// 过期或成功消费才删除;源 IP 不匹配(冒用)保留,让合法客户端在 TTL 内仍可取回。
bool valid = !expired && matched;
if (expired || valid)
CmdInfo.erase(it);
Lock.Unlock();
return valid;
}
@@ -109,6 +121,13 @@ bool SupportsFileTransferV2(context* ctx);
// 找不到主连接或老客户端:默认 CP936(覆盖 95% 简中/英语 ASCII 老客户端)。
UINT GetClientEncoding(context* ctx);
// 获取客户端「进程名/路径」编码 (CP_UTF8 或 936)。
// 与 GetClientEncoding 不同:Windows 客户端的进程名/路径由 A 接口
// (Process32FirstA / QueryFullProcessImageNameA 等)生成,恒为客户端系统
// ANSI(简中=GBK/936),不随 CLIENT_CAP_UTF8 转 UTF-8;仅 LNX/MAC 走 UTF-8。
// 与 McpServer::BuildListProcesses 的判定保持一致。
UINT GetProcessListEncoding(context* ctx);
// 服务端待续传的传输信息
struct PendingTransferV2 {
uint64_t clientID;
@@ -216,6 +235,9 @@ public:
VOID AddList(CString strIP, CString strAddr, CString strPCName, CString strOS, CString strCPU, CString strVideo, CString strPing,
CString ver, CString startTime, std::vector<std::string>& v, CONTEXT_OBJECT* ContextObject);
VOID ShowMessage(CString strType, CString strMsg);
// 消息中含 UTF-8(如地理位置)时使用:消息列经 LVM_SETITEMTEXTW 写宽字符串,
// 避免 UTF-8 在 ANSI 日志列表里被按 GBK 显示成乱码(Böblingen → B枚blingen)。
VOID ShowMessageW(const CStringW& strType, const CStringW& strMsg);
VOID CreatStatusBar();
VOID CreateToolBar();
VOID CreateNotifyBar();
@@ -351,9 +373,8 @@ public:
// ===== 文件传输速度配置([transfer] 节,ChunkKb / DurationMs) =====
// 主控端 UI 偏好,持久化走 THIS_CFG。上传方向读 THIS_CFG(重启主控端生效);
// 下载方向经 CMD_FILE_SPEED 下发到被控端(下次打开文件管理/远程桌面会话生效)。
// 下载方向随 MasterSettings 下发(新连接登录即收到,改档后立即推送给在线客户端)。
void OnFileTransferSpeed(); // 高级→文件传输速度
void SendFileSpeedCommand(); // 把当前档位经主连接下发给被控端
void SendThumbnailRequest(class context* ctx);// 发一次缩略图请求
void CacheThumbnail(uint64_t clientID, const BYTE* jpeg, size_t bytes);
void ClearThumbnailCacheEntry(uint64_t clientID);
@@ -432,7 +453,7 @@ public:
bool IsDllRequestLimited(const std::string& ip);
void RecordDllRequest(const std::string& ip);
CMenu m_MainMenu;
CBitmap m_bmOnline[69];
CBitmap m_bmOnline[75];
uint64_t m_superID;
std::map<HWND, CDialogBase *> m_RemoteWnds;
FileTransformCmd m_CmdList;
@@ -522,6 +543,8 @@ public:
afx_msg void OnExperimentFileManager();
afx_msg void OnExperimentPrivateScreen();
afx_msg void OnExperimentDrawingBoard();
afx_msg void OnExperimentTlsEnable();
afx_msg void OnExperimentTlsDisable();
afx_msg void OnOnlineDelete();
afx_msg void OnOnlineUpdate();
afx_msg void OnAbout();
@@ -619,6 +642,7 @@ public:
afx_msg void OnMsglogLoginNotify();
afx_msg void OnMsglogBanIP();
afx_msg void OnMsglogUnbanIP();
afx_msg void OnMsglogWhitelistIP();
afx_msg void OnOnlineAddWatch();
afx_msg void OnNMCustomdrawOnline(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnOnlineRunAsAdmin();
@@ -687,6 +711,7 @@ public:
afx_msg void OnCancelShare();
afx_msg void OnWebRemoteControl();
afx_msg void OnMcpSettings();
afx_msg void OnTlsCertificate();
afx_msg void OnConnectionManage();
afx_msg void OnProxyPortAutorun();
afx_msg void OnScreenpreviewLoop();
@@ -328,7 +328,11 @@
<ClInclude Include="KeyBoardDlg.h" />
<ClInclude Include="LangManager.h" />
<ClInclude Include="McpServer.h" />
<ClInclude Include="McpChat.h" />
<ClInclude Include="McpInternal.h" />
<ClInclude Include="McpMachine.h" />
<ClInclude Include="McpSettingsDlg.h" />
<ClInclude Include="TlsCertificateDlg.h" />
<ClInclude Include="NetworkDlg.h" />
<ClInclude Include="NotifyConfig.h" />
<ClInclude Include="NotifyManager.h" />
@@ -350,6 +354,7 @@
<ClInclude Include="ScreenSpyDlg.h" />
<ClInclude Include="SearchBarDlg.h" />
<ClInclude Include="Server.h" />
<ClInclude Include="ServerTlsSession.h" />
<ClInclude Include="ServicesDlg.h" />
<ClInclude Include="ConnectionsDlg.h" />
<ClInclude Include="SettingDlg.h" />
@@ -395,7 +400,11 @@
<ClCompile Include="WebService.cpp" />
<ClCompile Include="HostJson.cpp" />
<ClCompile Include="McpServer.cpp" />
<ClCompile Include="McpChat.cpp" />
<ClCompile Include="McpInternal.cpp" />
<ClCompile Include="McpMachine.cpp" />
<ClCompile Include="McpSettingsDlg.cpp" />
<ClCompile Include="TlsCertificateDlg.cpp" />
<ClCompile Include="..\..\client\MemoryModule.c">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader>
@@ -457,6 +466,7 @@
<ClCompile Include="ZstaPickerDlg.cpp" />
<ClCompile Include="IOCPKCPServer.cpp" />
<ClCompile Include="IOCPServer.cpp" />
<ClCompile Include="ServerTlsSession.cpp" />
<ClCompile Include="IOCPUDPServer.cpp" />
<ClCompile Include="IPHistoryDlg.cpp" />
<ClCompile Include="KeyBoardDlg.cpp" />
@@ -576,6 +586,8 @@
<Image Include="res\Bitmap\Shutdown.bmp" />
<Image Include="res\Bitmap\Snapshot.bmp" />
<Image Include="res\Bitmap\SpeedDesktop.bmp" />
<Image Include="res\Bitmap\TlsDisable.bmp" />
<Image Include="res\Bitmap\TlsEnable.bmp" />
<Image Include="res\Bitmap\Trial.bmp" />
<Image Include="res\Bitmap\Trigger.bmp" />
<Image Include="res\Bitmap\unauthorize.bmp" />
@@ -21,6 +21,7 @@
<ClCompile Include="InputDlg.cpp" />
<ClCompile Include="ZstaPickerDlg.cpp" />
<ClCompile Include="IOCPServer.cpp" />
<ClCompile Include="ServerTlsSession.cpp" />
<ClCompile Include="KeyBoardDlg.cpp" />
<ClCompile Include="Loader.c" />
<ClCompile Include="proxy\ProxyConnectServer.cpp" />
@@ -88,7 +89,11 @@
<ClCompile Include="TriggerSettingsDlg.cpp" />
<ClCompile Include="HostJson.cpp" />
<ClCompile Include="McpServer.cpp" />
<ClCompile Include="McpChat.cpp" />
<ClCompile Include="McpInternal.cpp" />
<ClCompile Include="McpMachine.cpp" />
<ClCompile Include="McpSettingsDlg.cpp" />
<ClCompile Include="TlsCertificateDlg.cpp" />
<ClCompile Include="CClientLog.cpp" />
<ClCompile Include="CActivityDialog.cpp" />
<ClCompile Include="LogSearchBar.cpp" />
@@ -155,6 +160,7 @@
</ClInclude>
<ClInclude Include="IOCPUDPServer.h" />
<ClInclude Include="Server.h" />
<ClInclude Include="ServerTlsSession.h" />
<ClInclude Include="CDrawingBoard.h" />
<ClInclude Include="IOCPKCPServer.h" />
<ClInclude Include="..\..\common\ikcp.h" />
@@ -200,7 +206,11 @@
<ClInclude Include="PreviewTipWnd.h" />
<ClInclude Include="TriggerSettingsDlg.h" />
<ClInclude Include="McpServer.h" />
<ClInclude Include="McpChat.h" />
<ClInclude Include="McpInternal.h" />
<ClInclude Include="McpMachine.h" />
<ClInclude Include="McpSettingsDlg.h" />
<ClInclude Include="TlsCertificateDlg.h" />
<ClInclude Include="CClientLog.h" />
<ClInclude Include="CActivityDialog.h" />
<ClInclude Include="LogSearchBar.h" />
@@ -355,5 +365,7 @@
<Image Include="res\Bitmap\FileManager.bmp" />
<Image Include="res\Bitmap\PrivacyShield.bmp" />
<Image Include="res\Bitmap\DrawingBoard.bmp" />
<Image Include="res\Bitmap\TlsEnable.bmp" />
<Image Include="res\Bitmap\TlsDisable.bmp" />
</ItemGroup>
</Project>
+17
View File
@@ -337,3 +337,20 @@ VOID CBuffer::CommitWrite(ULONG writtenSize)
m_Ptr += writtenSize;
LeaveCriticalSection(&m_cs);
}
// 截断缓冲区到指定有效长度(仅回退写指针,不移动/释放底层内存)。有效长度指「当前读取
// 位置之后的字节数」,与 GetBufferLength 一致;请求值超出现有有效长度时收敛到现有长度。
VOID CBuffer::TruncateBuffer(ULONG effectiveLen)
{
EnterCriticalSection(&m_cs);
if (m_Base == NULL) {
LeaveCriticalSection(&m_cs);
return;
}
ULONG totalDataLen = (ULONG)(m_Ptr - m_Base);
ULONG cur = (totalDataLen > m_ulReadOffset) ? (totalDataLen - m_ulReadOffset) : 0;
if (effectiveLen > cur)
effectiveLen = cur;
m_Ptr = m_Base + m_ulReadOffset + effectiveLen;
LeaveCriticalSection(&m_cs);
}
+5
View File
@@ -130,6 +130,11 @@ public:
// 确认写入完成,更新内部指针
VOID CommitWrite(ULONG writtenSize);
// 截断缓冲区到指定有效长度(仅回退写指针,不移动/释放底层内存)。用于「尾部明文替换为
// 密文」:TLS 下 OutCompressedBuffer 追加明文后需换回密文,用此接口避免 ClearBuffer 的
// DeAllocateBuffer 释放正在被异步 WSASend 引用的底层内存。
VOID TruncateBuffer(ULONG effectiveLen);
protected:
PBYTE m_Base;
PBYTE m_Ptr;
+21 -11
View File
@@ -258,6 +258,7 @@ void CBuildDlg::DoDataExchange(CDataExchange* pDX)
DDX_Control(pDX, IDC_EDIT_DOWNLOAD_URL, m_EditDownloadUrl);
DDX_Text(pDX, IDC_EDIT_DOWNLOAD_URL, m_sDownloadUrl);
DDV_MaxChars(pDX, m_sDownloadUrl, 255);
DDX_Control(pDX, IDC_COMBO_INSTALL_LOC, m_ComboLocation);
}
@@ -426,7 +427,7 @@ void CBuildDlg::OnBnClickedOk()
m_ComboCompress.SetCurSel(CLIENT_COMPRESS_NONE);
m_SliderClientSize.SetPos(0);
}
int startup = Startup_DLL;
int startup = Startup_DLL, installFlag = m_ComboLocation.GetCurSel();
CString file;
CString targetDir;
switch (index) {
@@ -434,7 +435,7 @@ void CBuildDlg::OnBnClickedOk()
case IndexTestRun_MemDLL:
case IndexTestRun_InjSC:
file = "TestRun.exe";
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "Client Demo" : m_sInstallDir);
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "Client Demo" : m_sInstallDir, installFlag);
typ = index == IndexTestRun_DLL ? CLIENT_TYPE_DLL : CLIENT_TYPE_MEMDLL;
startup = std::map<int, int> {
{IndexTestRun_DLL, Startup_DLL},{IndexTestRun_MemDLL, Startup_MEMDLL},{IndexTestRun_InjSC, Startup_InjSC},
@@ -444,14 +445,14 @@ void CBuildDlg::OnBnClickedOk()
break;
case IndexGhost:
file = "ghost.exe";
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "Windows Ghost" : m_sInstallDir);
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "Windows Ghost" : m_sInstallDir, installFlag);
typ = CLIENT_TYPE_ONE;
szBuffer = ReadResource(is64bit ? IDR_GHOST_X64 : IDR_GHOST_X86, dwFileSize,
is64bit ? ResFileName::GHOST_X64 : ResFileName::GHOST_X86);
break;
case IndexGhostMsc:
file = "ghost.exe";
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "Windows Ghost" : m_sInstallDir);
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "Windows Ghost" : m_sInstallDir, installFlag);
typ = CLIENT_TYPE_ONE;
startup = Startup_GhostMsc;
szBuffer = ReadResource(is64bit ? IDR_GHOST_X64 : IDR_GHOST_X86, dwFileSize,
@@ -459,7 +460,7 @@ void CBuildDlg::OnBnClickedOk()
break;
case IndexTestRunMsc:
file = "TestRun.exe";
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "Client Demo" : m_sInstallDir);
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "Client Demo" : m_sInstallDir, installFlag);
typ = CLIENT_TYPE_MEMDLL;
startup = Startup_TestRunMsc;
szBuffer = ReadResource(is64bit ? IDR_TESTRUN_X64 : IDR_TESTRUN_X86, dwFileSize,
@@ -467,14 +468,14 @@ void CBuildDlg::OnBnClickedOk()
break;
case IndexServerDll:
file = "ServerDll.dll";
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "ServerDll" : m_sInstallDir);
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "ServerDll" : m_sInstallDir, installFlag);
typ = CLIENT_TYPE_DLL;
szBuffer = ReadResource(is64bit ? IDR_SERVERDLL_X64 : IDR_SERVERDLL_X86, dwFileSize,
is64bit ? ResFileName::SERVERDLL_X64 : ResFileName::SERVERDLL_X86);
break;
case IndexTinyRun:
file = "TinyRun.dll";
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "TinyRun" : m_sInstallDir);
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "TinyRun" : m_sInstallDir, installFlag);
typ = CLIENT_TYPE_SHELLCODE;
szBuffer = ReadResource(is64bit ? IDR_TINYRUN_X64 : IDR_TINYRUN_X86, dwFileSize,
is64bit ? ResFileName::TINYRUN_X64 : ResFileName::TINYRUN_X86);
@@ -497,7 +498,7 @@ void CBuildDlg::OnBnClickedOk()
}
case IndexGhostSystem:
file = "ghost.exe";
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "Windows Ghost" : m_sInstallDir);
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "Windows Ghost" : m_sInstallDir, installFlag);
typ = CLIENT_TYPE_ONE;
startup = Startup_GhostSystem;
szBuffer = ReadResource(is64bit ? IDR_GHOST_X64 : IDR_GHOST_X86, dwFileSize,
@@ -505,14 +506,14 @@ void CBuildDlg::OnBnClickedOk()
break;
case IndexTestRunSystem:
file = "TestRun.exe";
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "Client Demo" : m_sInstallDir);
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "Client Demo" : m_sInstallDir, installFlag);
typ = CLIENT_TYPE_MEMDLL;
startup = Startup_TestRunSystem;
szBuffer = ReadResource(is64bit ? IDR_TESTRUN_X64 : IDR_TESTRUN_X86, dwFileSize,
is64bit ? ResFileName::TESTRUN_X64 : ResFileName::TESTRUN_X86);
break;
case OTHER_ITEM: {
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "YamaDll" : m_sInstallDir);
targetDir = GetInstallDirectory(m_sInstallDir.IsEmpty() ? "YamaDll" : m_sInstallDir, installFlag);
m_OtherItem.GetWindowTextA(file);
typ = -1;
if (file != _TR("未选择文件")) {
@@ -547,6 +548,7 @@ void CBuildDlg::OnBnClickedOk()
memcpy(g_ConnectAddress.szGroupName, m_sGroupName, m_sGroupName.GetLength());
memcpy(g_ConnectAddress.installDir, m_sInstallDir, m_sInstallDir.GetLength());
memcpy(g_ConnectAddress.installName, m_sInstallName, m_sInstallName.GetLength());
g_ConnectAddress.installFlag = installFlag;
if (!g_ConnectAddress.IsValid()) {
SAFE_DELETE_ARRAY(szBuffer);
@@ -781,7 +783,8 @@ BOOL CBuildDlg::OnInitDialog()
// 多语言翻译 - Static控件
SetDlgItemText(IDC_STATIC_OTHER_ITEM, _TR("未选择文件"));
SetDlgItemText(IDC_STATIC_PAYLOAD, _TR("载荷类型:"));
SetDlgItemText(IDC_STATIC_PAYLOAD2, _TR("安装目录:"));
SetDlgItemText(IDC_STATIC_LOCATION, _TR("安装目录:"));
SetDlgItemText(IDC_STATIC_PAYLOAD2, _TR("子目录:"));
SetDlgItemText(IDC_STATIC_PAYLOAD3, _TR("程序名称:"));
SetDlgItemText(IDC_STATIC_DOWNLOAD, _TR("下载地址(默认本机):"));
SetDlgItemText(IDC_STATIC_BUILD_SERVICE, _TR("服务程序:"));
@@ -852,6 +855,13 @@ BOOL CBuildDlg::OnInitDialog()
m_ComboCompress.InsertStringL(CLIENT_COMP_SC_AES_OLD_UPX, "SC AES<Old> + UPX");
m_ComboCompress.SetCurSel(CLIENT_COMPRESS_SC_AES_OLD);
m_ComboLocation.InsertStringL(0, "ProgramData");
m_ComboLocation.InsertStringL(1, "ProgramFiles - Admin");
m_ComboLocation.InsertStringL(2, "SystemRoot - Admin");
m_ComboLocation.InsertStringL(3, "APPDATA");
m_ComboLocation.InsertStringL(4, "LOCALAPPDATA");
m_ComboLocation.SetCurSel(0);
m_ComboPayload.InsertStringL(Payload_Self, "载荷写入当前程序尾部");
m_ComboPayload.InsertStringL(Payload_Raw, "载荷写入单独的二进制文件");
m_ComboPayload.InsertStringL(Payload_BMP, "载荷写入 BMP 格式图片");
+1
View File
@@ -107,4 +107,5 @@ public:
// 选 Linux / macOS 客户端时禁用 Windows-only 选项(架构 / 加壳 / 高级 group)
void EnableWindowsOnlyControls(BOOL enable);
CComboBox m_ComboLocation;
};
+26 -4
View File
@@ -5,6 +5,7 @@
#include "afxdialogex.h"
#include "CClientListDlg.h"
#include "2015Remote.h"
#include <string>
// CClientListDlg 对话框
@@ -93,6 +94,27 @@ static CString GetFieldValue(const ClientValue& val, GroupField field)
}
}
// 程序路径与地理位置均以 UTF-8 存储(见 AddList / client 的 RES_FILE_PATH、RES_CLIENT_LOC),
// 这里用 LVM_SETITEMTEXTW 直接写宽字符串,绕开 ANSI→CP_ACP 回转,
// 即使服务端运行在非中文 ACP(如德语)上,中文/带变音符的文本也能正常显示(与窗口/进程管理同法)。
static void SetUtf8ItemText(CListCtrl& list, int iItem, int iSubItem, const char* sz)
{
std::wstring w;
if (sz && sz[0]) {
int wlen = MultiByteToWideChar(CP_UTF8, 0, sz, -1, NULL, 0);
if (wlen > 1) {
w.resize(wlen - 1);
MultiByteToWideChar(CP_UTF8, 0, sz, -1, &w[0], wlen);
}
}
LVITEMW lv = {};
lv.mask = LVIF_TEXT;
lv.iItem = iItem;
lv.iSubItem = iSubItem;
lv.pszText = w.empty() ? const_cast<LPWSTR>(L"") : &w[0];
::SendMessageW(list.GetSafeHwnd(), LVM_SETITEMTEXTW, (WPARAM)iItem, (LPARAM)&lv);
}
// 比较两个客户端的指定列,返回 <0, 0, >0
static int CompareClientByColumn(const std::pair<ClientKey, ClientValue>& a,
const std::pair<ClientKey, ClientValue>& b,
@@ -294,12 +316,12 @@ void CClientListDlg::DisplayClients()
m_ClientList.SetItemText(nItem, COL_ID, strID);
m_ClientList.SetItemText(nItem, COL_NOTE, val.Note);
m_ClientList.SetItemText(nItem, COL_COMPUTER_NAME, CString(val.ComputerName));
m_ClientList.SetItemText(nItem, COL_LOCATION, val.Location);
SetUtf8ItemText(m_ClientList, nItem, COL_LOCATION, val.Location);
m_ClientList.SetItemText(nItem, COL_IP, val.IP);
m_ClientList.SetItemText(nItem, COL_OS, val.OsName);
m_ClientList.SetItemText(nItem, COL_INSTALL_TIME, val.InstallTime);
m_ClientList.SetItemText(nItem, COL_LAST_LOGIN, val.LastLoginTime);
m_ClientList.SetItemText(nItem, COL_PROGRAM_PATH, CString(val.ProgramPath));
SetUtf8ItemText(m_ClientList, nItem, COL_PROGRAM_PATH, val.ProgramPath);
m_ClientList.SetItemText(nItem, COL_LEVEL, strLevel);
m_ClientList.SetItemText(nItem, COL_AUTH, strAuth);
m_ClientList.SetItemData(nItem, (DWORD_PTR)key);
@@ -346,12 +368,12 @@ void CClientListDlg::DisplayClients()
m_ClientList.SetItemText(nItem, COL_ID, strID);
m_ClientList.SetItemText(nItem, COL_NOTE, val.Note);
m_ClientList.SetItemText(nItem, COL_COMPUTER_NAME, CString(val.ComputerName));
m_ClientList.SetItemText(nItem, COL_LOCATION, val.Location);
SetUtf8ItemText(m_ClientList, nItem, COL_LOCATION, val.Location);
m_ClientList.SetItemText(nItem, COL_IP, val.IP);
m_ClientList.SetItemText(nItem, COL_OS, val.OsName);
m_ClientList.SetItemText(nItem, COL_INSTALL_TIME, val.InstallTime);
m_ClientList.SetItemText(nItem, COL_LAST_LOGIN, val.LastLoginTime);
m_ClientList.SetItemText(nItem, COL_PROGRAM_PATH, CString(val.ProgramPath));
SetUtf8ItemText(m_ClientList, nItem, COL_PROGRAM_PATH, val.ProgramPath);
m_ClientList.SetItemText(nItem, COL_LEVEL, strLevel);
m_ClientList.SetItemText(nItem, COL_AUTH, strAuth);
m_ClientList.SetItemData(nItem, (DWORD_PTR)key);
+49
View File
@@ -151,6 +151,54 @@ void CDlgFileSend::UpdateProgress(CString file, const FileProgressInfo& info)
PostMessageA(WM_UPDATEFILEPROGRESS, (WPARAM)new CString(file), (LPARAM)new FileProgressInfo(info));
}
// 将字节/秒格式化为人类可读的速度串(如 "5.3M/s"、"320K/s"、"800B/s")
static CStringW FormatSpeed(double bps)
{
CStringW s;
if (bps >= 1024.0 * 1024.0)
s.Format(L"%.1fM/s", bps / (1024.0 * 1024.0));
else if (bps >= 1024.0)
s.Format(L"%.0fK/s", bps / 1024.0);
else
s.Format(L"%.0fB/s", bps);
return s;
}
// 累计字节并周期性刷新标题中的速度(如 "发送文件 - 5.3M/s")
void CDlgFileSend::UpdateTitleWithSpeed(uint64_t dataLength)
{
m_ullTotalBytes += dataLength;
ULONGLONG now = GetTickCount64();
// 首帧:用 Unicode API 捕获当前标题作为基础部分(可能已被 V2/C2C 覆盖为 "接收文件 (V2)" 等),
// 并建立采样基准;此时尚无速度可显示。
if (!m_bBaseTitleCaptured) {
WCHAR wBase[128] = { 0 };
::GetWindowTextW(m_hWnd, wBase, 128);
m_strBaseTitle = wBase;
m_bBaseTitleCaptured = true;
m_ullLastTick = now;
m_ullLastBytes = m_ullTotalBytes;
return;
}
ULONGLONG dt = now - m_ullLastTick;
if (dt < 200) return; // 采样间隔未到,仅累积字节
uint64_t delta = m_ullTotalBytes - m_ullLastBytes;
double speed = dt ? (double)delta * 1000.0 / (double)dt : 0.0;
m_dSpeedBps = (m_dSpeedBps == 0.0) ? speed : m_dSpeedBps * 0.6 + speed * 0.4; // 轻度平滑
m_ullLastTick = now;
m_ullLastBytes = m_ullTotalBytes;
// 基础标题(Unicode)+ ASCII 速度后缀,全程 Unicode API,避免非中文系统上 ANSI 消息按系统 ACP 解码乱码
CStringW title = m_strBaseTitle;
title += L" - ";
title += FormatSpeed(m_dSpeedBps);
::SetWindowTextW(m_hWnd, title);
}
void CDlgFileSend::FinishFileSend(BOOL succeed)
{
if (!GetSafeHwnd()) return;
@@ -170,6 +218,7 @@ LRESULT CDlgFileSend::OnUpdateFileProgress(WPARAM wParam, LPARAM lParam)
SetDlgItemText(IDC_STATIC_CURRENTINDEX, status);
SetDlgItemText(IDC_STATIC_CURRENT_FILE, *pFile);
m_Progress.SetPos((int)percent);
UpdateTitleWithSpeed(pInfo->dataLength);
// 只在第一次显示时置顶,后续更新不抢焦点
if (!IsWindowVisible()) {
+10
View File
@@ -51,6 +51,14 @@ public:
BOOL m_bTargetOffline = FALSE; // C2C目标已离线,已发送取消包
enum { IDD = IDD_DIALOG_FILESEND };
// 传输速度统计(用于标题实时显示速度,如 "发送文件 - 5.3M/s")
CStringW m_strBaseTitle; // 标题基础部分("发送文件"/"接收文件 (V2)" 等,Unicode),首帧进度时捕获
bool m_bBaseTitleCaptured = false;
uint64_t m_ullTotalBytes = 0; // 累计传输字节
uint64_t m_ullLastBytes = 0;
ULONGLONG m_ullLastTick = 0; // 上次速度采样时刻 (ms)
double m_dSpeedBps = 0.0; // 平滑后的速度 (B/s)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
@@ -59,6 +67,8 @@ protected:
afx_msg LRESULT OnUpdateFileProgress(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnFinishFileSend(WPARAM wParam, LPARAM lParam);
void UpdateTitleWithSpeed(uint64_t dataLength); // 累计字节并周期性刷新标题速度
public:
CProgressCtrl m_Progress;
virtual BOOL OnInitDialog();
+12 -1
View File
@@ -79,6 +79,18 @@ protected:
{
CDialog::OnInitDialog();
// 非中文系统上 MBCS 对话框模板的中文会被系统 ACP 转成 "?",TranslateDialog
// 拿到的是已乱码文本无法还原,故在此显式设置(参照 NotifySettingsDlg)。
// 均经 _TR 支持多语言翻译。
SetWindowText(_TR("文件传输速度"));
SetDlgItemText(IDC_FSPEED_HINT, _TR("拖动滑块设置文件传输速度:"));
SetDlgItemText(IDC_FSPEED_LABEL_SLOWEST, _TR("最慢"));
SetDlgItemText(IDC_FSPEED_LABEL_DEFAULT, _TR("默认"));
SetDlgItemText(IDC_FSPEED_LABEL_UNLIMITED, _TR("不限速"));
SetDlgItemText(IDC_FSPEED_RESET, _TR("恢复默认"));
SetDlgItemText(IDOK, _TR("确定"));
SetDlgItemText(IDCANCEL, _TR("取消"));
SendDlgItemMessage(IDC_FSPEED_SLIDER, TBM_SETRANGE, TRUE,
MAKELONG(0, FILE_SPEED_TIER_COUNT - 1));
SendDlgItemMessage(IDC_FSPEED_SLIDER, TBM_SETPAGESIZE, 0, 1);
@@ -86,7 +98,6 @@ protected:
SendDlgItemMessage(IDC_FSPEED_SLIDER, TBM_SETPOS, TRUE, TierIndexFor(m_chunkKb, m_durMs));
UpdateLabel();
TranslateDialog(this);
return TRUE;
}
+21 -5
View File
@@ -563,6 +563,17 @@ void CLicenseDlg::OnLicenseRenewal()
if (defaultHostNum <= 0) defaultHostNum = 100;
int defaultQuota = lic.PendingQuota > 0 ? lic.PendingQuota : 1;
// 判断当前授权是否已过期。续期从“今天”起算:客户端收到 days 后按
// getDateStr(0) + days 签发新授权(见 CMD_AUTHORIZATION 处理)。
// 若从已过去的原到期日加天数,预设日期会落在过去,下发时被
// SendPendingRenewal 钳制成 1 天,实际到期日与预设/提示不一致。
CTime now = CTime::GetCurrentTime();
CTime today(now.GetYear(), now.GetMonth(), now.GetDay(), 0, 0, 0);
CString strToday;
strToday.Format(_T("%04d%02d%02d"), now.GetYear(), now.GetMonth(), now.GetDay());
bool expired = currentExpireDate.length() == 8 &&
currentExpireDate < std::string(CT2A(strToday));
// 格式化当前过期日期显示
CString strCurrentExpire;
if (currentExpireDate.length() == 8) {
@@ -570,6 +581,9 @@ void CLicenseDlg::OnLicenseRenewal()
currentExpireDate.substr(0, 4).c_str(),
currentExpireDate.substr(4, 2).c_str(),
currentExpireDate.substr(6, 2).c_str());
if (expired) {
strCurrentExpire += _L(" (已过期,续期从今天起算)");
}
} else {
strCurrentExpire = _TR("当前到期: 未知");
}
@@ -595,15 +609,13 @@ void CLicenseDlg::OnLicenseRenewal()
return;
}
// 计算新的过期日期 (从原到期日期开始加天数)
CTime baseTime;
if (currentExpireDate.length() == 8) {
// 计算新的过期日期:未过期从原到期日加天数;已过期从今天起算。
CTime baseTime = today;
if (!expired && currentExpireDate.length() == 8) {
int year = atoi(currentExpireDate.substr(0, 4).c_str());
int month = atoi(currentExpireDate.substr(4, 2).c_str());
int day = atoi(currentExpireDate.substr(6, 2).c_str());
baseTime = CTime(year, month, day, 0, 0, 0);
} else {
baseTime = CTime::GetCurrentTime(); // 无法解析时用当前日期
}
CTimeSpan span(days, 0, 0, 0);
CTime newExpireTime = baseTime + span;
@@ -635,6 +647,10 @@ void CLicenseDlg::OnLicenseRenewal()
CString msg;
msg.FormatL("已预设续期至: %s\n并发连接数: %d\n配额: %d (支持%d台机器续期)\n客户端上线时将自动下发新授权",
strPending, hostNum, quota, quota);
if (expired) {
msg += _T("\n");
msg += _L("(原授权已过期,续期从今天起算)");
}
MessageBox(msg, _TR("预设成功"), MB_ICONINFORMATION);
}
}
+44 -2
View File
@@ -6,8 +6,35 @@
BEGIN_MESSAGE_MAP(CHeaderCtrlEx, CHeaderCtrl)
ON_NOTIFY_REFLECT(HDN_BEGINTRACKA, &CHeaderCtrlEx::OnBeginTrack)
ON_NOTIFY_REFLECT(HDN_BEGINTRACKW, &CHeaderCtrlEx::OnBeginTrack)
ON_WM_ERASEBKGND()
END_MESSAGE_MAP()
BOOL CHeaderCtrlEx::OnEraseBkgnd(CDC* pDC)
{
// 表头的 WM_PAINT 只画到最后一列,最后一列(如 TLS)右边那条空带
// (CListCtrlEx 算列宽时预留的 20px)要靠背景擦除上色。
// 之前整个跳过擦除,平时看着没事;最小化再还原时窗口内容被丢弃,
// 这条空带就再没人画,成了黑色且不会刷新(表头那行右端一条黑块)。
// 这里只补空带、不擦整行:整行擦除会在每次表头重画时先闪一帧底色。
CRect rcClient;
GetClientRect(&rcClient);
int used = 0;
const int nCols = GetItemCount();
if (nCols > 0) {
RECT rcLast = { 0 };
if (GetItemRect(nCols - 1, &rcLast)) {
used = rcLast.right; // 最后一列的右边界 = 表头已画到的位置
}
}
if (used < rcClient.right) {
CRect rcGap(used, 0, rcClient.right, rcClient.bottom);
pDC->FillSolidRect(&rcGap, ::GetSysColor(COLOR_3DFACE));
}
return TRUE;
}
void CHeaderCtrlEx::OnBeginTrack(NMHDR* pNMHDR, LRESULT* pResult)
{
LPNMHEADER pNMHeader = reinterpret_cast<LPNMHEADER>(pNMHDR);
@@ -139,8 +166,12 @@ void CListCtrlEx::AdjustColumnWidths()
for (int i = 0; i < (int)m_Columns.size(); i++) {
if (m_Columns[i].Visible) {
int width = (visiblePercent > 0) ? (int)(totalWidth * m_Columns[i].Percent / visiblePercent) : 0;
SetColumnWidth(i, width);
} else {
// 只改真正变化的列:SetColumnWidth 会让表头重画一次,OnSize 每次都跑这里,
// 逐列无条件设置就会在拖窗口时反复重画表头。
if (GetColumnWidth(i) != width) {
SetColumnWidth(i, width);
}
} else if (GetColumnWidth(i) != 0) {
SetColumnWidth(i, 0); // 隐藏列
}
}
@@ -160,6 +191,11 @@ void CListCtrlEx::SetColumnVisible(int nCol, BOOL bVisible)
if (m_Columns[nCol].CanHide || bVisible) { // 不允许隐藏的列只能设为可见
m_Columns[nCol].Visible = bVisible;
AdjustColumnWidths();
// 列数变化后完整重绘(含背景擦除),否则最后一列右侧会残留旧列残影。
// 不带 RDW_ALLCHILDREN:表头是列表的子窗口,列宽一变它自己就会重画,
// 强制跟着擦一帧只会在表头那行闪一下。
ScopedEraseBkgnd scope(*this);
RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW);
}
}
}
@@ -230,6 +266,12 @@ void CListCtrlEx::ToggleColumnVisibility(int nColumn)
// 重新调整列宽
AdjustColumnWidths();
// 列数变化后完整重绘(含背景擦除),否则最后一列(TLS 等)右侧会残留旧列残影。
// 与 OnSize 中 needRefresh 分支相同的处理:临时放行背景擦除 + 全量重绘。
// 表头不在其中:列宽变化会触发它自己重画,跟着擦一帧只会闪一下。
ScopedEraseBkgnd scope(*this);
RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW);
}
void CListCtrlEx::LoadColumnVisibility()
+1
View File
@@ -23,6 +23,7 @@ public:
protected:
DECLARE_MESSAGE_MAP()
afx_msg void OnBeginTrack(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
};
// CListCtrlEx - 支持列显示/隐藏功能的列表控件
+1 -1
View File
@@ -250,7 +250,7 @@ bool UpdateLicenseAuthorization(const std::string& deviceID, const std::string&
}
// IP 列表管理常量
#define MAX_IP_HISTORY 500 // 最多保留 几 个不同的 IP
#define MAX_IP_HISTORY 1000 // 最多保留 几 个不同的 IP
// 解析 IP 列表字符串为 vector<pair<IP, 时间戳>>
// 格式: "192.168.1.1|260218, 10.0.0.1|260215" (yyMMdd)
+19 -1
View File
@@ -89,11 +89,29 @@ protected:
{
CDialog::OnInitDialog();
// 非中文系统上 MBCS 对话框模板的中文会被系统 ACP 转成 "?",TranslateDialog
// 拿到的是已乱码文本无法还原,故在此显式设置(参照 NotifySettingsDlg)。
// 均经 _TR/_L 支持多语言翻译。
SetWindowText(_TR("屏幕预览质量等级"));
SetDlgItemText(IDC_PLEVEL_LABEL_LEVEL, _TR("等级"));
SetDlgItemText(IDC_PLEVEL_LABEL_WIDTH, _TR("最大宽度"));
SetDlgItemText(IDC_PLEVEL_LABEL_QUALITY, _TR("JPEG质量"));
static const TCHAR* kLevelNames[QUALITY_COUNT] = {
_T("Ultra 极佳"), _T("High 优秀"), _T("Good 良好"),
_T("Medium 一般"), _T("Low 较差"), _T("Minimal 最低")
};
for (int i = 0; i < QUALITY_COUNT; i++)
SetDlgItemText(IDC_PLEVEL_LABEL_LEVEL0 + i, _L(kLevelNames[i]));
SetDlgItemText(IDC_PLEVEL_LABEL_HINT,
_TR("最大宽度为期望编码宽度;JPEG 质量 1~100"));
SetDlgItemText(IDC_PLEVEL_RESET, _TR("恢复默认"));
SetDlgItemText(IDOK, _TR("确定"));
SetDlgItemText(IDCANCEL, _TR("取消"));
for (int i = 0; i < QUALITY_COUNT; i++) {
m_working[i] = m_profiles[i];
}
LoadToControls();
TranslateDialog(this);
return TRUE;
}
+2 -1
View File
@@ -89,8 +89,9 @@ typedef struct FeatureFlags {
#define MF_REQUEST_AUTH (1ULL << 42) // HIDE_MENU_REQUEST_AUTH
#define MF_MCP_SETTINGS (1ULL << 43) // HIDE_MENU_MCP_SETTINGS
#define MF_TLS_CERTIFICATE (1ULL << 44) // HIDE_MENU_TLS_CERTIFICATE
// [44-63] Reserved
// [45-63] Reserved
// ============================================================
+33 -4
View File
@@ -223,6 +223,27 @@ int GetIconIndex(LPCTSTR lpFileName, DWORD dwFileAttributes)
return index;
}
// 远程文件名/路径编码按 clientType 判定:Windows 走 A 接口(FindFirstFileA)=GBK/936,
// LNX/MAC 文件系统天然 UTF-8(同 McpServer.cpp::BuildListFiles)。这里用 LVM_SETITEMTEXTW
// 直接写宽字符串,绕开 ANSI→CP_ACP 回转,即使服务端运行在非中文 ACP 上中文名也能正常显示。
static void SetFileTextItem(CListCtrl& list, int iItem, int iSubItem, const char* sz, UINT cp)
{
std::wstring w;
if (sz && sz[0]) {
int wlen = MultiByteToWideChar(cp, 0, sz, -1, NULL, 0);
if (wlen > 1) {
w.resize(wlen - 1);
MultiByteToWideChar(cp, 0, sz, -1, &w[0], wlen);
}
}
LVITEMW lv = {};
lv.mask = LVIF_TEXT;
lv.iItem = iItem;
lv.iSubItem = iSubItem;
lv.pszText = w.empty() ? const_cast<LPWSTR>(L"") : &w[0];
::SendMessageW(list.GetSafeHwnd(), LVM_SETITEMTEXTW, (WPARAM)iItem, (LPARAM)&lv);
}
BOOL CFileManagerDlg::OnInitDialog()
{
__super::OnInitDialog();
@@ -1104,6 +1125,9 @@ void CFileManagerDlg::OnDblclkListRemote(NMHDR* pNMHDR, LRESULT* pResult)
void CFileManagerDlg::FixedRemoteFileList(BYTE *pbBuffer, DWORD dwBufferLen)
{
CString clientType = m_ContextObject->GetAdditionalData(RES_CLIENT_TYPE);
UINT cp = (clientType == _T("LNX") || clientType == _T("MAC")) ? CP_UTF8 : 936;
// 重新设置ImageList
SHFILEINFO sfi = {};
HIMAGELIST hImageListLarge = (HIMAGELIST)SHGetFileInfo(NULL, 0, &sfi,sizeof(SHFILEINFO), SHGFI_SYSICONINDEX | SHGFI_LARGEICON);
@@ -1151,7 +1175,8 @@ void CFileManagerDlg::FixedRemoteFileList(BYTE *pbBuffer, DWORD dwBufferLen)
pszFileName = ++pList;
if (bIsInsert) {
nItem = m_list_remote.InsertItem(nItemIndex++, pszFileName, GetIconIndex(pszFileName, nType));
nItem = m_list_remote.InsertItem(nItemIndex++, "", GetIconIndex(pszFileName, nType));
SetFileTextItem(m_list_remote, nItem, 0, pszFileName, cp);
m_list_remote.SetItemData(nItem, nType == FILE_ATTRIBUTE_DIRECTORY);
SHFILEINFO sfi = {};
SHGetFileInfo(pszFileName, FILE_ATTRIBUTE_NORMAL | nType, &sfi,sizeof(SHFILEINFO), SHGFI_TYPENAME | SHGFI_USEFILEATTRIBUTES);
@@ -1184,6 +1209,9 @@ void CFileManagerDlg::FixedRemoteFileList(BYTE *pbBuffer, DWORD dwBufferLen)
void CFileManagerDlg::FixedRemoteSearchFileList(BYTE *pbBuffer, DWORD dwBufferLen)
{
CString clientType = m_ContextObject->GetAdditionalData(RES_CLIENT_TYPE);
UINT cp = (clientType == _T("LNX") || clientType == _T("MAC")) ? CP_UTF8 : 936;
// 第一批结果到达时,初始化搜索列表
if (!m_bSearching) {
m_bSearching = true;
@@ -1241,7 +1269,8 @@ void CFileManagerDlg::FixedRemoteSearchFileList(BYTE *pbBuffer, DWORD dwBufferLe
}
}
int nItem = m_list_remote.InsertItem(m_nSearchResultCount, csFileName, nIcon);
int nItem = m_list_remote.InsertItem(m_nSearchResultCount, "", nIcon);
SetFileTextItem(m_list_remote, nItem, 0, csFileName, cp);
m_list_remote.SetItemData(nItem, nType == FILE_ATTRIBUTE_DIRECTORY);
pList += lstrlen(pszFullPath) + 1;
@@ -1261,7 +1290,7 @@ void CFileManagerDlg::FixedRemoteSearchFileList(BYTE *pbBuffer, DWORD dwBufferLe
m_list_remote.SetItemText(nItem, 2, time.FormatL("%Y-%m-%d %H:%M"));
// 路径
m_list_remote.SetItemText(nItem, 3, csDir);
SetFileTextItem(m_list_remote, nItem, 3, csDir, cp);
pList += 16;
m_nSearchResultCount++;
@@ -3329,7 +3358,7 @@ void CFileManagerDlg::OnTransferV2ToRemote()
g_2015RemoteDlg->SendFilesToClientV2(mainCtx, files, remoteDir);
ShowMessage(_TRF("V2传输已启动,共 %d 个文件 -> %s"), (int)files.size(), remoteDir.c_str());
} else {
ShowMessage(_TRF("找不到主连接: clientID=%llu"), clientID);
ShowMessage(_TRF("找不到主连接: clientID %llu"), clientID);
}
}
}
+6 -1
View File
@@ -69,8 +69,9 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap) {
CString os = ctx->GetClientData(ONLINELIST_OS);
device["os"] = AnsiToUtf8(os);
// 地理位置已统一按 UTF-8 存储(见 AddList),直接透传,不再 CP_ACP→UTF-8 二次转换。
CString location = ctx->GetClientData(ONLINELIST_LOCATION);
device["location"] = AnsiToUtf8(location);
device["location"] = std::string(location.GetString());
CString rtt = ctx->GetClientData(ONLINELIST_PING);
device["rtt"] = AnsiToUtf8(rtt);
@@ -113,5 +114,9 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap) {
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
device["clientType"] = AnsiToUtf8(clientType); // e.g. "MAC", "LNX", "EXE"
// 登录时上报的 TLS 传输标志(RES_TLS=="1" → "Y")。老客户端不上报,取值为 "N"。
// 注意这是登录凭据而不是实时探测:连接建立后若配置发生变化,需要客户端重连才会更新。
device["tls"] = (ctx->GetClientData(ONLINELIST_TLS) == "Y");
return device;
}
+1 -1
View File
@@ -124,7 +124,7 @@ void IOCPKCPServer::WorkerThread()
}
if (n > 0&& m_notify) {
memcpy(ctx->szBuffer, recvbuf, n);
BOOL ret = ParseReceivedData(ctx, n, m_notify);
BOOL ret = ParseReceivedData(ctx, (PBYTE)ctx->szBuffer, n, m_notify);
}
} while (n>0);
}
+221 -19
View File
@@ -3,6 +3,7 @@
#include "2015Remote.h"
#include "common/IPWhitelist.h"
#include "common/IPBlacklist.h"
#include "ServerTlsSession.h"
#include <iostream>
#include <ws2tcpip.h>
@@ -483,6 +484,11 @@ UINT IOCPServer::StartServer(pfnNotifyProc NotifyProc, pfnOfflineProc OffProc, U
m_nPort = uPort;
m_NotifyProc = NotifyProc;
m_OfflineProc = OffProc;
// 单向 TLS:启动时加载服务端身份(证书+私钥)。加载失败时 IsLoadError()==true,
// 明文客户端不受影响,TLS ClientHello 会被识别并 fail-closed 关闭(见设计文档 §5.2)。
ServerTlsIdentity::Load(THIS_CFG);
// manual-reset:本进程内可能有多个等待者(ListenThread / RttPollThreadProc)。
// 自动重置会让 SetEvent 只唤醒一个等待者,另一个要等自身 timeout(≤1s)。
// 改 manual-reset 后所有等待者一次性醒来;本工程从无 ResetEvent 调用,无副作用。
@@ -793,16 +799,16 @@ BOOL IOCPServer::OnClientInitializing(PCONTEXT_OBJECT ContextObject, DWORD dwTr
}
// May be this function should be a member of `CONTEXT_OBJECT`.
BOOL ParseReceivedData(CONTEXT_OBJECT * ContextObject, DWORD dwTrans, pfnNotifyProc m_NotifyProc, ZSTD_DCtx* m_Dctx, z_stream* z)
BOOL ParseReceivedData(CONTEXT_OBJECT * ContextObject, PBYTE data, DWORD dataLen, pfnNotifyProc m_NotifyProc, ZSTD_DCtx* m_Dctx, z_stream* z)
{
AUTO_TICK(50, ContextObject->GetPeerName());
BOOL ret = 1;
try {
if (dwTrans == 0) { //对方关闭了套接字
if (dataLen == 0) { //对方关闭了套接字
return FALSE;
}
//将接收到的数据拷贝到我们自己的内存中wsabuff 8192
ContextObject->InCompressedBuffer.WriteBuffer((PBYTE)ContextObject->szBuffer,dwTrans);
ContextObject->InCompressedBuffer.WriteBuffer(data, dataLen);
//查看数据包的完整性
while (true) {
PR pr = ContextObject->Parse(ContextObject->InCompressedBuffer);
@@ -889,18 +895,178 @@ BOOL ParseReceivedData(CONTEXT_OBJECT * ContextObject, DWORD dwTrans, pfnNotifyP
return ret;
}
BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans, ZSTD_DCtx* ctx, z_stream* z)
// 握手线程参数:把嗅探阶段已收到的 ClientHello 字节与连接上下文一起移交。
struct TlsHandshakeParam {
IOCPServer* server;
CONTEXT_OBJECT* ctx;
std::vector<BYTE> initial; // 嗅探阶段已攒下的首批字节(≥6,可能只是 ClientHello 分片)
};
// 方案 A:专用阻塞握手线程。占线期间独占 socket(阻塞 recv/send,无未决 overlapped I/O),
// 完成后把连接交还给 IOCP(PostRecv)。线程持有 ctx 的一枚 IoRefCount,结束时释放。
DWORD WINAPI IOCPServer::TlsHandshakeThreadProc(LPVOID lParam)
{
if (FALSE == ParseReceivedData(ContextObject, dwTrans, m_NotifyProc, ctx, z)) {
// 先减少引用计数,再调用 RemoveStaleContext (#215)
// RemoveStaleContext 完成后对象会被移到空闲池,不能再访问
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2; // 特殊返回值:告诉 HandleIO 不要再减少引用计数
TlsHandshakeParam* p = (TlsHandshakeParam*)lParam;
IOCPServer* This = p->server;
CONTEXT_OBJECT* ctx = p->ctx;
std::vector<BYTE> initial = std::move(p->initial);
delete p;
// 若上下文已被移除(服务端关停竞态),直接释放引用退出。
if (ctx->IsRemoved.load(std::memory_order_acquire)) {
ctx->IoRefCount.fetch_sub(1);
return 0;
}
PostRecv(ContextObject); //投递新的接收数据的请求
// 握手期间做同步 recv/send。注意:监听套接字经 WSAEventSelect 置为非阻塞后,accept 出的
// 子套接字继承非阻塞态,FIONBIO=0 不一定能切回阻塞;ServerTlsSession::Handshake 内部已用
// select 兜底 WSAEWOULDBLOCK,故这里仍设 FIONBIO=0 只是「尽量阻塞」的优化。
u_long nb = 0;
if (ioctlsocket(ctx->sClientSocket, FIONBIO, &nb) == SOCKET_ERROR)
Mprintf("[TLS] handshake: ioctlsocket(FIONBIO=0) failed err=%d\n", WSAGetLastError());
int tmo = 15000; // 15s 握手超时
setsockopt(ctx->sClientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tmo, sizeof(tmo));
setsockopt(ctx->sClientSocket, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tmo, sizeof(tmo));
bool ok = (ctx->tls != NULL) &&
ctx->tls->Handshake(ctx->sClientSocket, initial.data(), (int)initial.size());
if (ok) {
ctx->tlsState.store(TLS_Ready, std::memory_order_release);
}
// 先释放握手线程持有的引用,再触发任何可能 RemoveStaleContext 的动作(#215 顺序)。
ctx->IoRefCount.fetch_sub(1);
if (ok) {
This->PostRecv(ctx); // 交还 IOCP 接收
} else {
Mprintf("[TLS] handshake failed for %s (fail-closed)\n", ctx->GetPeerName().c_str());
This->RemoveStaleContext(ctx);
}
return 0;
}
// 判定为 TLS 后:创建会话、预支一枚 IoRefCount 给握手线程、启动握手线程。
BOOL IOCPServer::StartTlsHandshake(CONTEXT_OBJECT* ContextObject)
{
if (!ServerTlsIdentity::IsReady()) {
// 服务端身份不可用(未启用 TLS、或证书/私钥加载失败):fail-closed 关闭该连接。
Mprintf("[TLS] client %s sent ClientHello but server identity not ready "
"(TLS disabled or cert/key load failed); closing (fail-closed)\n",
ContextObject->GetPeerName().c_str());
return FALSE;
}
ContextObject->tls = new ServerTlsSession();
TlsHandshakeParam* p = new TlsHandshakeParam;
p->server = this;
p->ctx = ContextObject;
p->initial = std::move(ContextObject->tlsPreClassify);
ContextObject->tlsPreClassify.clear();
// 预支引用:握手线程结束时释放。此引用保证握手期间对象不被回收。
ContextObject->IoRefCount.fetch_add(1);
HANDLE h = CreateThread(NULL, 0, TlsHandshakeThreadProc, p, 0, NULL);
if (h == NULL) {
// 启动失败:回退预支引用,清理会话,按失败关闭。
ContextObject->IoRefCount.fetch_sub(1);
delete ContextObject->tls;
ContextObject->tls = NULL;
return FALSE;
}
CloseHandle(h);
return TRUE;
}
BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans, ZSTD_DCtx* ctx, z_stream* z)
{
int st = ContextObject->tlsState.load(std::memory_order_acquire);
// ---- 未分类:按 ClientHello 头嗅探明文 / TLS(见设计文档 §5.2)----
if (st == TLS_Unclassified) {
if (dwTrans == 0) { // 首个包即对端关闭
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2;
}
ContextObject->tlsPreClassify.insert(ContextObject->tlsPreClassify.end(),
(BYTE*)ContextObject->szBuffer,
(BYTE*)ContextObject->szBuffer + dwTrans);
if (ContextObject->tlsPreClassify.size() < 6) {
PostRecv(ContextObject); // 头还没攒够,继续收
return TRUE;
}
const BYTE* h = ContextObject->tlsPreClassify.data();
bool isTls = (h[0] == 0x16 && h[1] == 0x03 && h[5] == 0x01);
if (isTls) {
ContextObject->tlsState.store(TLS_Handshaking, std::memory_order_release);
if (!StartTlsHandshake(ContextObject)) {
Mprintf("[TLS] StartTlsHandshake failed for %s (fail-closed)\n",
ContextObject->GetPeerName().c_str());
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2;
}
return TRUE; // 不 PostRecv;握手线程完成后交还接收
}
// 明文:把嗅探阶段攒下的字节回放给现有解析路径,然后清空缓冲。
ContextObject->tlsState.store(TLS_Plain, std::memory_order_release);
std::vector<BYTE> replay = std::move(ContextObject->tlsPreClassify);
ContextObject->tlsPreClassify.clear();
if (FALSE == ParseReceivedData(ContextObject, replay.data(), (DWORD)replay.size(), m_NotifyProc, ctx, z)) {
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2;
}
PostRecv(ContextObject);
return TRUE;
}
// ---- 已分类 ----
if (st == TLS_Ready) {
if (dwTrans == 0) { // 明文 FIN:TLS 连接对端关闭
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2;
}
std::vector<BYTE> plain;
if (ContextObject->tls->Decrypt((const BYTE*)ContextObject->szBuffer, dwTrans, plain) < 0) {
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2;
}
if (plain.empty()) {
PostRecv(ContextObject); // 本轮无完整明文(TLS 记录分片/握手告警),继续收
return TRUE;
}
if (FALSE == ParseReceivedData(ContextObject, plain.data(), (DWORD)plain.size(), m_NotifyProc, ctx, z)) {
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2;
}
PostRecv(ContextObject);
return TRUE;
}
// TLS_Handshaking:握手线程独占 socket,正常不应出现 IORead;若出现属异常,fail-closed。
if (st == TLS_Handshaking) {
Mprintf("[TLS] unexpected IORead during handshake for %s (closing)\n",
ContextObject->GetPeerName().c_str());
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2;
}
// TLS_Plain:明文直通(原路径)。
if (FALSE == ParseReceivedData(ContextObject, (PBYTE)ContextObject->szBuffer, dwTrans, m_NotifyProc, ctx, z)) {
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2;
}
PostRecv(ContextObject);
return TRUE;
}
@@ -967,15 +1133,49 @@ BOOL WriteContextData(CONTEXT_OBJECT* ContextObject, PBYTE szBuffer, size_t ulOr
BOOL IOCPServer::OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffer, size_t ulOriginalLength)
{
// TLS 下 OutCompressedBuffer 可能还残留上一轮尚未发完的密文(IOCP 线程异步 WSASend 中),
// 新明文由 WriteContextData 追加在尾部。若把整个缓冲区重新加密,会把旧密文二次加密,
// 客户端解密后得到的是「旧 TLS 记录」→ Unknown header 17 03 03。故只加密本次新追加的尾部。
bool tlsReady = (ContextObject->tlsState.load(std::memory_order_acquire) == TLS_Ready);
ULONG oldLen = tlsReady ? ContextObject->OutCompressedBuffer.GetBufferLength() : 0;
if (WriteContextData(ContextObject, szBuffer, ulOriginalLength, ContextObject->Zcctx)) {
OVERLAPPEDPLUS* OverlappedPlus = new OVERLAPPEDPLUS(IOWrite);
BOOL bOk = PostQueuedCompletionStatus(m_hCompletionPort, 0, (ULONG_PTR)ContextObject, &OverlappedPlus->m_ol);
if ( (!bOk && GetLastError() != ERROR_IO_PENDING) ) { //如果投递失败
int a = GetLastError();
Mprintf("!!! OnClientPreSending 投递消息失败\n");
RemoveStaleContext(ContextObject);
SAFE_DELETE(OverlappedPlus);
return FALSE;
// 单向 TLS:只加密新追加的明文尾部,产出密文后与前缀旧密文拼接,使缓冲区始终保持
// 一串合法 TLS 记录;之后 IOWrite / OnClientPostSending 完全不变(见设计文档 §5.5)。
if (tlsReady) {
ULONG totalLen = ContextObject->OutCompressedBuffer.GetBufferLength();
ULONG plainLen = totalLen - oldLen;
if (plainLen > 0) {
std::vector<BYTE> wire;
if (ContextObject->tls->Encrypt((const BYTE*)ContextObject->OutCompressedBuffer.GetBuffer(oldLen),
(int)plainLen, wire) != (int)plainLen) {
Mprintf("[TLS] Encrypt failed for %s (fail-closed)\n",
ContextObject->GetPeerName().c_str());
return FALSE; // 加密失败:丢弃本次发送
}
// 截断尾部明文,再追加密文。用 TruncateBuffer 而非 ClearBuffer:ClearBuffer 会
// DeAllocateBuffer(可能 VirtualFree 正在被异步 WSASend 引用的底层内存)。
ContextObject->OutCompressedBuffer.TruncateBuffer(oldLen);
ContextObject->OutCompressedBuffer.WriteBuffer(wire.data(), (DWORD)wire.size());
}
}
// 仅当没有发送正在进行时才投递 IOWrite 唤醒发送。若已有 WSASend 在途,其完成回调
// (OnClientPostSending)会看到排空后仍残留的新数据并继续发送,无需再投递;否则会对
// 同一缓冲并发多个 WSASend,读到同一段可变内存,产出重复/错位密文(客户端 DecryptMessage
// 失败,表现为 recv -1、GetLastError=6001)。
if (!ContextObject->bSendPending) {
ContextObject->bSendPending = true;
OVERLAPPEDPLUS* OverlappedPlus = new OVERLAPPEDPLUS(IOWrite);
BOOL bOk = PostQueuedCompletionStatus(m_hCompletionPort, 0, (ULONG_PTR)ContextObject, &OverlappedPlus->m_ol);
if ( (!bOk && GetLastError() != ERROR_IO_PENDING) ) { //如果投递失败
int a = GetLastError();
Mprintf("!!! OnClientPreSending 投递消息失败\n");
ContextObject->bSendPending = false;
RemoveStaleContext(ContextObject);
SAFE_DELETE(OverlappedPlus);
return FALSE;
}
}
return TRUE;
}
@@ -990,6 +1190,7 @@ BOOL IOCPServer::OnClientPostSending(CONTEXT_OBJECT* ContextObject,ULONG ulCompl
ContextObject->OutCompressedBuffer.RemoveCompletedBuffer(ulCompletedLength); //将完成的数据从数据结构中去除
if (ContextObject->OutCompressedBuffer.GetBufferLength() == 0) {
ContextObject->bSendPending = false; // 缓冲排空,允许下一次 OnClientPreSending 投递
ContextObject->OutCompressedBuffer.ClearBuffer();
return true; //走到这里说明我们的数据真正完全发送
} else {
@@ -1001,6 +1202,7 @@ BOOL IOCPServer::OnClientPostSending(CONTEXT_OBJECT* ContextObject,ULONG ulCompl
NULL, ulFlags,&OverlappedPlus->m_ol, NULL);
if ( iOk == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING ) {
// 先减少引用计数,再调用 RemoveStaleContext (#215)
ContextObject->bSendPending = false;
ContextObject->IoRefCount.fetch_sub(1);
if (RemoveStaleContext(ContextObject))
Mprintf("!!! OnClientPostSending 投递消息失败: %d\n", WSAGetLastError());
+5 -1
View File
@@ -91,6 +91,7 @@ private:
static DWORD WINAPI ListenThreadProc(LPVOID lParam);
static DWORD WINAPI WorkThreadProc(LPVOID lParam);
static DWORD WINAPI RttPollThreadProc(LPVOID lParam);
static DWORD WINAPI TlsHandshakeThreadProc(LPVOID lParam);
BOOL InitializeIOCP(VOID);
VOID OnAccept();
@@ -101,6 +102,7 @@ private:
BOOL HandleIO(IOType PacketFlags, PCONTEXT_OBJECT ContextObject, DWORD dwTrans, ZSTD_DCtx* ctx, z_stream *z);
BOOL OnClientInitializing(PCONTEXT_OBJECT ContextObject, DWORD dwTrans);
BOOL OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans, ZSTD_DCtx* ctx, z_stream* z);
BOOL StartTlsHandshake(CONTEXT_OBJECT* ContextObject);
BOOL OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffer, size_t ulOriginalLength);
BOOL OnClientPostSending(CONTEXT_OBJECT* ContextObject, ULONG ulCompressedLength);
int AddWorkThread(int n)
@@ -257,6 +259,8 @@ public:
typedef CDialogBase DialogBase;
BOOL ParseReceivedData(CONTEXT_OBJECT* ContextObject, DWORD dwTrans, pfnNotifyProc m_NotifyProc, ZSTD_DCtx *ctx=NULL, z_stream* z=NULL);
// 解析一段已解密/直通的接收字节。data/dataLen 为数据源(TLS 连接传解密后的明文,
// 明文连接传 szBuffer 原始字节);dataLen==0 视为对端关闭。
BOOL ParseReceivedData(CONTEXT_OBJECT* ContextObject, PBYTE data, DWORD dataLen, pfnNotifyProc m_NotifyProc, ZSTD_DCtx *ctx=NULL, z_stream* z=NULL);
BOOL WriteContextData(CONTEXT_OBJECT* ContextObject, PBYTE szBuffer, size_t ulOriginalLength, ZSTD_CCtx *ctx=NULL, z_stream* z = NULL);
+1 -1
View File
@@ -107,7 +107,7 @@ void IOCPUDPServer::WorkerThread()
IO_CONTEXT* ioCtx = CONTAINING_RECORD(pOverlapped, IO_CONTEXT, ol);
CONTEXT_UDP* ctx = ioCtx->pContext;
BOOL ret = ParseReceivedData(ctx, bytes, m_notify);
BOOL ret = ParseReceivedData(ctx, (PBYTE)ctx->szBuffer, bytes, m_notify);
if (999 != ret)
ctx->Destroy();
+15 -2
View File
@@ -123,6 +123,9 @@ BOOL CKeyBoardDlg::OnInitDialog()
// 后,控件内部以 Unicode 存储,W 版消息直通,不再走 CP_ACP。
// -----------------------------------------------------------------
RebuildEdit(m_edit);
// 剪切板显示框同样重建为 Unicode 控件,ShowClipboardText 全程走 W 版消息,
// 否则 MBCS 下 SetWindowTextA 会在 A<->W 边界按 CP_ACP 转码,中文丢失。
RebuildEdit(m_EditClipText);
m_edit.SetLimitText(MAXDWORD); // 设置最大长度
auto rule = utf8_to_ansi((char*)m_TextRule.param);
@@ -171,9 +174,19 @@ void CKeyBoardDlg::OnReceiveComplete()
LRESULT CKeyBoardDlg::ShowClipboardText(WPARAM wParam, LPARAM lParam)
{
char* buf = (char*)wParam;
std::string text = utf8_to_ansi(buf);
// 剪切板文本是 UTF-8(client/my_clip.h 的 clip::get_text 从 CF_UNICODETEXT 转出)。
// 直接转宽字符串,用 W 版写入重建后的 Unicode 控件,绕开 utf8_to_ansi 的 CP_ACP
// 回转——非中文系统(德语/英语)上中文也能正常显示(与 m_edit 同法)。
std::wstring w;
if (buf && buf[0]) {
int wlen = MultiByteToWideChar(CP_UTF8, 0, buf, -1, NULL, 0);
if (wlen > 1) {
w.resize(wlen - 1);
MultiByteToWideChar(CP_UTF8, 0, buf, -1, &w[0], wlen);
}
}
SAFE_DELETE_ARRAY(buf);
m_EditClipText.SetWindowTextA(text.c_str());
::SetWindowTextW(m_EditClipText.GetSafeHwnd(), w.c_str());
return S_OK;
}
+13 -4
View File
@@ -723,11 +723,11 @@ protected:
AppendData(&dlgTemplate, sizeof(DLGTEMPLATE));
AppendWord(0); // 菜单
AppendWord(0); // 窗口类
AppendString(_T("切换语言 / Switch Language"));
AppendString(_T("切换语言"));
AlignToDword();
// 静态文本
AddControl(0x0082, 15, 15, 50, 12, (WORD)-1,
AddControl(0x0082, 15, 15, 50, 12, 1002,
SS_LEFT | WS_CHILD | WS_VISIBLE, _T("语言:"));
// ComboBox
@@ -796,8 +796,17 @@ protected:
{
CDialog::OnInitDialog();
// 翻译对话框控件(标题、标签、按钮)
TranslateDialog(this);
// 模板为动态构造的 Unicode 模板,MBCS 下被 ANSI 创建路径误读,标题/标签/按钮文字会乱码,
// 故在此显式设置(走线程 locale GBK,与其它对话框同法),不再对已乱码文本调用 TranslateDialog。
// 标题含中文:非中文系统上 ANSI 消息按系统 ACP 解码会乱码,用 _TR 取翻译(中文→切换语言,
// 英语→Switch Language)后,显式 GBK(936)→Unicode 转换再用 Unicode 消息设置(与工具栏同法)。
CString strTitle = _TR("切换语言");
WCHAR wTitle[64] = { 0 };
MultiByteToWideChar(936, 0, strTitle, -1, wTitle, 64);
::SetWindowTextW(m_hWnd, wTitle);
SetDlgItemText(1002, _TR("语言:"));
SetDlgItemText(IDOK, _TR("确定"));
SetDlgItemText(IDCANCEL, _TR("取消"));
m_comboLang.SubclassDlgItem(1001, this);
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
#pragma once
// MCP「远程交谈」工具族:chat_open / chat_send / chat_wait / chat_close。
//
// 复用 Windows 客户端既有的「远程交谈」链路(协议不变):
// 主连接 [COMMAND_CHAT=161]
// → 客户端子连接先 [TOKEN_CONN_AUTH=246],再 [TOKEN_CHAT_START=62]
// → 服务端在子连接回 [COMMAND_NEXT_CHAT=0](客户端据此弹 IDD_CHAT)
// → 双向文本 [CP936 字节][NUL];服务端 [COMMAND_CHAT_CLOSE=1] 结束。
//
// 会话状态由 CMcpServer 持有(McpServer.h),本文件只负责工具 schema、参数校验、
// 编码转换与响应构造。协议、客户端怪癖与验证矩阵见 docs/Mcp_Chat_Design.md。
#include "jsoncpp/json.h"
#include <string>
class CMy2015RemoteDlg;
namespace McpChat {
bool Handles(const std::string& toolName);
// 开关 close 时不追加任何工具(tools/list 与调用侧一致)。
void AppendTools(Json::Value& tools);
std::string Call(const Json::Value& id, const std::string& toolName,
const Json::Value& args, CMy2015RemoteDlg* parent);
} // namespace McpChat
+420
View File
@@ -0,0 +1,420 @@
#include "stdafx.h"
#include "McpInternal.h"
#include "context.h" // context 接口(GetClientID/IsLogin)
#include "2015RemoteDlg.h" // CMy2015RemoteDlg 成员(m_HostList/m_cs)+ WM_SHOWERRORMSG
#include "LangManager.h" // _TR
#ifndef _WIN64
#ifdef _DEBUG
#pragma comment(lib, "jsoncpp/jsoncppd.lib")
#else
#pragma comment(lib, "jsoncpp/jsoncpp.lib")
#endif
#else
#ifdef _DEBUG
#pragma comment(lib, "jsoncpp/jsoncpp_x64d.lib")
#else
#pragma comment(lib, "jsoncpp/jsoncpp_x64.lib")
#endif
#endif
namespace McpInternal {
std::string JsonToString(const Json::Value& v) {
Json::StreamWriterBuilder b;
b["indentation"] = "";
// jsoncpp 默认按 17 位有效数字输出 double,27.8 会写成 27.800000000000001。
// 我们只有 memoryGB 一个浮点字段(1 位小数),15 位足够且输出干净。
b["precision"] = 15;
b["precisionType"] = "significant";
return Json::writeString(b, v);
}
std::string BuildResult(const Json::Value& id, const Json::Value& result) {
Json::Value resp(Json::objectValue);
resp["jsonrpc"] = "2.0";
resp["id"] = id;
resp["result"] = result;
return JsonToString(resp);
}
std::string BuildError(const Json::Value& id, int code, const std::string& msg) {
Json::Value resp(Json::objectValue);
resp["jsonrpc"] = "2.0";
resp["id"] = id;
Json::Value err(Json::objectValue);
err["code"] = code;
err["message"] = msg;
resp["error"] = err;
return JsonToString(resp);
}
std::string ToLowerAscii(const std::string& s) {
std::string r = s;
for (char& c : r) if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a');
return r;
}
bool ContainsCI(const std::string& haystack, const std::string& needle) {
if (needle.empty()) return true;
return ToLowerAscii(haystack).find(ToLowerAscii(needle)) != std::string::npos;
}
std::string JsonStrField(const Json::Value& v, const char* key) {
if (v.isObject() && v.isMember(key) && v[key].isString())
return v[key].asString();
return "";
}
bool IsDigits(const std::string& s) {
if (s.empty()) return false;
for (char c : s) if (c < '0' || c > '9') return false;
return true;
}
std::string GetStringArg(const Json::Value& args, const char* key) {
return JsonStrField(args, key);
}
bool GetIntArg(const Json::Value& args, const char* key, int& out) {
if (!args.isMember(key)) return false;
const Json::Value& v = args[key];
if (v.isNumeric()) { out = v.asInt(); return true; }
if (v.isString()) {
const std::string s = v.asString();
if (IsDigits(s) || (!s.empty() && s[0] == '-' && IsDigits(s.substr(1)))) {
out = atoi(s.c_str());
return true;
}
}
return false;
}
bool ReadUInt64(const Json::Value& v, uint64_t& out) {
if (v.isNumeric()) { out = v.asUInt64(); return true; }
if (v.isString()) {
std::string s = v.asString();
if (IsDigits(s)) { out = strtoull(s.c_str(), nullptr, 10); return true; }
}
return false;
}
bool ReadUInt64Arg(const Json::Value& args, const char* key, uint64_t& out) {
if (!args.isMember(key)) return false;
return ReadUInt64(args[key], out);
}
bool ParseHostIdArg(const Json::Value& args, uint64_t& out, std::string& err) {
std::string sid = GetStringArg(args, "id");
if (sid.empty()) {
err = "Missing required parameter: id";
return false;
}
if (!IsDigits(sid)) {
err = "Invalid id: expected a decimal host id string";
return false;
}
out = strtoull(sid.c_str(), nullptr, 10);
return true;
}
context* FindMainContext(CMy2015RemoteDlg* parent, uint64_t id) {
if (!parent) return nullptr;
context* found = nullptr;
EnterCriticalSection(&parent->m_cs);
for (context* ctx : parent->m_HostList) {
if (ctx && ctx->GetClientID() == id && ctx->IsLogin()) {
found = ctx;
break;
}
}
LeaveCriticalSection(&parent->m_cs);
return found;
}
size_t BoundedStrlen(const char* p, size_t avail) {
size_t n = 0;
while (n < avail && p[n]) ++n;
return n;
}
std::string ToUtf8(const char* s, UINT cp) {
if (!s || !*s) return "";
int wlen = MultiByteToWideChar(cp, 0, s, -1, NULL, 0);
if (wlen <= 0) return "";
std::wstring w(wlen - 1, L'\0');
MultiByteToWideChar(cp, 0, s, -1, &w[0], wlen);
int u8len = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, NULL, 0, NULL, NULL);
if (u8len <= 0) return "";
std::string out(u8len - 1, '\0');
WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, &out[0], u8len, NULL, NULL);
return out;
}
std::string ToAnsi(const std::string& utf8, UINT cp) {
if (utf8.empty()) return "";
int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), (int)utf8.size(), NULL, 0);
if (wlen <= 0) return utf8;
std::wstring w(wlen, L'\0');
MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), (int)utf8.size(), &w[0], wlen);
int alen = WideCharToMultiByte(cp, 0, w.c_str(), wlen, NULL, 0, NULL, NULL);
if (alen <= 0) return utf8;
std::string out(alen, '\0');
WideCharToMultiByte(cp, 0, w.c_str(), wlen, &out[0], alen, NULL, NULL);
return out;
}
bool Utf8ToCpExact(const std::string& utf8, UINT cp, std::string& out) {
out.clear();
if (utf8.empty()) return true;
int wlen = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.c_str(), (int)utf8.size(), NULL, 0);
if (wlen <= 0) return false;
std::wstring w(wlen, L'\0');
if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.c_str(), (int)utf8.size(),
&w[0], wlen) != wlen)
return false;
BOOL usedDefault = FALSE;
int alen = WideCharToMultiByte(cp, WC_NO_BEST_FIT_CHARS, w.c_str(), wlen, NULL, 0, NULL, &usedDefault);
if (alen <= 0 || usedDefault) return false;
out.assign(alen, '\0');
usedDefault = FALSE;
if (WideCharToMultiByte(cp, WC_NO_BEST_FIT_CHARS, w.c_str(), wlen, &out[0], alen,
NULL, &usedDefault) != alen || usedDefault) {
out.clear();
return false;
}
return true;
}
bool IsValidUtf8(const char* s, size_t n) {
if (!s || n == 0) return true;
int wlen = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s, (int)n, NULL, 0);
return wlen > 0;
}
void AuditManageAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail) {
if (!parent) return;
std::string text = "host " + std::to_string(devId) + " " + tool + ": " + detail;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP管理操作")));
}
void AuditChatAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail) {
if (!parent) return;
std::string text = "host " + std::to_string(devId) + " " + tool + ": " + detail;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP远程交谈")));
}
// ===== 列表输出治理 =====
PageWindow ResolvePageWindow(const Json::Value& args, int defaultLimit, int maxLimit) {
PageWindow w;
w.limit = defaultLimit;
if (args.isObject()) {
if (args.isMember("limit") && args["limit"].isInt()) {
int v = args["limit"].asInt();
if (v > 0) w.limit = v; // 0/负数视为未指定,用默认值
}
if (args.isMember("offset") && args["offset"].isInt()) {
int v = args["offset"].asInt();
if (v > 0) w.offset = v;
}
}
if (w.limit > maxLimit) w.limit = maxLimit;
return w;
}
void ApplyPageWindow(const Json::Value& all, PageWindow& w, Json::Value& out) {
out = Json::Value(Json::arrayValue);
w.total = all.isArray() ? (int)all.size() : 0;
w.totalAll = w.total;
int begin = w.offset < w.total ? w.offset : w.total;
int end = (begin + w.limit < w.total) ? begin + w.limit : w.total;
for (int i = begin; i < end; ++i) out.append(all[i]);
w.returned = end > begin ? end - begin : 0;
w.hasMore = end < w.total;
}
void WritePageFields(Json::Value& structuredContent, const PageWindow& w) {
structuredContent["total"] = w.total;
structuredContent["totalAll"] = w.totalAll;
structuredContent["offset"] = w.offset;
structuredContent["limit"] = w.limit;
structuredContent["hasMore"] = w.hasMore;
}
void AppendPagingProps(Json::Value& props, int defaultLimit, int maxLimit) {
Json::Value limitProp(Json::objectValue);
limitProp["type"] = "integer";
limitProp["description"] = std::string(u8"本次最多返回的条数,默认 ") +
std::to_string(defaultLimit) + std::string(u8",上限 ") +
std::to_string(maxLimit) + std::string(u8"。");
props["limit"] = limitProp;
Json::Value offsetProp(Json::objectValue);
offsetProp["type"] = "integer";
offsetProp["description"] = u8"跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。";
props["offset"] = offsetProp;
}
void AppendBatchIdsProp(Json::Value& props) {
Json::Value idsProp(Json::objectValue);
idsProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "string";
idsProp["items"] = items;
idsProp["description"] = std::string(u8"批量查询:一次传多台主机 id(最多 50 个),"
u8"结果按台汇总在 results 里。与 id 二选一,仅只读工具支持;"
u8"limit/offset 对每台主机各自生效。");
props["ids"] = idsProp;
}
void MakeIdOrIdsRequired(Json::Value& schema) {
// 调用方可能先按单机 schema 生成了 required:["id"]:留着它会让「只传 ids」违反 schema
// (required 与 anyOf 同时生效)。这里只清理这一个精确形态,别的 required 不动。
if (schema.isMember("required") && schema["required"].isArray() &&
schema["required"].size() == 1 && schema["required"][0].isString() &&
schema["required"][0].asString() == "id") {
schema.removeMember("required");
}
Json::Value anyOf(Json::arrayValue);
for (const char* key : { "id", "ids" }) {
Json::Value alt(Json::objectValue);
Json::Value req(Json::arrayValue);
req.append(key);
alt["required"] = req;
anyOf.append(alt);
}
schema["anyOf"] = anyOf;
}
std::string PageSummary(const PageWindow& w, const char* unit) {
std::string s = std::string(u8"共 ") + std::to_string(w.total) + std::string(u8" ") + unit;
if (w.total == 0) return s + std::string(u8"。");
int begin = w.offset < w.total ? w.offset : w.total;
if (begin >= w.total) {
s += std::string(u8",offset 超出范围,本次返回 0 条。");
return s;
}
int end = (begin + w.limit < w.total) ? begin + w.limit : w.total;
s += std::string(u8",本次返回第 ") + std::to_string(begin + 1) + "-" +
std::to_string(end) + std::string(u8" 条");
if (w.hasMore) s += std::string(u8"(还有更多,可用 offset 继续取)");
return s + std::string(u8"。");
}
// ===== 工具注解(A3)=====
namespace {
struct ToolHints {
const char* name;
bool readOnly;
bool destructive;
bool idempotent;
bool openWorld; // false = 只读服务端本机状态(主机列表、审计日志),不触达外部主机
};
// 53 个工具的语义登记表。新增工具必须在此登记(漏登记 → 走默认 destructiveHint=true)。
const ToolHints kToolHints[] = {
// --- 服务端本机只读 ---
{ "list_online_hosts", true, false, true, false },
{ "search_hosts", true, false, true, false },
{ "list_all_hosts", true, false, true, false },
{ "get_host_detail", true, false, true, false },
{ "get_activity_history", true, false, true, false },
{ "get_audit_log", true, false, true, false },
{ "get_server_status", true, false, true, false },
// --- 主机只读 ---
{ "list_processes", true, false, true, true },
{ "list_windows", true, false, true, true },
{ "list_files", true, false, true, true },
{ "list_services", true, false, true, true },
{ "get_client_log", true, false, true, true },
{ "get_keylog", true, false, true, true },
{ "get_screenshot", true, false, true, true },
{ "list_registry", true, false, true, true },
{ "download_file", true, false, true, true }, // 只读主机(写的是主控本机目录)
{ "search_file", true, false, true, true },
{ "list_network_connections", true, false, true, true },
{ "host_list_processes", true, false, true, true },
{ "host_list_windows", true, false, true, true },
{ "host_list_network_state", true, false, true, true },
{ "host_list_software", true, false, true, true },
{ "host_list_browser_history", true, false, true, true },
{ "host_list_favorites", true, false, true, true },
{ "host_list_win32_services", true, false, true, true },
{ "host_list_driver_services", true, false, true, true },
{ "host_list_scheduled_tasks", true, false, true, true },
{ "host_get_hosts_file", true, false, true, true },
// --- 终端 ---
{ "terminal_open", false, false, true, true },
{ "terminal_exec", false, true, false, true }, // 任意命令,后果由命令决定
{ "exec_command", false, true, false, true },
{ "terminal_close", false, false, true, true },
// --- 远程控制 ---
{ "remote_open", false, false, true, true },
{ "remote_close", false, false, true, true },
{ "remote_keyboard", false, false, false, true },
{ "remote_mouse", false, false, false, true },
{ "remote_clipboard", false, false, false, true }, // 覆盖对端剪贴板
// --- 文件传输 ---
{ "upload_file", false, true, false, true }, // 覆盖/新增远端文件
// --- 设备管理(McpManage)---
{ "kill_process", false, true, false, true },
{ "operate_window", false, true, false, true },
{ "control_service", false, true, true, true }, // start/stop/set_* 重复执行同一状态
{ "power_action", false, true, false, true },
// --- 主机管理 / 连接管理(McpMachine)---
{ "kill_network_connection", false, true, false, true },
{ "host_control_process", false, true, false, true },
{ "host_control_window", false, true, false, true },
{ "host_control_service", false, true, true, true },
{ "host_control_task", false, true, false, true },
{ "host_set_remark", false, false, true, false }, // 只写服务端主机库
{ "host_set_watch_level", false, false, true, false },
// --- 远程交谈(McpChat)---
{ "chat_open", false, false, false, true },
{ "chat_send", false, false, false, true },
{ "chat_wait", false, false, false, true }, // 会取走 inbox 消息,不是纯读
{ "chat_close", false, false, true, true },
};
} // namespace
void ApplyToolAnnotations(Json::Value& tools) {
if (!tools.isArray()) return;
for (Json::Value& tool : tools) {
if (!tool.isObject() || !tool["name"].isString()) continue;
const std::string name = tool["name"].asString();
bool readOnly = false, destructive = true, idempotent = false, openWorld = true;
for (const auto& h : kToolHints) {
if (name == h.name) {
readOnly = h.readOnly;
destructive = h.destructive;
idempotent = h.idempotent;
openWorld = h.openWorld;
break;
}
}
Json::Value ann(Json::objectValue);
ann["readOnlyHint"] = readOnly;
// 只读工具的 destructiveHint 按规范无意义,统一置 false,免得客户端误报「破坏性」。
ann["destructiveHint"] = readOnly ? false : destructive;
ann["idempotentHint"] = idempotent;
ann["openWorldHint"] = openWorld;
tool["annotations"] = ann;
}
}
} // namespace McpInternal
+115
View File
@@ -0,0 +1,115 @@
#pragma once
// MCP 工具实现共享的内部辅助函数。
//
// 这些函数原先都定义在 McpServer.cpp 的匿名命名空间里;主机管理 / 连接管理
// 工具族(McpMachine.cpp)需要复用同一套 JSON、host id 解析与编码转换逻辑,
// 故抽出到独立编译单元,由 McpServer.cpp 与 McpMachine.cpp 共同引用。
//
// 约定:函数语义与实现与抽取前完全一致(McpServer.cpp 通过 using-directive
// 引入,调用点不变),不做行为改动。
#include <Windows.h>
#include "jsoncpp/json.h"
#include <string>
#include <cstdint>
class CMy2015RemoteDlg;
class context;
namespace McpInternal {
// Json::Value → 紧凑 JSON 字符串
std::string JsonToString(const Json::Value& v);
// JSON-RPC 2.0 成功 / 错误响应
std::string BuildResult(const Json::Value& id, const Json::Value& result);
std::string BuildError(const Json::Value& id, int code, const std::string& msg);
// 仅 ASCII 小写化;不区分大小写的子串匹配
std::string ToLowerAscii(const std::string& s);
bool ContainsCI(const std::string& haystack, const std::string& needle);
// 入参读取
std::string JsonStrField(const Json::Value& v, const char* key);
bool IsDigits(const std::string& s);
std::string GetStringArg(const Json::Value& args, const char* key);
bool GetIntArg(const Json::Value& args, const char* key, int& out);
bool ReadUInt64(const Json::Value& v, uint64_t& out);
bool ReadUInt64Arg(const Json::Value& args, const char* key, uint64_t& out);
// 解析 id 入参(必填、纯数字)为 uint64;非法返回 false 并写 err。
bool ParseHostIdArg(const Json::Value& args, uint64_t& out, std::string& err);
// 在 m_HostList 中按 clientID 找在线主 context(锁内遍历 m_cs)。
context* FindMainContext(CMy2015RemoteDlg* parent, uint64_t id);
// 有界 strlen:p 最多可读 avail 字节,返回 n < avail 表示遇到 '\0'。
size_t BoundedStrlen(const char* p, size_t avail);
// 编码转换:任意代码页 → UTF-8(输出 JSON 用);UTF-8 → 目标代码页(下发客户端用)。
std::string ToUtf8(const char* s, UINT cp);
std::string ToAnsi(const std::string& utf8, UINT cp);
// 严格 UTF-8 → 目标代码页:任一字符无法表示即失败(不用 '?' 顶替)。
// UTF-8 本身非法也失败。聊天消息用它拒绝 GBK 不可表示的字符(emoji 等)。
bool Utf8ToCpExact(const std::string& utf8, UINT cp, std::string& out);
// 校验字节串是否为合法 UTF-8(n=0 视为合法)。
bool IsValidUtf8(const char* s, size_t n);
// 写操作审计:PostMessageA(WM_SHOWERRORMSG) 落到服务端消息/审计日志(不可关闭)。
void AuditManageAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail);
// 远程交谈审计:与 AuditManageAction 同落地方式,标题区分(MCP远程交谈)。
// 只记录会话 id / 字节数,绝不记录消息正文。
void AuditChatAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail);
// ===== 列表输出治理 =====
//
// 列表类工具统一走 limit/offset:默认 limit=100,硬上限 1000,offset 默认 0。
// structuredContent 里同时给出 total/totalAll/offset/limit/hasMore,与
// McpMachine.cpp 的 host_list_*/list_network_connections 保持同一套字段,
// 调用方据此翻页,而不是让一次返回把上下文撑爆。
struct PageWindow {
int offset = 0;
int limit = 100;
int total = 0; // ApplyPageWindow 填入:切片前的总条数(本工具无二次过滤,故等于 totalAll)
int totalAll = 0;
int returned = 0; // 本次实际返回条数
bool hasMore = false; // 窗口之后还有条目(供调用方判断是否继续翻页)
};
// 读 args 里的 limit/offset(缺省/非法/非正数按默认值,limit 超上限截断到上限)。
PageWindow ResolvePageWindow(const Json::Value& args, int defaultLimit = 100, int maxLimit = 1000);
// 按窗口切片:out = all[offset, offset+limit),并回填 w.total/totalAll/returned/hasMore。
void ApplyPageWindow(const Json::Value& all, PageWindow& w, Json::Value& out);
// 把 total/totalAll/offset/limit/hasMore 写进 structuredContent。
void WritePageFields(Json::Value& structuredContent, const PageWindow& w);
// 往 inputSchema 的 properties 追加 limit / offset 两个字段。
void AppendPagingProps(Json::Value& props, int defaultLimit = 100, int maxLimit = 1000);
// 往 inputSchema 的 properties 追加 ids(只读工具的批量入口,最多 50 个 id)。
void AppendBatchIdsProp(Json::Value& props);
// 把 inputSchema 的必填约束改成「id 或 ids 二选一」。
void MakeIdOrIdsRequired(Json::Value& schema);
// 统一的提示文字,例如「共 283 个进程,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」
std::string PageSummary(const PageWindow& w, const char* unit);
// ===== 工具注解(A3)=====
//
// 给 tools/list 里的每个工具补 MCP annotations(readOnlyHint / destructiveHint /
// idempotentHint / openWorldHint),让 MCP 客户端能按语义分组审批、默认折叠只读工具。
// 名称未在注解表里的工具按 schema 规范的默认值处理(destructiveHint=true),
// 即「新增工具必须显式登记」,漏登记只会更保守,不会误标成只读。
void ApplyToolAnnotations(Json::Value& tools);
} // namespace McpInternal
File diff suppressed because it is too large. Load diff
+31
View File
@@ -0,0 +1,31 @@
#pragma once
// 主机管理(10 个标签页)与连接管理(连接列表 / 强制断开)MCP 工具族。
//
// 协议(详见 docs/Mcp_Machine_Design.md):
// 主机管理:主连接 COMMAND_MACHINE_MANAGE(162) → 客户端 MachineManager 子连接回
// TOKEN_SYSINFOLIST(61) → 发 1 字节 tab(0..9) → 回 TOKEN_MACHINE_*(31..42)。
// 连接管理:主连接 COMMAND_CONNECTION(253) → CConnectionsManager 子连接回
// TOKEN_CONNECTION_LIST(255) → 发 254+原始 110 字节记录强制断开。
//
// 会话状态由 CMcpServer 持有(与 m_Pending 共用单飞行表),本模块只负责工具 schema、
// 参数校验、组包与解析。
#include "jsoncpp/json.h"
#include <string>
class CMy2015RemoteDlg;
namespace McpMachine {
// 是否由本模块处理(AppendTools 与 Call 必须保持一致)。
bool Handles(const std::string& toolName);
// 按当前开关(McpMachine / McpMachineDangerous / McpReadonly)追加可见工具。
void AppendTools(Json::Value& tools);
// 执行工具;返回完整 JSON-RPC 响应字符串(成功 = BuildResult,失败 = BuildError)。
std::string Call(const Json::Value& id, const std::string& toolName,
const Json::Value& args, CMy2015RemoteDlg* parent);
} // namespace McpMachine
File diff suppressed because it is too large. Load diff
+267 -1
View File
@@ -9,7 +9,10 @@
#include <condition_variable>
#include <map>
#include <set>
#include <unordered_map>
#include <vector>
#include <deque>
#include <memory>
#include <cstdint>
#include <ctime>
@@ -37,6 +40,14 @@ struct FileTransferEntry {
std::string sha256;
};
// 远程交谈消息(chat_wait 输出 messages[] 的一项)。
// text 为 UTF-8;at 为收到消息的 Unix 秒;id 为会话内单调递增序号。
struct ChatMessage {
uint64_t id = 0;
int64_t at = 0;
std::string text;
};
// MCP (Model Context Protocol) 服务端:httplib 封装 + JSON-RPC 2.0 分发 + 静态 token 校验。
// 与 CWebService 平级、互不依赖;默认禁用,经「扩展 → MCP设置」开启后监听
// (默认 127.0.0.1:6544,仅本机回环)。见 docs/Mcp_Design.md。
@@ -93,6 +104,31 @@ public:
// 等 TOKEN_FILE_LIST(调用方不关子链接)。
bool OnDriveList(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len);
// ===== B2:search_file(文件搜索,COMMAND_SEARCH_FILE → N×TOKEN_SEARCH_FILE_LIST
// + TOKEN_SEARCH_FILE_FINISH)=====
//
// 搜索结果是「流式多包」:客户端边搜边发,最后单独发一个 FINISH。子连接在 FINISH
// 之前绝不能关——客户端 CFileManager 的搜索线程持有 this 指针,连接在内搜索未停时
// 断开会让它访问已析构对象(客户端既有缺陷)。
//
// MessageHandle(TOKEN_SEARCH_FILE_LIST) 调用:挂起命中且为 search_file 则收下这一包。
// 超过收集上限时自行下发 COMMAND_FILES_SEARCH_STOP 并标记 truncated。
// 只接受来自登记过的那条子连接(pending.subCtx)的包:被放弃的旧搜索在设备重开后
// 仍可能吐尾包,按 context 身份区分,避免把旧搜索的结果/结束信号算到新搜索头上。
bool OnSearchFileRecords(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len);
// MessageHandle(TOKEN_SEARCH_FILE_FINISH) 调用:置 finished 并唤醒等待者。
// 同样只认 pending.subCtx 发来的 FINISH;其它子连接的 FINISH 只关它自己,不影响挂起。
void FinishSearchFile(uint64_t device_id, context* subCtx);
// 工具线程:等待搜索结束(或超时)。取走已收集的原始包;finished=false 表示还在搜。
bool WaitSearchFile(uint64_t device_id, std::vector<std::vector<BYTE>>& records,
bool& finished, bool& truncated, context*& subCtx, int timeoutMs);
// 工具线程:让客户端停止搜索(COMMAND_FILES_SEARCH_STOP,客户端会等搜索线程退出
// 后回 FINISH)。幂等。
void StopSearchFile(uint64_t device_id);
// ===== P3:list_registry(注册表查询,三阶段:COMMAND_REGEDIT → TOKEN_REGEDIT →
// COMMAND_REG_FIND → TOKEN_REG_PATH + TOKEN_REG_KEY)=====
@@ -242,6 +278,11 @@ public:
// 收尾:擦会话 + 锁外 CancelIO 文件管理器/流式两条子链接(幂等)。
void ClearFileTransfer(uint64_t device_id);
// 文件传输子链接断开(OfflineProc 调用):清反查表 + 置空裸指针,避免工具线程超时路径
// 对已回收(连接池复用)的 context 误 CancelIO。流式子链接断开 = 传输失败(1003);
// 文件管理器子链接断开只是少了收尾对象,传输数据走流式子链接,不判失败。
void OnFileTransferContextClosed(context* subCtx);
// ===== P7:设备管理控制(kill_process / operate_window / control_service / power_action)=====
// 写工具复用 m_Pending 单飞行;followUp/followUpSent/subCtx 标记接管进度。
// 「就绪 token」与「确认 token」是同一 token(客户端子连接构造即回一包,写后再回一包),
@@ -270,12 +311,123 @@ public:
// 超时路径不会对已回收(连接池复用)的 context 误 CancelIO。
void OnManageSubClosed(context* subCtx);
// ===== P8:主机管理 / 连接管理(子连接会话)=====
// 协议:主连接下发 COMMAND_MACHINE_MANAGE(162) / COMMAND_CONNECTION(253) → 客户端新建
// 子连接 → 子连接回就绪包(TOKEN_SYSINFOLIST=61 / TOKEN_CONNECTION_LIST=255)→ 在同一
// 子连接上多步收发。会话复用 m_Pending 表(统一「单设备单飞行」),kind 区分工具族。
// 见 docs/Mcp_Machine_Design.md。
void SetMachineEnabled(bool enabled) { m_machineEnabled = enabled; }
bool IsMachineEnabled() const { return m_machineEnabled; }
void SetMachineDangerousEnabled(bool enabled) { m_machineDangerousEnabled = enabled; }
bool IsMachineDangerousEnabled() const { return m_machineDangerousEnabled; }
// MessageHandle 顶部钩子(终端拦截之后、switch 之前):true = 本包已由 MCP 消费。
// 已绑定的子连接:只保存期望 token 的包与 TOKEN_MACHINE_MSG(42),其余丢弃。
// 未绑定的子连接:仅 61/255 可作为就绪包尝试绑定;否则返回 false(MFC 行为不变)。
bool OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len);
// OfflineProc 钩子:接管的子连接断开 → 置 closed 唤醒等待者(幂等)。
void OnManagedContextClosed(context* subCtx);
// 工具线程:登记会话(false = 该设备已有挂起请求在飞 → 设备忙)。
bool BeginMachineSession(uint64_t device_id, const std::string& tool, context* mainCtx);
bool BeginConnMgrSession(uint64_t device_id, const std::string& tool, context* mainCtx);
// ===== N3:键盘记录(get_keylog)=====
// 复用 P8 的会话表(PendingKind::Keylog,单设备单飞行),但不走「请求-响应」:
// 主连接下发 COMMAND_KEYBOARD(169) → 客户端新建子连接 → TOKEN_KEYBOARD_START(293)
// 作为就绪包绑定 → 之后客户端每约 1s 推一包 TOKEN_KEYBOARD_DATA(294) 击键文本,
// 服务端累积到 keylogBuf 由 WaitKeylogData 取走。独立开关 McpKeylog(默认关)。
// 见 docs/Mcp_Design.md。
void SetKeylogEnabled(bool enabled) { m_keylogEnabled = enabled; }
bool IsKeylogEnabled() const { return m_keylogEnabled; }
bool BeginKeylogSession(uint64_t device_id, const std::string& tool, context* mainCtx);
enum class KeylogWaitResult { Ok, Timeout, Closed };
// 取走累积字节并清零;timeoutMs 内无数据则 Timeout。truncated 回传是否已到上限。
KeylogWaitResult WaitKeylogData(uint64_t device_id, std::string& out,
int timeoutMs, bool& truncated);
// 工具线程:发命令前清空上一次响应并登记期望 token。
void ArmManagedResponse(uint64_t device_id, BYTE expectedToken);
// 工具线程:等待子连接就绪包 / 指定 token 的响应(超时由调用方按步给)。
enum class ManagedWaitResult { Ok, Timeout, Closed, ClientError };
ManagedWaitResult WaitManagedPacket(uint64_t device_id, BYTE token,
std::vector<BYTE>& out, context*& subCtxOut,
int timeoutMs, std::string& clientError);
// 工具线程:结束会话;cancelIo = 关闭子连接;markOrphan = 打 5s 墓碑
// (吸收迟到的 61/255,避免超时后弹出 MFC 对话框)。
void EndManagedSession(uint64_t device_id, bool cancelIo, bool markOrphan);
// ===== P9:远程交谈(chat_open / chat_send / chat_wait / chat_close)=====
// 复用 Windows 客户端既有「远程交谈」:主连接下发 COMMAND_CHAT(161) → 客户端新建子连接
// (先 TOKEN_CONN_AUTH(246) 再 TOKEN_CHAT_START(62))→ 服务端在该子连接回
// COMMAND_NEXT_CHAT(0) → 客户端弹 IDD_CHAT。之后双向文本为 raw CP936 + NUL。
// 协议不变(客户端聊天窗口已改为 Unicode 对话框,仅影响显示);独立 m_ChatMutex,
// 不与 P8 的 m_Pending 共享(不受单设备单飞行约束)。
// 见 docs/Mcp_Chat_Design.md。
void SetChatEnabled(bool enabled) { m_chatEnabled = enabled; }
bool IsChatEnabled() const { return m_chatEnabled; }
// MessageHandle 顶部钩子(MCP 终端之后、P8 之前:聊天文本首字节可能是 61/255/246)。
// true = 本包已由 MCP 消费。未绑定子连接上的 246(TOKEN_CONN_AUTH) 走快速路径返回
// false,交给认证分支;已绑定子连接上的 0xF6 前导字节文本则由本函数消费。
bool OnChatSubPacket(context* subCtx, const BYTE* data, ULONG len);
// OfflineProc 钩子:接管的子连接断开 → 会话 closed + 清路由 + 唤醒等待者(幂等)。
void OnChatContextClosed(context* subCtx);
// 工具线程:登记会话并发 COMMAND_CHAT 之后调用。false = 该设备已有未关闭会话(-32003)。
bool BeginChatOpen(uint64_t device_id, context* mainCtx, const std::string& sessionId);
// 工具线程:等待客户端子连接就绪且建窗等待期满(readyAt)。
enum class ChatReadyResult { Ok, Timeout, Closed, NotFound };
ChatReadyResult WaitChatReady(uint64_t device_id, const std::string& sessionId, int timeoutMs);
// 工具线程:发送前登记(校验 sessionId/started/readyAt/sendBusy)。输出 subCtx。
// 返回:0=ok;1=不存在/不匹配/未就绪/已关;2=忙。
int BeginChatSend(uint64_t device_id, const std::string& sessionId, context*& subCtx);
// 工具线程:发送结束(清 sendBusy)。closed 期间发送失败时调用方仍须调用。
void FinishChatSend(uint64_t device_id, const std::string& sessionId);
// 工具线程:取走最多 maxMessages 条;inbox 为空则等到 deadline / closed。
enum class ChatWaitResult { Ok, Timeout, Closed, NotFound, Mismatch, Busy };
ChatWaitResult WaitChatMessages(uint64_t device_id, const std::string& sessionId,
int timeoutMs, size_t maxMessages,
std::vector<ChatMessage>& out, bool& timedOut,
bool& closed, int& dropped);
// 关闭会话(校验 sessionId;标记 closed + 清路由 + 唤醒)。返回 0=已关;1=不存在(幂等);
// 2=sessionId 不匹配。子连接 [1] 与 CancelIO 由调用方在锁外执行。
int CloseChatSession(uint64_t device_id, const std::string& sessionId,
context*& subCtxOut, bool& hadSession);
// chat_open 超时/失败收尾:标记 closed + 清路由;已绑定子连接写入 subCtxOut(调用方 CancelIO),
// 未绑定则打 device/peer 5s 墓碑,吸收迟到的 62(避免超时后弹出 MFC 对话框)。
void AbortChatOpen(uint64_t device_id, context*& subCtxOut, bool& hadSession);
// idle 回收:关闭 lastActiveAt 超时且无等待/无发送的会话。返回回收数量。
int SweepIdleChats(time_t idleTimeoutSec);
// 安全配置(启动时由 CMy2015RemoteDlg 读 THIS_CFG 后设置)。
void SetReadonly(bool readonly) { m_readonly = readonly; }
void SetCmdWhitelist(const std::string& whitelist) { m_cmdWhitelist = whitelist; }
bool IsReadonly() const { return m_readonly; }
const std::string& GetCmdWhitelist() const { return m_cmdWhitelist; }
// 监听地址/端口(Start 时记录,供 get_server_status 报告)。
const std::string& GetBind() const { return m_bind; }
int GetPort() const { return m_port; }
// get_server_status:在飞会话与鉴权封禁计数。每类各取一次自己的锁,
// 返回前全部释放——调用方拿到的是「大致同一时刻」的估算值,不用来同步。
void GetRuntimeCounters(int& pending, int& terminal, int& screenCtrl,
int& fileXfer, int& chat, int& blockedIps);
private:
CMcpServer();
~CMcpServer();
@@ -285,10 +437,40 @@ private:
// POST /mcp 处理器:token 校验 + JSON-RPC 分发。
void HandleMcp(const httplib::Request& req, httplib::Response& res);
// ===== 鉴权加固 =====
// 同一 IP 在窗口期内连续鉴权失败达到阈值即封禁一段时间;封禁期内直接 429,不再比对 token。
bool IsAuthBlocked(const std::string& ip);
bool RecordAuthFailure(const std::string& ip); // 返回 true 表示本次失败触发了封禁
void ClearAuthFailures(const std::string& ip);
// 审计日志(<exe>\logs\mcp_audit.log):只写时间/IP/工具名/结果等元数据,
// 绝不写 token、Authorization 头、请求参数或返回内容。
void AuditMcpEvent(const char* event, const std::string& ip, const std::string& detail);
static void AppendAuditFile(const std::string& line);
struct AuthFailRecord {
int count = 0;
std::chrono::steady_clock::time_point windowStart;
std::chrono::steady_clock::time_point blockedUntil;
};
std::mutex m_AuthMutex;
std::unordered_map<std::string, AuthFailRecord> m_AuthFails;
// 挂起请求类型:主机管理/连接管理会话与既有一次性请求共用 m_Pending 保证单设备单飞行,
// 但 MessageHandle 的 P2b/P3/P7 拦截分支(IsPending/TakeMainResponse)必须把这两类排除,
// 否则用户手动打开对话框时 UI 包会被 MCP 抢走。
enum class PendingKind { Generic, FollowUp, Machine, ConnMgr, Keylog };
static bool KindAcceptsToken(PendingKind kind, BYTE token);
bool BeginManagedSession(uint64_t device_id, const std::string& tool,
PendingKind kind, context* mainCtx);
httplib::Server m_server;
std::thread m_thread;
std::atomic<bool> m_running{false};
std::string m_token;
std::string m_bind; // Start 传入的监听地址
int m_port = 0; // Start 传入的监听端口
CMy2015RemoteDlg* m_parent = nullptr;
// 挂起请求注册表(受 m_PendingMutex 保护,键 = device_id)。
@@ -306,11 +488,52 @@ private:
std::vector<BYTE> followUp; // 接管后下发的写命令 payload(首字节 = 写命令)
bool followUpSent = false; // false=等子连接就绪(首包);true=已发写命令、等确认包
context* subCtx = nullptr; // 接管的子连接(超时/失败 CancelIO 用,防孤儿子连接)
// ===== P8:主机管理 / 连接管理会话(kind = Machine / ConnMgr 时有效)=====
PendingKind kind = PendingKind::Generic;
context* mainCtx = nullptr; // Begin 时抓取的主连接(只作身份校验,不从其收发)
std::string peer; // mainCtx->GetPeerName()(老客户端子连接 ID=0 时兜底)
BYTE expectedToken = 0; // 期望的响应 token(0 = 未设置)
bool hasResponse = false;
std::vector<BYTE> response; // 含首字节 token
std::string clientError; // TOKEN_MACHINE_MSG(42) 文本(已转 UTF-8)
bool closed = false; // 子连接在等待期间断开
std::chrono::steady_clock::time_point deadline; // 整个会话的截止时间
// ===== N3:键盘记录(kind = Keylog 时有效)=====
std::string keylogBuf; // 累积的原始击键字节(客户端编码,未含 token)
bool keylogTruncated = false; // 已到字节上限,后续数据被丢弃
// ===== B2:search_file(tool == "search_file" 时有效)=====
std::vector<std::vector<BYTE>> searchRecords; // 已收集的 TOKEN_SEARCH_FILE_LIST 原始包
size_t searchBytes = 0;
bool searchFinished = false; // 已收到 TOKEN_SEARCH_FILE_FINISH
bool searchStopSent = false; // 已下发 COMMAND_FILES_SEARCH_STOP
bool searchTruncated = false; // 命中收集上限,后续匹配被丢弃
};
std::mutex m_PendingMutex;
std::condition_variable m_PendingCv;
std::map<uint64_t, PendingRequest> m_Pending;
// ===== P8:子连接路由(受 m_PendingMutex 保护)=====
// 已绑定子连接 → device(该子连接的一切包都由 MCP 消费)。
std::map<context*, uint64_t> m_SubCtxToDevice;
// CancelIO 之后仍可能到达的包:静默丢弃(避免子连接回收前的尾巴包弹对话框)。
std::set<context*> m_AbsorbedSubCtx;
// 会话异常结束后 5s 内的迟到就绪包墓碑(device / peer 两个维度)。
struct OrphanMark {
std::chrono::steady_clock::time_point expiry;
PendingKind kind = PendingKind::Generic;
};
std::map<uint64_t, OrphanMark> m_OrphanByDevice;
std::map<std::string, OrphanMark> m_OrphanByPeer;
// 清理过期墓碑(持 m_PendingMutex 调用)。
void PruneOrphanMarksLocked(std::chrono::steady_clock::time_point now);
// 路由表大小(已绑定 + 已吸收的子连接数)。MessageHandle 每个包都会调用
// OnManagedSubPacket,若无会话在飞则用它无锁快速返回,避免音频/屏幕等高频
// 子连接逐包争用 m_PendingMutex。只在持锁时更新(store)。
std::atomic<int> m_ManagedRoutes{0};
void RefreshManagedRoutesLocked();
// get_screenshot 的 reqId 发生器(16 位,跳过 0)。与 MFC 预览的 m_PreviewReqId 各自独立计数。
std::atomic<uint16_t> m_PreviewReqId{1};
@@ -365,7 +588,7 @@ private:
uint32_t directoryCount = 0; // 目录项计数(目录不发 COMPLETE 包)
uint32_t filesDone = 0; // 已完成的文件数(含跳过的)
bool done = false; // 全部完成或出错
int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时
int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时;1003=流式子连接断线
std::map<uint32_t, FileTransferEntry> fileEntries; // fileIndex → {path,size,sha256}
std::set<uint32_t> skipIndexes; // overwrite=false 跳过的 fileIndex
std::vector<FileTransferEntry> skipped; // 跳过的文件(供输出)
@@ -374,6 +597,46 @@ private:
std::mutex m_FileXferMutex;
std::condition_variable m_FileXferCv;
std::map<uint64_t, FileTransferSession> m_FileXferSessions; // device_id → 会话
// 子连接反查(受 m_FileXferMutex 保护):OfflineProc 拿不到 device_id,只能按 context* 找会话。
std::map<context*, uint64_t> m_FileXferContextToDevice;
// ===== P9:远程交谈(受 m_ChatMutex 保护;单设备单会话)=====
// 用 shared_ptr 持有会话:chat_wait / chat_send 在工作线程里复制一份后,即使 map 条目
// 被 chat_close 或断线删除也安全,不需要额外的「迭代器有效」规则。
struct ChatSession {
std::string sessionId;
context* mainCtx = nullptr; // 主连接(仅身份校验)
uint64_t mainClientId = 0;
context* subCtx = nullptr; // 已绑定的子连接;关闭后置空
std::string peer; // GetPeerName()(老客户端 clientID=0 兜底)
bool started = false; // 已收到 TOKEN_CHAT_START 并回 [0]
bool closed = false;
bool sendBusy = false; // 同一会话串行发送
bool waitBusy = false; // 同一会话只允许一个 chat_wait
std::chrono::steady_clock::time_point readyAt; // 建窗等待期满(绑定 + 1000ms)
time_t lastActiveAt = 0;
std::deque<ChatMessage> inbox; // 未投递消息(UTF-8)
size_t inboxBytes = 0;
uint64_t nextMsgId = 1;
int dropped = 0; // inbox 溢出丢弃的条数(chat_wait 报告)
};
using ChatSessionPtr = std::shared_ptr<ChatSession>;
std::mutex m_ChatMutex;
std::condition_variable m_ChatCv;
std::map<uint64_t, ChatSessionPtr> m_ChatSessions; // device_id → 会话
std::map<context*, uint64_t> m_ChatContextToDevice; // subCtx → device_id(顶部路由)
std::set<context*> m_ChatAbsorbedSubCtx; // CancelIO 后尾巴包静默丢弃
struct ChatOrphanMark { std::chrono::steady_clock::time_point expiry; };
std::map<uint64_t, ChatOrphanMark> m_ChatOrphanByDevice; // 迟到 62 墓碑(5s)
std::map<std::string, ChatOrphanMark> m_ChatOrphanByPeer;
std::atomic<int> m_ChatRoutes{0}; // 路由集合大小(快速路径)
bool m_chatEnabled = false; // P9 开关(默认关)
// 持 m_ChatMutex 调用:只更新 m_ChatRoutes(store,relaxed 读取在锁外)。
void RefreshChatRoutesLocked();
// 持 m_ChatMutex 调用:清理过期墓碑。
void PruneChatOrphansLocked(std::chrono::steady_clock::time_point now);
bool m_readonly = true;
std::string m_cmdWhitelist;
@@ -381,6 +644,9 @@ private:
bool m_remoteControlEnabled = false; // 远程控制开关(默认关;要求 m_readonly=false)
bool m_fileTransferEnabled = false; // 文件传输开关(默认关;download_file)
bool m_manageEnabled = false; // P7 管理控制开关(默认关;要求 m_readonly=false)
bool m_machineEnabled = false; // P8 主机管理族总开关(默认关;16 个 host_* 工具)
bool m_machineDangerousEnabled = false; // P8 高风险子集(冻结/解冻进程、停止/重启服务)
bool m_keylogEnabled = false; // N3 键盘记录开关(默认关;get_keylog)
};
// 全局访问器(仿 WebService(),见 WebService.h 末尾)
+59 -4
View File
@@ -106,7 +106,7 @@ INT_PTR CMcpSettingsDlg::DoModal()
{
USES_CONVERSION;
CString title = _TR("MCP设置");
BuildDialogTemplate(m_Template, T2CW(title), 320, 420);
BuildDialogTemplate(m_Template, T2CW(title), 320, 540);
InitModalIndirect((LPCDLGTEMPLATE)m_Template.data());
return CDialog::DoModal();
}
@@ -148,6 +148,18 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnManage.Create(_TR("启用管理操作(进程/窗口/服务/电源)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_MANAGE);
m_btnMachine.Create(_TR("启用主机管理(进程/窗口/服务/任务/网络状态)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_MACHINE);
m_btnMachineDangerous.Create(_TR("启用危险主机操作(冻结/解冻进程、停止/重启服务)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_MACHINE_DANGEROUS);
m_btnChat.Create(_TR("启用远程交谈(AI 与用户对话)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_CHAT);
m_btnKeylog.Create(_TR("启用键盘记录(AI 采集击键)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_KEYLOG);
m_lblWhitelist.Create(_TR("命令白名单"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editWhitelist.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP |
ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL,
@@ -172,6 +184,10 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnRemoteControl.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnFileTransfer.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnManage.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnMachine.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnMachineDangerous.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnChat.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnKeylog.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_lblWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_editWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnOK.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
@@ -189,6 +205,10 @@ BOOL CMcpSettingsDlg::OnInitDialog()
int remoteControl = THIS_CFG.GetInt("settings", "McpRemoteControl", 0);
int fileTransfer = THIS_CFG.GetInt("settings", "McpFileTransfer", 0);
int manage = THIS_CFG.GetInt("settings", "McpManage", 0);
int machine = THIS_CFG.GetInt("settings", "McpMachine", 0);
int machineDangerous = THIS_CFG.GetInt("settings", "McpMachineDangerous", 0);
int chat = THIS_CFG.GetInt("settings", "McpChat", 0);
int keylog = THIS_CFG.GetInt("settings", "McpKeylog", 0);
std::string whitelist = THIS_CFG.GetStr("settings", "McpCmdWhitelist", "");
m_btnEnable.SetCheck(enabled ? BST_CHECKED : BST_UNCHECKED);
@@ -200,6 +220,10 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnRemoteControl.SetCheck(remoteControl ? BST_CHECKED : BST_UNCHECKED);
m_btnFileTransfer.SetCheck(fileTransfer ? BST_CHECKED : BST_UNCHECKED);
m_btnManage.SetCheck(manage ? BST_CHECKED : BST_UNCHECKED);
m_btnMachine.SetCheck(machine ? BST_CHECKED : BST_UNCHECKED);
m_btnMachineDangerous.SetCheck(machineDangerous ? BST_CHECKED : BST_UNCHECKED);
m_btnChat.SetCheck(chat ? BST_CHECKED : BST_UNCHECKED);
m_btnKeylog.SetCheck(keylog ? BST_CHECKED : BST_UNCHECKED);
// 白名单存储为逗号分隔,展示为每行一条。
m_editWhitelist.SetWindowText(CString(WhitelistForDisplay(whitelist).c_str()));
@@ -220,6 +244,18 @@ void CMcpSettingsDlg::OnOK()
bool remoteControl = (m_btnRemoteControl.GetCheck() == BST_CHECKED);
bool fileTransfer = (m_btnFileTransfer.GetCheck() == BST_CHECKED);
bool manage = (m_btnManage.GetCheck() == BST_CHECKED);
bool machine = (m_btnMachine.GetCheck() == BST_CHECKED);
bool machineDangerous = (m_btnMachineDangerous.GetCheck() == BST_CHECKED);
bool chat = (m_btnChat.GetCheck() == BST_CHECKED);
bool keylog = (m_btnKeylog.GetCheck() == BST_CHECKED);
// 危险子集依附于主机管理总开关:没开主机管理就没有工具可放开,直接清除并提示。
if (machineDangerous && !machine) {
machineDangerous = false;
m_btnMachineDangerous.SetCheck(BST_UNCHECKED);
MessageBoxL(_TR("危险主机操作依附于主机管理:请先启用主机管理。"), _TR("提示"),
MB_ICONWARNING);
}
// 端口校验:1-65535
int port = atoi(CT2A(sPort));
@@ -247,14 +283,21 @@ void CMcpSettingsDlg::OnOK()
THIS_CFG.SetInt("settings", "McpRemoteControl", remoteControl ? 1 : 0);
THIS_CFG.SetInt("settings", "McpFileTransfer", fileTransfer ? 1 : 0);
THIS_CFG.SetInt("settings", "McpManage", manage ? 1 : 0);
THIS_CFG.SetInt("settings", "McpMachine", machine ? 1 : 0);
THIS_CFG.SetInt("settings", "McpMachineDangerous", machineDangerous ? 1 : 0);
THIS_CFG.SetInt("settings", "McpChat", chat ? 1 : 0);
THIS_CFG.SetInt("settings", "McpKeylog", keylog ? 1 : 0);
std::string whitelist = CT2A(sWhitelist);
whitelist = NormalizeWhitelist(whitelist);
THIS_CFG.SetStr("settings", "McpCmdWhitelist", whitelist);
// 拆成两段可翻译的单行键,中间用 \r\n 连接(多行键无法在 INI 中表示)
// 拆成多段可翻译的单行键,中间用 \r\n 连接(多行键无法在 INI 中表示)
MessageBox(_TR("MCP 设置已保存。") + _T("\r\n") +
_TR("启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作的改动需重启程序生效。") + _T("\r\n") +
_TR("持久终端、远程控制与管理操作仅在只读模式关闭时生效。"),
_TR("启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作/主机管理/危险主机操作的改动需重启程序生效。") + _T("\r\n") +
_TR("持久终端、远程控制与管理操作仅在只读模式关闭时生效。") + _T("\r\n") +
_TR("主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。") + _T("\r\n") +
_TR("远程交谈开关的改动需重启程序生效。") + _T("\r\n") +
_TR("键盘记录开关的改动需重启程序生效。"),
_TR("提示"), MB_ICONINFORMATION);
CDialog::OnOK();
@@ -300,6 +343,18 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
m_btnManage.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnMachine.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnMachineDangerous.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnChat.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnKeylog.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
const int whitelistH = 90;
m_lblWhitelist.MoveWindow(margin, y, labelW, rowH);
m_editWhitelist.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, whitelistH);
+8
View File
@@ -32,6 +32,10 @@ private:
IDC_MCP_REMOTECONTROL = 1008, // 「启用远程控制」复选框(AI 操控桌面,要求只读关)
IDC_MCP_FILETRANSFER = 1009, // 「启用文件传输」复选框(download_file,不要求只读关)
IDC_MCP_MANAGE = 1010, // 「启用管理操作」复选框(kill/窗口/服务/电源,要求只读关)
IDC_MCP_MACHINE = 1011, // 「启用主机管理」复选框(host_* 工具族)
IDC_MCP_MACHINE_DANGEROUS = 1012, // 「启用危险主机操作」复选框(冻结/停止/重启)
IDC_MCP_CHAT = 1013, // 「启用远程交谈」复选框(chat_* 工具族,不要求只读关)
IDC_MCP_KEYLOG = 1014, // 「启用键盘记录」复选框(get_keylog,不要求只读关)
};
CButton m_btnEnable;
@@ -42,6 +46,10 @@ private:
CButton m_btnRemoteControl;
CButton m_btnFileTransfer;
CButton m_btnManage;
CButton m_btnMachine;
CButton m_btnMachineDangerous;
CButton m_btnChat;
CButton m_btnKeylog;
CStatic m_lblWhitelist;
CEdit m_editWhitelist;
CButton m_btnOK, m_btnCancel;
+2 -1
View File
@@ -205,7 +205,8 @@ void NotifyManager::BuildHostOnlineEmail(context* ctx, const std::string& matche
// Get host info
std::string computerName = CT2A(ctx->GetClientData(ONLINELIST_COMPUTER_NAME), CP_UTF8);
std::string ip = CT2A(ctx->GetClientData(ONLINELIST_IP), CP_UTF8);
std::string location = CT2A(ctx->GetClientData(ONLINELIST_LOCATION), CP_UTF8);
// 地理位置已统一按 UTF-8 存储(见 AddList),直接透传,不再 CP_ACP→UTF-8 二次转换。
std::string location = ctx->GetClientData(ONLINELIST_LOCATION).GetString();
std::string os = CT2A(ctx->GetClientData(ONLINELIST_OS), CP_UTF8);
std::string version = CT2A(ctx->GetClientData(ONLINELIST_VERSION), CP_UTF8);
+4
View File
@@ -102,6 +102,10 @@ void CPluginSettingsDlg::InitListCtrl()
GetDlgItem(IDC_STATIC_PLUGIN_INTERVAL)->SetWindowText(_TR("间隔(秒):"));
GetDlgItem(IDC_STATIC_PLUGIN_COUNTER)->SetWindowText(_TR("最大次数:"));
SetWindowText(_TR("插件设置"));
// 按钮文字来自对话框模板,非中文系统上会被系统 ACP 转成 "??",须显式设置(参照 NotifySettingsDlg)
SetDlgItemText(IDC_BTN_SAVE, _TR("保存"));
SetDlgItemText(IDOK, _TR("关闭"));
}
void CPluginSettingsDlg::LoadPluginsToList()
+21 -1
View File
@@ -124,11 +124,31 @@ protected:
{
CDialog::OnInitDialog();
// 非中文系统上 MBCS 对话框模板的中文会被系统 ACP 转成 "?",TranslateDialog
// 拿到的是已乱码文本无法还原,故在此显式设置(参照 NotifySettingsDlg)。
// 均经 _TR/_L 支持多语言翻译。
SetWindowText(_TR("远程桌面质量等级"));
SetDlgItemText(IDC_QLEVEL_LABEL_LEVEL, _TR("等级"));
SetDlgItemText(IDC_QLEVEL_LABEL_FPS, _TR("帧率(FPS)"));
SetDlgItemText(IDC_QLEVEL_LABEL_WIDTH, _TR("最大宽度"));
SetDlgItemText(IDC_QLEVEL_LABEL_ALGO, _TR("编码算法"));
SetDlgItemText(IDC_QLEVEL_LABEL_BITRATE, _TR("码率(kbps)"));
static const TCHAR* kLevelNames[QUALITY_COUNT] = {
_T("Ultra 极佳"), _T("High 优秀"), _T("Good 良好"),
_T("Medium 一般"), _T("Low 较差"), _T("Minimal 最低")
};
for (int i = 0; i < QUALITY_COUNT; i++)
SetDlgItemText(IDC_QLEVEL_LABEL_LEVEL0 + i, _L(kLevelNames[i]));
SetDlgItemText(IDC_QLEVEL_LABEL_HINT,
_TR("最大宽度 0 表示原始分辨率;DIFF/RGB565 适合局域网,H264 适合跨网"));
SetDlgItemText(IDC_QLEVEL_RESET, _TR("恢复默认"));
SetDlgItemText(IDOK, _TR("确定"));
SetDlgItemText(IDCANCEL, _TR("取消"));
for (int i = 0; i < QUALITY_COUNT; i++) {
m_working[i] = m_profiles[i];
}
LoadToControls();
TranslateDialog(this);
return TRUE;
}
+203 -1
View File
@@ -13,6 +13,7 @@
#include "CGridDialog.h"
#include "2015RemoteDlg.h"
#include "CPasswordDlg.h"
#include "InputDlg.h"
#include "CDlgFileSend.h"
#include <file_upload.h>
#include <md5.h>
@@ -707,6 +708,9 @@ BOOL CScreenSpyDlg::OnInitDialog()
Mprintf("[ScreenSpy] Dialog created for device %llu, isMfcSession=%d, isWebSession=%d\n",
m_ClientID, isMfcSession ? 1 : 0, m_bIsWebSession.load() ? 1 : 0);
// 逐主机鼠标坐标补偿。必须在用户开始操作前加载;默认 1.0 不影响任何主机。
LoadMouseScale();
// 获取默认 IME 上下文(ImmAssociateContext 返回之前关联的上下文)
// 先禁用再恢复,以获取原始上下文句柄
m_hOldIMC = ImmAssociateContext(m_hWnd, NULL);
@@ -728,6 +732,7 @@ BOOL CScreenSpyDlg::OnInitDialog()
SysMenu->AppendMenuL(MF_STRING, IDM_REMOTE_CURSOR, "使用远程光标(&C)");
SysMenu->AppendMenuL(MF_STRING, IDM_ADAPTIVE_SIZE, "自适应窗口大小(&A)");
SysMenu->AppendMenuL(MF_STRING, IDM_TRACE_CURSOR, "跟踪被控端鼠标(&T)");
SysMenu->AppendMenuL(MF_STRING, IDM_MOUSE_CALIB, "鼠标坐标校准(&M)");
SysMenu->AppendMenuL(MF_STRING, IDM_BLOCK_INPUT, "锁定被控端鼠标和键盘(&L)");
SysMenu->AppendMenuL(MF_STRING, IDM_RESTORE_CONSOLE, "RDP会话归位(&R)");
// 只在虚拟桌面模式下显示重置选项
@@ -1126,6 +1131,10 @@ VOID CScreenSpyDlg::OnReceiveComplete()
case TOKEN_CLIPBOARD_TEXT: {
Buffer str = m_ContextObject->InDeCompressedBuffer.GetMyBuffer(1);
UpdateServerClipboard(str.c_str(), str.length());
// 反向回传:远程剪贴板文本(UTF-8)→ Web 客户端
if (m_bIsWebSession && WebService().IsRunning()) {
WebService().NotifyClipboardText(m_ClientID, std::string(str.c_str(), str.length()));
}
break;
}
case TOKEN_BITMAPINFO: {
@@ -1138,6 +1147,8 @@ VOID CScreenSpyDlg::OnReceiveComplete()
m_ClientID = *((uint64_t*)(m_ContextObject->InDeCompressedBuffer.GetBuffer(1 + sizeof(BITMAPINFOHEADER))));
}
PrepareDrawing(m_BitmapInfor_Full);
// 重连或切换显示器后重新校验鼠标补偿(客户端上报分辨率可能已变化)。
LoadMouseScale();
// 分辨率切换完成,允许解码
m_bResolutionChanging = false;
// Notify web clients of resolution change (only for Web session dialogs)
@@ -2117,6 +2128,10 @@ void CScreenSpyDlg::OnSysCommand(UINT nID, LPARAM lParam)
m_ContextObject->Send2Client(cmd, sizeof(cmd));
break;
}
case IDM_MOUSE_CALIB: { // 鼠标坐标校准(逐主机,默认 1.0)
ShowMouseCalibration();
break;
}
case IDM_SAVEDIB: { // 快照保存
SaveSnapshot();
break;
@@ -2718,12 +2733,199 @@ void CScreenSpyDlg::SendScaledMouseMessage(MSG* pMsg, bool makeLP)
low = x + m_ulHScrollPos;
high = y + m_ulVScrollPos;
}
// 逐主机鼠标坐标补偿(系统菜单「鼠标坐标校准」)。默认 1.0,对所有主机无影响。
// 客户端若用错误的逻辑分辨率换算坐标(见 macos/ScreenHandler.mm),注入点会随
// 离左上角的距离线性偏移;这里先按 真实分辨率 ÷ 上报分辨率 缩放,抵消其换算。
// 注意:补偿后坐标可以超出位图尺寸(例如 y 需要 1096 才能落到 1023 行),
// 因此不按位图边界裁剪,只做 16 位协议范围裁剪。
if (m_mouseScaleX != 1.0)
low = (LONG)(low * m_mouseScaleX + 0.5);
if (m_mouseScaleY != 1.0)
high = (LONG)(high * m_mouseScaleY + 0.5);
low = max(0L, min(low, 65535L));
high = max(0L, min(high, 65535L));
if (makeLP) msg.lParam = MAKELPARAM(low, high);
msg.pt.x = low;
msg.pt.y = high;
SendCommand(&msg);
}
// 解析客户端上报的分辨率 "N:WxH"(N=显示器数)。失败返回 false。
static bool ParseReportedResolution(const CString& res, int& w, int& h)
{
int colon = res.Find(':');
if (colon < 0) return false;
CString dims = res.Mid(colon + 1);
int sep = dims.FindOneOf(_T("xX*,"));
if (sep <= 0) return false;
w = _ttoi(dims.Left(sep));
h = _ttoi(dims.Mid(sep + 1));
return w > 0 && h > 0;
}
// 自动建议补偿系数。只针对已确诊的情形:Mac 客户端 + 画面与上报分辨率在两轴上
// 比例不一致(旧 Mac 客户端用 [NSScreen mainScreen] 的逻辑尺寸做坐标换算)。
// 建议值 = 画面尺寸 ÷ 上报尺寸,前提是抓屏显示器为标准 1× 分辨率(非 Retina)且
// 画质档位没有压缩画面宽度;两者任一不成立时用户需手工修正。
// 两轴比例一致说明客户端换算正常(Retina 下画面与上报同为一个缩放倍数),不补偿。
static bool SuggestMouseScale(const CString& clientType, int imgW, int imgH,
int repW, int repH, double& sx, double& sy)
{
if (clientType != _T("MAC"))
return false;
if (imgW <= 0 || imgH <= 0 || repW <= 0 || repH <= 0)
return false;
double rx = (double)imgW / repW;
double ry = (double)imgH / repH;
double lo = min(rx, ry), hi = max(rx, ry);
if (lo <= 0.0 || hi / lo <= 1.02) // 两轴一致:正常客户端,无需补偿
return false;
if (rx < 0.2 || rx > 5.0 || ry < 0.2 || ry > 5.0)
return false;
sx = rx;
sy = ry;
return true;
}
void CScreenSpyDlg::LoadMouseScale()
{
m_mouseScaleX = m_mouseScaleY = 1.0;
m_mouseScaleFromConfig = false;
std::string raw = THIS_CFG.GetStr("mouse_scale", std::to_string(m_ClientID));
if (raw.empty()) return;
// 格式: "sx,sy,refRepW,refRepH[,refImgW,refImgH]"。后两项是校准时的画面尺寸,
// 用于识别抓屏显示器是否已切换;旧记录没有后两项,退化为按上报/画面比例判断。
double sx = 1.0, sy = 1.0;
int refW = 0, refH = 0, refImgW = 0, refImgH = 0;
int fields = sscanf_s(raw.c_str(), "%lf,%lf,%d,%d,%d,%d",
&sx, &sy, &refW, &refH, &refImgW, &refImgH);
if (fields != 4 && fields != 6) {
Mprintf("[MouseScale] device %llu: invalid config '%s'\n", m_ClientID, raw.c_str());
return;
}
if (!(sx >= 0.2 && sx <= 5.0 && sy >= 0.2 && sy <= 5.0)) {
Mprintf("[MouseScale] device %llu: out of range %.4f,%.4f\n", m_ClientID, sx, sy);
return;
}
// 1.0 等价于“无补偿”(用户复位后留下的记录),按未校准处理,允许重新自动建议。
if (sx == 1.0 && sy == 1.0)
return;
// 校准记录绑定当时的「客户端上报分辨率」。客户端修复后上报值会变,旧系数会变成
// 二次补偿(反而更偏),因此上报值不一致时自动失效。refW/refH=0 表示上报值不可用,
// 无法校验,按配置生效。
int curW = 0, curH = 0;
bool haveRep = false;
context* mainCtx = m_pParent ? m_pParent->FindHost(m_ClientID) : nullptr;
if (mainCtx && ParseReportedResolution(mainCtx->GetAdditionalData(RES_RESOLUTION), curW, curH))
haveRep = true;
if (refW > 0 && refH > 0 && haveRep && (curW != refW || curH != refH)) {
Mprintf("[MouseScale] device %llu: reported %dx%d != calibrated %dx%d, override disabled\n",
m_ClientID, curW, curH, refW, refH);
return;
}
// 校准记录还绑定当时的「画面(抓屏)宽高比」。切换显示器后(例如外接屏切回内置屏)
// 画面比例会变,旧系数不能再套用;切回原显示器时比例恢复,系数自动重新生效。
// 客户端修复后同一次会话内画面比例不变,但上报值会变,仍由上面的检查兜底。
int curImgW = m_BitmapInfor_Full ? m_BitmapInfor_Full->bmiHeader.biWidth : 0;
int curImgH = m_BitmapInfor_Full ? abs(m_BitmapInfor_Full->bmiHeader.biHeight) : 0;
if (curImgW > 0 && curImgH > 0) {
if (refImgW > 0 && refImgH > 0) {
double refAspect = (double)refImgW / refImgH;
double curAspect = (double)curImgW / curImgH;
if (fabs(curAspect / refAspect - 1.0) > 0.02) {
Mprintf("[MouseScale] device %llu: frame %dx%d (aspect %.3f) != calibrated aspect %.3f, override disabled\n",
m_ClientID, curImgW, curImgH, curAspect, refAspect);
return;
}
} else if (haveRep && curW > 0 && curH > 0) {
// 旧格式没记录画面比例:只有当前画面与上报分辨率两轴比例不一致(即客户端
// 仍存在换算偏差)时才套用;两轴一致说明换算正常(例如切回内置屏),不补偿。
double rx = (double)curImgW / curW;
double ry = (double)curImgH / curH;
double lo = min(rx, ry), hi = max(rx, ry);
if (lo <= 0.0 || hi / lo <= 1.02) {
Mprintf("[MouseScale] device %llu: frame %dx%d matches reported %dx%d, override disabled\n",
m_ClientID, curImgW, curImgH, curW, curH);
return;
}
}
}
m_mouseScaleX = sx;
m_mouseScaleY = sy;
m_mouseScaleFromConfig = true;
Mprintf("[MouseScale] device %llu: apply x%.4f y%.4f\n", m_ClientID, sx, sy);
}
void CScreenSpyDlg::ShowMouseCalibration()
{
int imgW = m_BitmapInfor_Full ? m_BitmapInfor_Full->bmiHeader.biWidth : 0;
int imgH = m_BitmapInfor_Full ? abs(m_BitmapInfor_Full->bmiHeader.biHeight) : 0;
CString reported, clientType;
int repW = 0, repH = 0;
context* mainCtx = m_pParent ? m_pParent->FindHost(m_ClientID) : nullptr;
if (mainCtx) {
reported = mainCtx->GetAdditionalData(RES_RESOLUTION);
ParseReportedResolution(reported, repW, repH);
clientType = mainCtx->GetAdditionalData(RES_CLIENT_TYPE);
}
// 没有保存过系数时,按「画面 ÷ 上报」自动填入建议值(无需手工计算);
// 保存过的系数优先展示,避免覆盖用户手工微调的结果。
double sx = m_mouseScaleX, sy = m_mouseScaleY;
bool autoFilled = !m_mouseScaleFromConfig
&& SuggestMouseScale(clientType, imgW, imgH, repW, repH, sx, sy);
// 提示文本走 CInputDialog 的 m_sTipInfo(DDV 上限 64 字符),保持简短。
CString tip;
if (autoFilled)
tip = _TR("已按 画面/上报 自动填写,可修改");
else
tip.Format(_TR("画面 %dx%d;上报 %s;系数为真实除以上报"),
imgW, imgH, reported.IsEmpty() ? _T("-") : reported.GetString());
CString xStr, yStr;
xStr.Format(_T("%.4f"), sx);
yStr.Format(_T("%.4f"), sy);
CInputDialog dlg(this);
dlg.Init(_TR("鼠标坐标校准"), _TR("X 轴缩放系数"));
dlg.m_str = xStr;
dlg.Init2(_TR("Y 轴缩放系数"), yStr);
dlg.m_sTipInfo = tip;
if (dlg.DoModal() != IDOK)
return;
sx = _ttof(dlg.m_str);
sy = _ttof(dlg.m_sSecondInput);
if (!(sx >= 0.2 && sx <= 5.0 && sy >= 0.2 && sy <= 5.0)) {
MessageBox(_TR("缩放系数需在 0.2 到 5.0 之间。"), _TR("鼠标坐标校准"), MB_ICONWARNING);
return;
}
// 记录上报分辨率 + 画面尺寸,供下次加载时判断系数是否仍然适用(切换显示器后失效)。
CString val;
if (sx == 1.0 && sy == 1.0) {
// 1.0 表示不补偿;写成等价的空记录,下次打开对话框仍会按当前画面自动建议。
val = _T("1.0,1.0,0,0");
m_mouseScaleFromConfig = false;
} else {
val.Format(_T("%.6f,%.6f,%d,%d,%d,%d"), sx, sy, repW, repH, imgW, imgH);
m_mouseScaleFromConfig = true;
}
THIS_CFG.SetStr("mouse_scale", std::to_string(m_ClientID), val.GetString());
m_mouseScaleX = sx;
m_mouseScaleY = sy;
Mprintf("[MouseScale] device %llu: saved x%.4f y%.4f (reported %dx%d)\n",
m_ClientID, sx, sy, repW, repH);
}
VOID CScreenSpyDlg::SendCommand(const MYMSG* Msg)
{
if (!m_bIsCtrl)
@@ -3643,7 +3845,7 @@ void CScreenSpyDlg::OnDropFiles(HDROP hDropInfo)
memcpy((char*)szBuffer + 1 + masterId.length(), hmac.c_str(), hmac.length());
memcpy(szBuffer + 1 + 80, str.data(), str.size());
auto md5 = CalcMD5FromBytes((BYTE*)str.data(), str.size());
m_pParent->m_CmdList.PutCmd(md5);
m_pParent->m_CmdList.PutCmd(md5, m_ContextObject->GetPeerName());
m_ContextObject->Send2Client(szBuffer, 81 + str.size());
Mprintf("【拖拽】 [本地 -> 远程] V1 传输: %s\n", md5.c_str());
SAFE_DELETE_ARRAY(szBuffer);
+8
View File
@@ -141,6 +141,7 @@ enum {
IDM_AUDIO_TOGGLE, // 音频开关
IDM_ENABLE_H264_HARD,
IDM_ENABLE_AV1_HARD,
IDM_MOUSE_CALIB, // 鼠标坐标校准(逐主机补偿客户端坐标换算偏差)
};
// 状态信息窗口 - 全屏时显示帧率/速度/质量
@@ -243,6 +244,13 @@ public:
CCursorInfo m_CursorInfo; //自定义的一个系统的光标类
VOID SendCommand(const MYMSG* Msg);
void SendScaledMouseMessage(MSG* pMsg, bool makeLP);
// 鼠标坐标补偿:默认 1.0(不补偿)。用于客户端上报的逻辑分辨率与实际显示不一致
// (例如合盖后用外接显示器的 Mac)时,抵消客户端在 OnReceive 里的错误换算。
double m_mouseScaleX = 1.0;
double m_mouseScaleY = 1.0;
bool m_mouseScaleFromConfig = false; // 当前系数来自已保存配置(否则对话框可自动建议)
void LoadMouseScale(); // 从配置读取本主机的补偿系数(会校验上报分辨率)
void ShowMouseCalibration();// 系统菜单「鼠标坐标校准」入口
VOID UpdateServerClipboard(char *szBuffer,ULONG ulLength);
VOID SendServerClipboard(void);
+6
View File
@@ -277,6 +277,12 @@ void CSearchBarDlg::DoSearch()
colText = ctx->GetClientData(col);
}
// 地理位置列已统一按 UTF-8 存储(见 AddList),而搜索输入是 CP_ACP;
// 转回 CP_ACP 再比对,否则按中文位置搜索会因编码不一致而失配。
if (col == ONLINELIST_LOCATION) {
colText = CString(Utf8ToAnsi(std::string(colText.GetString())).c_str());
}
colText.MakeLower();
if (colText.Find(searchText) >= 0) {
matched = true;
+31
View File
@@ -329,6 +329,17 @@ public:
#define PREALLOC_DECOMPRESS_SIZE (4 * 1024)
#include "context.h"
// 每连接传输层状态(单向 TLS,见 docs/TransportTLS_MFCServer_Design.md §5.2)。
// 明文与 TLS 客户端在同一端口共存:首包按 ClientHello 头嗅探分派。
enum ServerTlsState {
TLS_Unclassified = 0, // 尚未收到足够字节判定(缓冲 tlsPreClassify)
TLS_Plain = 1, // 明文客户端,直通现有解析路径
TLS_Handshaking = 2, // TLS 客户端,握手线程阻塞 AcceptSecurityContext 中
TLS_Ready = 3, // TLS 握手完成,收包解密 / 发包加密
};
class ServerTlsSession; // 定义见 ServerTlsSession.h(避免把 Schannel 头拖进本文件)
typedef class CONTEXT_OBJECT : public context
{
public:
@@ -341,6 +352,7 @@ public:
FreeDecompressBuffer();
FreeCompressBuffer();
FreeSendCompressBuffer();
FreeTls();
if (Zcctx) {
ZSTD_freeCCtx(Zcctx);
Zcctx = nullptr;
@@ -377,6 +389,11 @@ public:
ikcpcb* kcp = nullptr; // 新增,指向KCP会话
std::string GroupName; // 分组名称
CLock SendLock; // fix #214
// 发送是否处于「进行中」状态。OnClientPreSending 每次 Send2Client 都会 Post 一个
// IOWrite,若不加节制,OnClientPostSending(0) 会对同一 OutCompressedBuffer 并发发起
// 多个 WSASend,读到同一段可变内存(背靠背小包最易触发:resize→COMMAND_NEXT→resize)。
// 置位后抑制多余的 IOWrite,待缓冲排空(最后一个 WSASend 完成)再清零。仅受 SendLock 保护。
bool bSendPending = false;
time_t OnlineTime = 0; // 上线时间
time_t LastHeartbeatTime = 0; // 最后心跳时间
@@ -392,6 +409,11 @@ public:
// 试用版反代理逐连接检测器。仅由 IOCPServer 的 RTT 轮询线程访问,免锁。
TcpRttBreachDetector m_RttDetector;
// ---- 单向 TLS 状态(跨线程:握手线程写入 TLS_Ready,工作线程读取;用 atomic 保序)----
std::atomic<int> tlsState{ TLS_Unclassified }; // ServerTlsState
ServerTlsSession* tls = nullptr; // 每连接 TLS 会话(握手线程独占→就绪后共用)
std::vector<BYTE> tlsPreClassify; // 分类前缓冲的首批字节(嗅探 ClientHello 头)
// 子连接身份校验:客户端发 TOKEN_CONN_AUTH 通过验证后置位。
// 主连接(走 TOKEN_LOGIN 流程)不参与此机制。当前阶段宽容(未通过也接受),
// 仅作为标记供后续命令处理 / 未来收紧策略使用。
@@ -495,6 +517,9 @@ public:
}
}
// 释放每连接 TLS 会话。定义在 ServerTlsSession.cpp(需 ServerTlsSession 完整类型才能 delete)。
void FreeTls();
std::string GetProtocol() const override
{
return Parser.m_Masker && Parser.m_Masker->GetMaskType() == MaskTypeNone ? "TCP" : "HTTP";
@@ -539,6 +564,12 @@ public:
m_RttUs.store(0, std::memory_order_release);
m_LastRttSampleMs.store(0, std::memory_order_release);
m_RttDetector.Reset();
// 复用对象池时重置 TLS 状态:释放旧会话、回到未分类、清空嗅探缓冲。
FreeTls();
tlsState.store(TLS_Unclassified, std::memory_order_release);
tlsPreClassify.clear();
// 复用对象池时清空发送进行中标志,避免上次连接残留的 bSendPending 抑制新连接的发送。
bSendPending = false;
}
void SetAuthenticated(bool v) { m_bAuthenticated.store(v, std::memory_order_release); }
bool IsAuthenticated() const { return m_bAuthenticated.load(std::memory_order_acquire); }
+604
View File
@@ -0,0 +1,604 @@
// ServerTlsSession.cpp — 服务端单向 TLS(Schannel 入站)实现
//
// 与客户端 TlsChannel.cpp 对称,但走 AcceptSecurityContext 入站握手、DecryptMessage/
// EncryptMessage 流式加解密。证书/私钥加载为 PEM + CNG(NCryptImportKey PKCS#8),
// 以便与 Go 服务端(server/go 的 crypto/tls,YAMA_TLS_CERT/KEY)共用同一对密钥。
#include "StdAfx.h"
#include "ServerTlsSession.h"
#include "Server.h" // CONTEXT_OBJECT::FreeTls()
#include "common/iniFile.h" // config(GetInt/GetStr)
#include <ncrypt.h>
#include <bcrypt.h>
#include <fstream>
#include <iterator>
#include <sstream>
#pragma comment(lib, "secur32.lib")
#pragma comment(lib, "crypt32.lib")
#pragma comment(lib, "ncrypt.lib")
namespace
{
// 进程级身份(进程启动加载一次;未来 UI/指令热切换时改为引用计数 + 惰性释放)。
std::mutex g_identityMtx;
bool g_enabled = false;
bool g_ready = false;
bool g_loadError = false;
CredHandle g_cred = {};
bool g_credValid = false;
PCCERT_CONTEXT g_cert = NULL; // 与入站凭据同生命周期,FreeIdentity 时释放
NCRYPT_KEY_HANDLE g_persistedKey = 0; // 已持久化到 CNG KSP 的私钥句柄,FreeIdentity 时删除
// 持久化私钥在 CNG KSP 中的名字。用固定名 + NCRYPT_OVERWRITE_KEY_FLAG,重启时覆盖旧键,
// 避免残留;同名键的密钥材料与 server.key 相同,覆盖无副作用。
const wchar_t* g_keyName = L"YamaServerTlsKey";
// 一次性读文件为 std::string(二进制安全)。
bool ReadFileText(const std::string& path, std::string& out)
{
std::ifstream f(path, std::ios::binary);
if (!f.is_open())
return false;
std::ostringstream ss;
ss << f.rdbuf();
if (f.bad())
return false;
out = ss.str();
return true;
}
// PEM(-----BEGIN ...----- 包裹的 base64)解码为 DER。失败返回 false。
// CRYPT_STRING_ANY 会自动识别带头的 base64(PEM),对证书与 PKCS#8 私钥均适用。
bool PemToDer(const std::string& pem, std::vector<BYTE>& der)
{
if (pem.empty())
return false;
DWORD need = 0;
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
NULL, &need, NULL, NULL))
return false;
der.resize(need);
return CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
der.data(), &need, NULL, NULL) == TRUE;
}
// 从 PEM 文本里定位私钥块的类型,用于给出可操作的错误提示。
enum KeyFmt { KF_PKCS8, KF_PKCS1, KF_UNKNOWN };
KeyFmt DetectKeyFormat(const std::string& keyPem)
{
if (keyPem.find("-----BEGIN PRIVATE KEY-----") != std::string::npos)
return KF_PKCS8;
if (keyPem.find("-----BEGIN RSA PRIVATE KEY-----") != std::string::npos ||
keyPem.find("-----BEGIN EC PRIVATE KEY-----") != std::string::npos)
return KF_PKCS1;
return KF_UNKNOWN;
}
}
// =====================================================================================
// ServerTlsIdentity —— 进程级服务端身份(可重入加载,禁止 call_once,供未来热切换)
// =====================================================================================
void ServerTlsIdentity::FreeIdentity()
{
// 先释放凭据,再释放证书上下文,最后删除持久化私钥(凭据/证书可能仍按名引用该键)。
if (g_credValid)
{
FreeCredentialsHandle(&g_cred);
g_credValid = false;
}
g_cred = {};
if (g_cert)
{
CertFreeCertificateContext(g_cert);
g_cert = NULL;
}
if (g_persistedKey)
{
NCryptDeleteKey(g_persistedKey, 0); // 删除并释放句柄
g_persistedKey = 0;
}
}
bool ServerTlsIdentity::Load(config& cfg)
{
std::lock_guard<std::mutex> lk(g_identityMtx);
bool enabled = cfg.GetInt("tls", "Enabled", 0) != 0;
std::string certPath = cfg.GetStr("tls", "CertPath", "");
std::string keyPath = cfg.GetStr("tls", "KeyPath", "");
g_enabled = enabled;
// 先释放旧身份(本轮只在启动时调用一次,不存在「旧身份仍被并发握手使用」的问题;
// 未来热切换需先引用计数、再惰性释放旧凭据)。
FreeIdentity();
g_ready = false;
g_loadError = false;
if (!enabled)
{
Mprintf("[TLS] server TLS disabled ([tls] Enabled=0) — plaintext only\n");
return true;
}
if (certPath.empty() || keyPath.empty())
{
g_loadError = true;
Mprintf("[TLS] FATAL: [tls] Enabled=1 but CertPath/KeyPath empty; "
"refusing TLS ClientHello (fail-closed)\n");
return false;
}
if (!LoadIdentity(certPath, keyPath))
{
g_loadError = true;
return false;
}
g_ready = true;
Mprintf("[TLS] server TLS enabled: cert=%s key=%s\n", certPath.c_str(), keyPath.c_str());
return true;
}
bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::string& keyPath)
{
std::string certPem, keyPem;
if (!ReadFileText(certPath, certPem))
{
Mprintf("[TLS] FATAL: cannot read cert file %s\n", certPath.c_str());
return false;
}
if (!ReadFileText(keyPath, keyPem))
{
Mprintf("[TLS] FATAL: cannot read key file %s\n", keyPath.c_str());
return false;
}
// 1) 证书:PEM → DER → PCCERT_CONTEXT。
std::vector<BYTE> certDer;
if (!PemToDer(certPem, certDer))
{
Mprintf("[TLS] FATAL: cert file %s is not a valid PEM\n", certPath.c_str());
return false;
}
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING,
certDer.data(), (DWORD)certDer.size());
if (cert == NULL)
{
Mprintf("[TLS] FATAL: CertCreateCertificateContext failed (%u)\n", GetLastError());
return false;
}
// 2) 私钥:PEM → DER → 持久化到 CNG KSP(仅支持 PKCS#8;PKCS#1 给出可操作的转换提示)。
//
// 关键:Schannel 入站凭据(AcquireCredentialsHandle)需要「能按名重开」的持久化私钥。
// NCryptImportKey 产出的是匿名临时键,绑定 CERT_NCRYPT_KEY_HANDLE_PROP_ID 后 Schannel 仍
// 拿不到(AcquireCredentialsHandle 返回 SEC_E_NO_CREDENTIALS 0x8009030e)。因此先把
// PKCS#8 导入为临时键、导出为裸 RSA 私钥 BLOB(NCryptSetProperty 只认裸 BLOB,不认
// PKCS#8),再写入持久化键并 finalize,最后用 CERT_KEY_PROV_INFO_PROP_ID 按名引用。
std::vector<BYTE> keyDer;
NCRYPT_KEY_HANDLE persistedKey = 0;
if (DetectKeyFormat(keyPem) == KF_PKCS8)
{
if (!PemToDer(keyPem, keyDer))
{
Mprintf("[TLS] FATAL: key file %s is not a valid PEM\n", keyPath.c_str());
CertFreeCertificateContext(cert);
return false;
}
// 显式打开 Microsoft Software Key Storage Provider。hProvider 传 NULL 会让
// NCryptImportKey 走「默认提供者」解析,实测返回 NTE_INVALID_HANDLE(0x80090026),
// 故必须显式取得 KSP 句柄(临时键独立于 hProv,导入后即可释放)。
NCRYPT_PROV_HANDLE hProv = 0;
SECURITY_STATUS st = NCryptOpenStorageProvider(&hProv, MS_KEY_STORAGE_PROVIDER, 0);
if (st != ERROR_SUCCESS)
{
Mprintf("[TLS] FATAL: NCryptOpenStorageProvider failed 0x%08x\n", (unsigned)st);
CertFreeCertificateContext(cert);
return false;
}
// 2a) PKCS#8 → 临时键。
NCRYPT_KEY_HANDLE tmp = 0;
st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, NULL,
&tmp, keyDer.data(), (DWORD)keyDer.size(), 0);
if (st == ERROR_SUCCESS)
{
// 2b) 允许明文导出,导出为裸 RSA 私钥 BLOB。
DWORD policy = NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | NCRYPT_ALLOW_EXPORT_FLAG;
NCryptSetProperty(tmp, NCRYPT_EXPORT_POLICY_PROPERTY, (PBYTE)&policy, sizeof(policy), 0);
std::vector<BYTE> raw;
DWORD rawLen = 0;
st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL, NULL, 0, &rawLen, 0);
if (st == ERROR_SUCCESS)
{
raw.resize(rawLen);
st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL,
raw.data(), rawLen, &rawLen, 0);
}
// 2c) 写入持久化键并 finalize(落到 KSP,可被 Schannel 按名重开)。
if (st == ERROR_SUCCESS)
st = NCryptCreatePersistedKey(hProv, &persistedKey, BCRYPT_RSA_ALGORITHM,
g_keyName, AT_KEYEXCHANGE, NCRYPT_OVERWRITE_KEY_FLAG);
if (st == ERROR_SUCCESS)
st = NCryptSetProperty(persistedKey, BCRYPT_RSAFULLPRIVATE_BLOB,
raw.data(), (DWORD)raw.size(), 0);
if (st == ERROR_SUCCESS)
st = NCryptFinalizeKey(persistedKey, 0);
NCryptFreeObject(tmp);
}
NCryptFreeObject(hProv);
if (st != ERROR_SUCCESS)
{
Mprintf("[TLS] FATAL: failed to persist PKCS#8 key for %s (0x%08x)\n",
keyPath.c_str(), (unsigned)st);
if (persistedKey)
NCryptFreeObject(persistedKey);
CertFreeCertificateContext(cert);
return false;
}
}
else
{
// PKCS#1(RSA/EC PRIVATE KEY)或未知格式:本次不支持,给转换命令。
Mprintf("[TLS] FATAL: key file %s must be PKCS#8 (-----BEGIN PRIVATE KEY-----). "
"Convert with: openssl pkcs8 -topk8 -nocrypt -in %s -out %s\n",
keyPath.c_str(), keyPath.c_str(), keyPath.c_str());
CertFreeCertificateContext(cert);
return false;
}
// 3) 绑定私钥到证书上下文:按名引用持久化键。Schannel 经 CryptAcquireCertificatePrivateKey
// 在 MS_KEY_STORAGE_PROVIDER 里用 pwszContainerName 重开该键。
CRYPT_KEY_PROV_INFO provInfo = {};
provInfo.pwszContainerName = (LPWSTR)g_keyName;
provInfo.pwszProvName = (LPWSTR)MS_KEY_STORAGE_PROVIDER;
provInfo.dwProvType = 0; // 0 = CNG(无 CAPI provider type)
provInfo.dwKeySpec = AT_KEYEXCHANGE;
if (!CertSetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, 0, &provInfo))
{
Mprintf("[TLS] FATAL: CertSetCertificateContextProperty(CERT_KEY_PROV_INFO_PROP_ID) "
"failed (%u)\n", GetLastError());
NCryptDeleteKey(persistedKey, 0); // 删除并释放句柄
CertFreeCertificateContext(cert);
return false;
}
// 绑定后持久化键句柄交进程级 g_persistedKey,随 FreeIdentity 删除(覆盖旧键,避免残留)。
g_persistedKey = persistedKey;
// 4) 入站凭据:显式指定服务端证书,不请求客户端证书(单向 TLS)。
SCHANNEL_CRED sc = {};
sc.dwVersion = SCHANNEL_CRED_VERSION;
sc.cCreds = 1;
sc.paCred = &cert;
sc.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER;
// NO_DEFAULT_CREDS 避免回退到系统默认凭据,确保只用我们提供的证书/私钥。
//(单向 TLS 不请求客户端证书,故无需 SCH_CRED_MANUAL_CRED_VALIDATION。)
sc.dwFlags = SCH_CRED_NO_DEFAULT_CREDS;
TimeStamp tsExpiry = {};
SECURITY_STATUS st = AcquireCredentialsHandleA(
NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider", SECPKG_CRED_INBOUND,
NULL, &sc, NULL, NULL, &g_cred, &tsExpiry);
if (st != SEC_E_OK)
{
Mprintf("[TLS] FATAL: AcquireCredentialsHandle(SECPKG_CRED_INBOUND) failed 0x%08x\n",
(unsigned)st);
CertFreeCertificateContext(cert); // 无凭据引用,安全释放
g_cred = {};
if (g_persistedKey) // 回滚:删除已持久化的私钥,避免残留
{
NCryptDeleteKey(g_persistedKey, 0); // 删除并释放句柄
g_persistedKey = 0;
}
return false;
}
// 成功:把证书上下文生命周期交给进程级 g_cert,随 FreeIdentity 释放,
// 保证在 FreeCredentialsHandle 之前私钥一直可用。
g_cert = cert;
g_credValid = true;
return true;
}
bool ServerTlsIdentity::IsEnabled()
{
std::lock_guard<std::mutex> lk(g_identityMtx);
return g_enabled;
}
bool ServerTlsIdentity::IsReady()
{
std::lock_guard<std::mutex> lk(g_identityMtx);
return g_ready && g_credValid;
}
bool ServerTlsIdentity::IsLoadError()
{
std::lock_guard<std::mutex> lk(g_identityMtx);
return g_loadError;
}
CredHandle ServerTlsIdentity::Cred()
{
std::lock_guard<std::mutex> lk(g_identityMtx);
return g_cred;
}
// =====================================================================================
// ServerTlsSession —— 单连接会话(握手 + 加解密)
// =====================================================================================
void ServerTlsSession::CloseHandles()
{
if (m_ctxValid)
{
DeleteSecurityContext(&m_ctx);
m_ctxValid = false;
}
m_ctx = {};
m_ready = false;
m_raw.clear();
}
// 握手线程在 IOCP 的子套接字上做同步 I/O。该套接字可能是非阻塞的(监听套接字经
// WSAEventSelect 置为非阻塞后,accept 出的子套接字继承非阻塞态;线程里 FIONBIO=0 也
// 不一定即时生效)。故 recv/send 遇 WSAEWOULDBLOCK 时用 select 等可读/可写再重试,
// 而非当致命错误,避免「客户端回包还没到就误判握手失败」。
static bool WaitSocketReady(SOCKET sock, bool forRead, int timeoutMs)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(sock, &fds);
timeval tv;
tv.tv_sec = timeoutMs / 1000;
tv.tv_usec = (timeoutMs % 1000) * 1000;
return select(0, forRead ? &fds : NULL, forRead ? NULL : &fds, NULL, &tv) > 0;
}
bool ServerTlsSession::SendAll(SOCKET sock, const void* data, int len)
{
const BYTE* p = (const BYTE*)data;
int sent = 0;
while (sent < len)
{
int n = send(sock, (const char*)p + sent, len - sent, 0);
if (n == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
{
if (!WaitSocketReady(sock, false, 15000))
return false;
continue; // 非阻塞套接字发送缓冲满:等可写后重试
}
if (n <= 0)
return false;
sent += n;
}
return true;
}
bool ServerTlsSession::Handshake(SOCKET sock, const BYTE* initial, int initialLen)
{
std::lock_guard<std::mutex> lk(m_mtx);
if (m_ctxValid)
CloseHandles(); // 防御:会话应只握手一次
CredHandle cred = ServerTlsIdentity::Cred();
// 单向 TLS:服务端不请求客户端证书,故无需 ASC_REQ_MANUAL_CRED_VALIDATION
//(该标志只在 mTLS 校验客户端证书时有意义;SDK 的 ASC 命名空间里亦无此常量)。
DWORD req = ASC_REQ_SEQUENCE_DETECT | ASC_REQ_REPLAY_DETECT | ASC_REQ_CONFIDENTIALITY |
ASC_REQ_ALLOCATE_MEMORY | ASC_REQ_STREAM;
std::vector<BYTE> hs(initial, initial + initialLen);
CtxtHandle ctx = {};
bool ctxValid = false;
TimeStamp tsExpiry = {};
ULONG attrs = 0;
SECURITY_STATUS sc = SEC_I_CONTINUE_NEEDED;
for (;;)
{
SecBuffer inBufs[2] = {
{ (ULONG)hs.size(), SECBUFFER_TOKEN, hs.empty() ? NULL : hs.data() },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc inDesc = { SECBUFFER_VERSION, 2, inBufs };
SecBuffer outBuf = { 0, SECBUFFER_TOKEN, NULL };
SecBufferDesc outDesc = { SECBUFFER_VERSION, 1, &outBuf };
sc = AcceptSecurityContext(&cred, ctxValid ? &ctx : NULL, &inDesc, req,
SECURITY_NATIVE_DREP, ctxValid ? NULL : &ctx,
&outDesc, &attrs, &tsExpiry);
ctxValid = true;
// 发出服务端握手记录(ServerHello/Certificate/... 或 Finished)。
if (outBuf.cbBuffer > 0 && outBuf.pvBuffer)
{
bool ok = SendAll(sock, outBuf.pvBuffer, (int)outBuf.cbBuffer);
FreeContextBuffer(outBuf.pvBuffer);
if (!ok)
{
sc = SEC_E_INTERNAL_ERROR;
break;
}
}
// 计算已消费字节:SECBUFFER_EXTRA 里是「未消费的尾部」(下一条握手消息 / 首条应用数据)。
// 必须在 SEC_E_OK / 失败判定之前处理:否则握手完成时 hs 里仍混着已消费的握手记录,
// 紧跟 Finished 的首条应用数据(客户端登录包)会随 hs 一起被丢弃,导致随机丢包。
if (inBufs[1].BufferType == SECBUFFER_EXTRA)
{
int extra = (int)inBufs[1].cbBuffer;
hs.erase(hs.begin(), hs.begin() + (hs.size() - extra));
}
else if (sc != SEC_E_INCOMPLETE_MESSAGE && sc != SEC_I_INCOMPLETE_CREDENTIALS)
{
hs.clear(); // 已全部消费,继续等下一轮握手消息
}
// 否则:SEC_E_INCOMPLETE_MESSAGE —— 保留 hs(不完整消息),续收补齐。
if (sc == SEC_E_OK)
break;
if (FAILED(sc) && sc != SEC_E_INCOMPLETE_MESSAGE && sc != SEC_I_INCOMPLETE_CREDENTIALS)
{
Mprintf("[TLS] AcceptSecurityContext failed 0x%08x (in=%u consumed? extra=%u)\n",
(unsigned)sc, inBufs[0].cbBuffer, inBufs[1].BufferType == SECBUFFER_EXTRA ? inBufs[1].cbBuffer : 0);
break; // 真正的失败
}
char raw[8192];
int r;
for (;;)
{
r = recv(sock, raw, sizeof(raw), 0);
if (r == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
{
if (!WaitSocketReady(sock, true, 15000))
{
r = SOCKET_ERROR;
break; // 等可读超时
}
continue; // 非阻塞套接字暂无数据:等可读后重试
}
break;
}
if (r <= 0)
{
Mprintf("[TLS] handshake recv failed/EOF (r=%d err=%d)\n", r, WSAGetLastError());
sc = SEC_E_INTERNAL_ERROR;
break;
}
hs.insert(hs.end(), (BYTE*)raw, (BYTE*)raw + r);
}
if (sc != SEC_E_OK)
{
Mprintf("[TLS] handshake failed: final status 0x%08x (fail-closed)\n", (unsigned)sc);
if (ctxValid)
DeleteSecurityContext(&ctx);
return false;
}
// 握手成功后 hs 里残留的「未消费尾部」是紧跟 Finished 的首条应用数据(TLS 记录)。
// 交给 Decrypt 处理,否则首包会丢(表现为随机登录超时/重连/协议错位)。
if (!hs.empty())
m_raw.insert(m_raw.end(), hs.begin(), hs.end());
// 查询流式记录尺寸(加密封装用)。
SecPkgContext_StreamSizes sizes = {};
if (QueryContextAttributes(&ctx, SECPKG_ATTR_STREAM_SIZES, &sizes) != SEC_E_OK)
{
DeleteSecurityContext(&ctx);
return false;
}
m_ctx = ctx;
m_ctxValid = true;
m_sizes = sizes;
m_ready = true;
return true;
}
int ServerTlsSession::Decrypt(const BYTE* cipher, int len, std::vector<BYTE>& plain)
{
std::lock_guard<std::mutex> lk(m_mtx);
if (!m_ready)
return -1;
if (len <= 0)
return 0;
m_raw.insert(m_raw.end(), cipher, cipher + len);
for (;;)
{
SecBuffer bufs[4] = {
{ (ULONG)m_raw.size(), SECBUFFER_DATA, m_raw.empty() ? NULL : m_raw.data() },
{ 0, SECBUFFER_EMPTY, NULL },
{ 0, SECBUFFER_EMPTY, NULL },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc desc = { SECBUFFER_VERSION, 4, bufs };
SECURITY_STATUS sc = DecryptMessage(&m_ctx, &desc, 0, NULL);
if (sc == SEC_E_INCOMPLETE_MESSAGE)
break; // 记录不完整,等下一轮 WSARecv
if (sc == SEC_I_CONTEXT_EXPIRED) {
Mprintf("[TLS] DecryptMessage: peer close_notify (SEC_I_CONTEXT_EXPIRED)\n");
return -1; // 对端 close_notify / 会话结束
}
if (sc == SEC_I_RENEGOTIATE || FAILED(sc)) {
Mprintf("[TLS] DecryptMessage failed 0x%08x (raw=%u)\n", (unsigned)sc, (unsigned)m_raw.size());
return -1;
}
int decLen = (int)bufs[1].cbBuffer;
const BYTE* p = (const BYTE*)bufs[1].pvBuffer;
int extra = (bufs[3].BufferType == SECBUFFER_EXTRA) ? (int)bufs[3].cbBuffer : 0;
int consumed = (int)m_raw.size() - extra;
if (decLen > 0 && p)
plain.insert(plain.end(), p, p + decLen);
m_raw.erase(m_raw.begin(), m_raw.begin() + consumed);
if (m_raw.empty())
break;
}
return 0;
}
int ServerTlsSession::Encrypt(const BYTE* plain, int len, std::vector<BYTE>& wire)
{
std::lock_guard<std::mutex> lk(m_mtx);
if (!m_ready)
return -1;
if (len <= 0)
return 0;
ULONG maxMsg = m_sizes.cbMaximumMessage > 0 ? m_sizes.cbMaximumMessage : 16384;
int total = 0;
while (total < len)
{
int chunk = (len - total > (int)maxMsg) ? (int)maxMsg : (len - total);
std::vector<BYTE> rec(m_sizes.cbHeader + chunk + m_sizes.cbTrailer);
BYTE* hdr = rec.data();
BYTE* body = hdr + m_sizes.cbHeader;
BYTE* trailer = body + chunk;
memcpy(body, plain + total, chunk);
SecBuffer bufs[4] = {
{ m_sizes.cbHeader, SECBUFFER_STREAM_HEADER, hdr },
{ (ULONG)chunk, SECBUFFER_DATA, body },
{ m_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, trailer },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc desc = { SECBUFFER_VERSION, 4, bufs };
SECURITY_STATUS sc = EncryptMessage(&m_ctx, 0, &desc, 0);
if (FAILED(sc))
return -1; // 握手已建立,此处失败视为致命(调用方关闭连接)
int wireLen = (int)(bufs[0].cbBuffer + bufs[1].cbBuffer + bufs[2].cbBuffer);
wire.insert(wire.end(), rec.data(), rec.data() + wireLen);
total += chunk;
}
return total;
}
// =====================================================================================
// CONTEXT_OBJECT::FreeTls —— 释放每连接 TLS 会话(定义在此以便 delete 完整类型)
// =====================================================================================
void CONTEXT_OBJECT::FreeTls()
{
delete tls;
tls = NULL;
}
+92
View File
@@ -0,0 +1,92 @@
// ServerTlsSession.h — MFC 服务端单向 TLS(Schannel 入站)会话封装
//
// 与客户端 TlsChannel 对称:客户端走 InitializeSecurityContext(出站),本类走
// AcceptSecurityContext(入站)。单向 TLS:不请求/校验客户端证书,客户端身份仍由
// 隧道内登录(V1 PwdHmac / V2 ECDSA)承担。
//
// 分层:
// ServerTlsIdentity —— 进程级「服务端身份」(证书 + 私钥 → 入站凭据)。可重入加载
// (Load 禁止用 call_once,供未来 UI/指令热切换),本轮启动时加载一次。
// ServerTlsSession —— 每条连接一个,持有握手/加解密所需的 Schannel 上下文与缓冲,
// 随 CONTEXT_OBJECT 池化复用而重建。
//
// 线程模型:Handshake 在专用握手线程上阻塞执行(方案 A);握手完成后,Decrypt 由
// IOCP 工作线程调用(每连接同一时刻只有一个未决 WSARecv,天然串行)、Encrypt 在
// SendLock 内调用。Schannel 上下文非线程安全,故 Encrypt/Decrypt 内部以 m_mtx 互斥。
//
// 选型:Schannel(Windows 原生 SSPI),secur32.lib / crypt32.lib / ncrypt.lib 系统库。
// 证书/私钥为 PEM(与 Go 服务端 YAMA_TLS_CERT/KEY 同构,可共用同一对密钥);私钥
// 须为 PKCS#8(-----BEGIN PRIVATE KEY-----),见 ServerTlsSession.cpp 的加载实现。
#pragma once
#include <WinSock2.h>
#ifndef SECURITY_WIN32
#define SECURITY_WIN32 1
#endif
#include <security.h>
#include <schannel.h>
#include <mutex>
#include <string>
#include <vector>
class config; // common/iniFile.h(仅需引用,避免把 ini 头拖进 Server.h 的 include 图)
// ---- 进程级服务端身份(证书 + 私钥),可重入加载(禁止 call_once,供未来热切换)----
class ServerTlsIdentity
{
public:
// 从 cfg(THIS_CFG)读 [tls] 节:Enabled / CertPath / KeyPath,并加载身份。
// 返回 true 表示「配置已生效」(开关关、或开关开且身份加载成功);开关开但加载
// 失败时返回 false 且 IsLoadError()==true,服务端须对 TLS ClientHello fail-closed。
static bool Load(config& cfg);
static bool IsEnabled(); // [tls] Enabled != 0
static bool IsReady(); // 开关开 && 身份加载成功(有可用入站凭据)
static bool IsLoadError(); // 开关开 && 身份加载失败(fail-closed)
// 入站凭据(AcquireCredentialsHandle 产出)。返回拷贝;句柄值本身可安全拷贝。
static CredHandle Cred();
private:
static void FreeIdentity();
static bool LoadIdentity(const std::string& certPath, const std::string& keyPath);
};
// ---- 单连接服务端 TLS 会话(握手 + 加解密)----
class ServerTlsSession
{
public:
ServerTlsSession() {}
~ServerTlsSession() { CloseHandles(); }
ServerTlsSession(const ServerTlsSession&) = delete;
ServerTlsSession& operator=(const ServerTlsSession&) = delete;
// 阻塞式服务端握手(方案 A:专用握手线程上调用)。initial/initialLen 是嗅探阶段已
// 收到的 ClientHello 字节(可能只是分片;内部按 SEC_E_INCOMPLETE_MESSAGE 续收补齐)。
// 成功返回 true,失败 false(调用方关闭连接,fail-closed)。
bool Handshake(SOCKET sock, const BYTE* initial, int initialLen);
// 解密:把本次 WSARecv 收到的密文 cipher[0..len] 喂入,把能解出的明文追加到 plain。
// 返回 0 = 成功(可能无明文);-1 = 错误 / 对端 close_notify(调用方关闭连接)。
int Decrypt(const BYTE* cipher, int len, std::vector<BYTE>& plain);
// 加密:把明文 plain[0..len] 加密成完整 TLS 记录,追加到 wire。
// 返回加密的明文字节数(== len);-1 = 错误。
int Encrypt(const BYTE* plain, int len, std::vector<BYTE>& wire);
bool Ready() const { return m_ready; }
private:
void CloseHandles();
bool SendAll(SOCKET sock, const void* data, int len);
std::mutex m_mtx; // 序列化对 m_ctx 的 Encrypt/Decrypt(Schannel 非线程安全)
CtxtHandle m_ctx = {};
bool m_ctxValid = false;
bool m_ready = false;
SecPkgContext_StreamSizes m_sizes = {};
std::vector<BYTE> m_raw; // 尚未解密 / 未消费完的 TLS 记录原始字节
};
+76
View File
@@ -349,6 +349,75 @@ public:
void onHttp(HttpHandler handler) { m_httpHandler = handler; }
private:
// ---- Real client IP behind a reverse proxy ----
// A same-host nginx/Caddy connects from 127.0.0.1 and reports the original
// peer in X-Real-IP / X-Forwarded-For. Only trust those headers when the
// TCP peer is loopback: otherwise any internet client could forge its
// address in the audit log and rotate it to evade login throttling.
static std::string trimHttpValue(const std::string& s) {
size_t b = s.find_first_not_of(" \t");
if (b == std::string::npos) return "";
size_t e = s.find_last_not_of(" \t\r\n");
return s.substr(b, e - b + 1);
}
static std::string asciiLower(const std::string& s) {
std::string out = s;
for (char& c : out) {
if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a');
}
return out;
}
// Case-insensitive lookup of one header in the raw request. The request
// line is first, so matching "\r\n<name>:" cannot hit the request target.
static std::string httpHeader(const std::string& request, const char* name) {
const std::string needle = "\r\n" + asciiLower(name) + ":";
const std::string hay = asciiLower(request);
size_t pos = hay.find(needle);
if (pos == std::string::npos) return "";
size_t vstart = pos + needle.size();
size_t vend = hay.find("\r\n", vstart);
return trimHttpValue(request.substr(vstart,
vend == std::string::npos ? std::string::npos : vend - vstart));
}
// Accept only a bare IPv4/IPv6 literal; forwarded headers are attacker
// controlled even when the proxy is trusted, so no hostnames/ports.
static std::string normalizeIPLiteral(const std::string& value) {
std::string s = trimHttpValue(value);
if (s.empty() || s.size() > 63) return "";
struct in_addr v4;
if (inet_pton(AF_INET, s.c_str(), &v4) == 1) return s;
struct in6_addr v6;
if (inet_pton(AF_INET6, s.c_str(), &v6) == 1) return s;
return "";
}
static std::string forwardedClientIP(const std::string& request) {
// X-Forwarded-For is "client, proxy1, ..." with the oldest hop first.
// Our own proxy appends the peer it saw, so the last valid entry is
// the one it actually observed: a client-supplied list cannot forge
// it. Prefer this over X-Real-IP, which is only trustworthy when the
// proxy explicitly overwrites it (some configs pass it through).
std::string xff = httpHeader(request, "x-forwarded-for");
size_t end = xff.size();
while (end > 0) {
size_t comma = xff.rfind(',', end - 1);
size_t start = comma == std::string::npos ? 0 : comma + 1;
std::string ip = normalizeIPLiteral(xff.substr(start, end - start));
if (!ip.empty()) return ip;
if (comma == std::string::npos) break;
end = comma;
}
return normalizeIPLiteral(httpHeader(request, "x-real-ip"));
}
static bool isLoopbackPeer(const std::string& ip) {
return ip.rfind("127.", 0) == 0 || ip == "::1" ||
ip == "::ffff:127.0.0.1";
}
// Parse Proxy Protocol v2 header and extract real client IP
bool parseProxyProtocolV2(SOCKET sock, std::string& clientIP) {
// PP2 signature (12 bytes)
@@ -448,6 +517,13 @@ private:
if (request.find("\r\n\r\n") != std::string::npos) break;
}
// Behind a same-host reverse proxy the TCP peer is 127.0.0.1; recover
// the real client address the proxy recorded in the handshake.
if (isLoopbackPeer(clientIP)) {
std::string forwarded = forwardedClientIP(request);
if (!forwarded.empty()) clientIP = forwarded;
}
// Check if WebSocket upgrade
if (request.find("Upgrade: websocket") == std::string::npos) {
// Regular HTTP request - extract path
+28 -3
View File
@@ -232,6 +232,26 @@ void CSystemDlg::ShowWindowsList(void)
ApplySort(); // 应用记忆的排序偏好
}
// 按客户端编码 (936 或 UTF-8) 解码字节串,并用 LVM_SETITEMTEXTW 写入列表单元格,
// 绕开 ANSI→CP_ACP 回转(非中文 ACP 服务端上中文也能正常显示,与窗口管理同法)。
static void SetClientTextItem(CListCtrl& list, int iItem, int iSubItem, const char* sz, UINT cp)
{
std::wstring w;
if (sz && sz[0]) {
int wlen = MultiByteToWideChar(cp, 0, sz, -1, NULL, 0);
if (wlen > 1) {
w.resize(wlen - 1);
MultiByteToWideChar(cp, 0, sz, -1, &w[0], wlen);
}
}
LVITEMW lv = {};
lv.mask = LVIF_TEXT;
lv.iItem = iItem;
lv.iSubItem = iSubItem;
lv.pszText = w.empty() ? const_cast<LPWSTR>(L"") : &w[0];
::SendMessageW(list.GetSafeHwnd(), LVM_SETITEMTEXTW, (WPARAM)iItem, (LPARAM)&lv);
}
void CSystemDlg::ShowProcessList(void)
{
// GetMyBuffer(1) 深拷贝数据,跳过 TOKEN 字节
@@ -248,6 +268,10 @@ void CSystemDlg::ShowProcessList(void)
const char *szProcessFullPath;
DWORD dwOffset = 0;
CString str;
// 进程名/路径编码:Windows 客户端 A 接口生成,恒为 GBK/936;仅 LNX/MAC 为 UTF-8。
// 不能用 GetClientEncoding(它对新客户端返回 CP_UTF8,会把 GBK 进程名解成乱码)。
UINT cp = GetProcessListEncoding(m_ContextObject);
DeleteAllItems();
//遍历发送来的每一个字符别忘了他的数据结构啊 Id+进程名+0+完整名+0
int i;
@@ -258,10 +282,11 @@ void CSystemDlg::ShowProcessList(void)
szProcessFullPath = szExeFile + lstrlen(szExeFile) + 1; //完整名就是进程名之后的啦
//他的数据结构的构建很巧妙
m_ControlList.InsertItem(i, arr[0].c_str()); //将得到的数据加入到列表当中
m_ControlList.InsertItem(i, ""); // 占位,首列随后用 Unicode 写入
str.FormatL("%5u", *PID);
m_ControlList.SetItemText(i, 1, str);
m_ControlList.SetItemText(i, 2, szProcessFullPath);
m_ControlList.SetItemText(i, 1, str); // PID (ASCII)
SetClientTextItem(m_ControlList, i, 0, arr[0].c_str(), cp); // 进程名(按客户端编码)
SetClientTextItem(m_ControlList, i, 2, szProcessFullPath, cp); // 程序路径(按客户端编码)
m_ControlList.SetItemText(i, 3, arr[1].empty() ? "N/A" : arr[1].c_str());
// ItemData 为进程ID;Data[3] 需与第 4 列"架构"一致,否则按架构排序拿到空串而无意义
auto data = new ItemData{ *PID, {arr[0].c_str(), str, szProcessFullPath, arr[1].empty() ? "N/A" : arr[1].c_str()}, arr[1].c_str() };
+234
View File
@@ -0,0 +1,234 @@
#include "stdafx.h"
#include "TlsCertificateDlg.h"
#include "LangManager.h" // _TR / MessageBoxL
#include "2015Remote.h" // THIS_CFG (GetThisCfg)
#include "ServerTlsSession.h" // ServerTlsIdentity::Load / IsLoadError
#include "common/iniFile.h" // config::GetInt/GetStr/SetInt/SetStr
#include <atlconv.h>
#include <afxdlgs.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
namespace {
// 构造一个无控件的 DLGTEMPLATE:cdit=0,控件由 OnInitDialog 动态创建。
// (与 McpSettingsDlg.cpp / ZstaPickerDlg.cpp 内同名函数一致)
void BuildDialogTemplate(std::vector<BYTE>& out, LPCWSTR caption, short cx, short cy)
{
out.clear();
auto append = [&](const void* p, size_t n) {
const BYTE* b = (const BYTE*)p;
out.insert(out.end(), b, b + n);
};
auto appendW = [&](WORD v) {
out.push_back((BYTE)(v & 0xFF));
out.push_back((BYTE)((v >> 8) & 0xFF));
};
auto appendWStr = [&](LPCWSTR s) {
size_t n = wcslen(s);
append(s, (n + 1) * sizeof(WCHAR));
};
DLGTEMPLATE dt = { 0 };
dt.style = DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER |
WS_POPUP | WS_CAPTION | WS_SYSMENU;
dt.dwExtendedStyle = 0;
dt.cdit = 0;
dt.x = 0; dt.y = 0;
dt.cx = cx; dt.cy = cy;
append(&dt, sizeof(dt));
appendW(0); // no menu
appendW(0); // default dialog class
appendWStr(caption); // caption
appendW(8); // font point size
appendWStr(L"MS Shell Dlg"); // typeface
while (out.size() % 4) out.push_back(0); // DWORD align
}
} // namespace
BEGIN_MESSAGE_MAP(CTlsCertificateDlg, CDialog)
ON_BN_CLICKED(IDC_TLS_CERT_BROWSE, &CTlsCertificateDlg::OnBrowseCert)
ON_BN_CLICKED(IDC_TLS_KEY_BROWSE, &CTlsCertificateDlg::OnBrowseKey)
END_MESSAGE_MAP()
CTlsCertificateDlg::CTlsCertificateDlg(CWnd* parent)
: CDialog((LPCTSTR)NULL, parent)
{
}
INT_PTR CTlsCertificateDlg::DoModal()
{
USES_CONVERSION;
CString title = _TR("TLS证书");
BuildDialogTemplate(m_Template, T2CW(title), 340, 180);
InitModalIndirect((LPCDLGTEMPLATE)m_Template.data());
return CDialog::DoModal();
}
BOOL CTlsCertificateDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CRect cli;
GetClientRect(&cli);
// 占位 rect,真正布局在 LayoutControls 里
CRect r0(0, 0, 10, 10);
m_btnEnable.Create(_TR("启用加密"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_TLS_ENABLE);
m_lblCert.Create(_TR("证书路径"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editCert.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
r0, this, IDC_TLS_CERT);
m_btnCertBrowse.Create(_TR("浏览"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
r0, this, IDC_TLS_CERT_BROWSE);
m_lblKey.Create(_TR("私钥路径"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editKey.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
r0, this, IDC_TLS_KEY);
m_btnKeyBrowse.Create(_TR("浏览"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
r0, this, IDC_TLS_KEY_BROWSE);
m_btnOK.Create(_TR("确定"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_DEFPUSHBUTTON,
r0, this, IDOK);
m_btnCancel.Create(_TR("取消"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
r0, this, IDCANCEL);
// 子控件继承对话框字体 (DS_SETFONT)
HFONT hFont = (HFONT)::SendMessage(GetSafeHwnd(), WM_GETFONT, 0, 0);
if (hFont) {
m_btnEnable.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_lblCert.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_editCert.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnCertBrowse.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_lblKey.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_editKey.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnKeyBrowse.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnOK.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnCancel.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
}
// 回填配置
int enabled = THIS_CFG.GetInt("tls", "Enabled", 0);
std::string cert = THIS_CFG.GetStr("tls", "CertPath", "");
std::string key = THIS_CFG.GetStr("tls", "KeyPath", "");
m_btnEnable.SetCheck(enabled ? BST_CHECKED : BST_UNCHECKED);
m_editCert.SetWindowText(CString(cert.c_str()));
m_editKey.SetWindowText(CString(key.c_str()));
LayoutControls(cli.Width(), cli.Height());
return TRUE;
}
void CTlsCertificateDlg::OnOK()
{
CString sCert, sKey;
m_editCert.GetWindowText(sCert);
m_editKey.GetWindowText(sKey);
bool enabled = (m_btnEnable.GetCheck() == BST_CHECKED);
std::string cert = CT2A(sCert);
std::string key = CT2A(sKey);
// 校验:启用加密时必须填写证书/私钥路径
if (enabled && cert.empty()) {
MessageBoxL("请填写证书路径", "提示", MB_ICONWARNING);
return;
}
if (enabled && key.empty()) {
MessageBoxL("请填写私钥路径", "提示", MB_ICONWARNING);
return;
}
// 落盘 [tls] 三键
THIS_CFG.SetInt("tls", "Enabled", enabled ? 1 : 0);
THIS_CFG.SetStr("tls", "CertPath", cert);
THIS_CFG.SetStr("tls", "KeyPath", key);
// 热重载身份(设计文档 §7.1):开关与证书/私钥路径对新建连接即时生效。
// 已知窄竞态:Load 内部 FreeIdentity 与「已取 Cred 副本、尚在握手」的连接存在竞态,
// 未来热切换需引用计数 + 惰性释放(见 ServerTlsSession.cpp FreeIdentity 注释),本次不做。
ServerTlsIdentity::Load(THIS_CFG);
if (ServerTlsIdentity::IsLoadError()) {
MessageBoxL("证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。",
"提示", MB_ICONWARNING);
} else {
MessageBox(_TR("TLS 配置已保存。") + _T("\r\n") +
_TR("改动对新建连接即时生效。"),
_TR("提示"), MB_ICONINFORMATION);
}
CDialog::OnOK();
}
void CTlsCertificateDlg::OnBrowseCert()
{
CFileDialog dlg(TRUE, _T("crt"), nullptr,
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
_T("Certificate Files (*.crt;*.pem;*.cer;*.cert)|*.crt;*.pem;*.cer;*.cert|All Files (*.*)|*.*||"),
this);
dlg.m_ofn.lpstrTitle = _T("Select Certificate");
if (dlg.DoModal() == IDOK) {
m_editCert.SetWindowText(dlg.GetPathName());
}
}
void CTlsCertificateDlg::OnBrowseKey()
{
CFileDialog dlg(TRUE, _T("key"), nullptr,
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
_T("Key Files (*.key;*.pem)|*.key;*.pem|All Files (*.*)|*.*||"),
this);
dlg.m_ofn.lpstrTitle = _T("Select Private Key");
if (dlg.DoModal() == IDOK) {
m_editKey.SetWindowText(dlg.GetPathName());
}
}
void CTlsCertificateDlg::LayoutControls(int cx, int cy)
{
const int margin = 14;
const int labelW = 72;
const int rowH = 24;
const int gap = 10;
const int browseW = 64;
const int btnW = 88;
const int btnH = 26;
int y = margin;
m_btnEnable.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
int editW = cx - margin * 2 - labelW - browseW - gap;
m_lblCert.MoveWindow(margin, y, labelW, rowH);
m_editCert.MoveWindow(margin + labelW, y - 2, editW, rowH);
m_btnCertBrowse.MoveWindow(cx - margin - browseW, y - 2, browseW, rowH);
y += rowH + gap;
m_lblKey.MoveWindow(margin, y, labelW, rowH);
m_editKey.MoveWindow(margin + labelW, y - 2, editW, rowH);
m_btnKeyBrowse.MoveWindow(cx - margin - browseW, y - 2, browseW, rowH);
y += rowH + gap;
// 确定 / 取消按钮紧随私钥路径下方
m_btnCancel.MoveWindow(cx - margin - btnW, y, btnW, btnH);
m_btnOK.MoveWindow(cx - margin - btnW * 2 - gap, y, btnW, btnH);
y += btnH + margin;
// 收缩对话框到内容实际高度并重新居中,消除底部空白。
if (y < cy) {
CRect wnd;
GetWindowRect(&wnd);
SetWindowPos(NULL, 0, 0, wnd.Width(), y + (wnd.Height() - cy),
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
CenterWindow();
}
}
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff. Show more