cc9ce35c4d37193dd5c2cebee5e1d3a93ef4de65
13
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
c4021e1fc9 |
Feature: Ship a built-in TLS certificate so encryption works out of the box
A fresh install used to require openssl before the server could speak TLS: two empty paths in [tls] meant the identity failed to load and every ClientHello was refused. TLS is now on by default and, when no custom certificate is configured, the server generates its own self-signed one the first time it needs it -- RSA-2048, SHA-256, CN=yama-server, CA:TRUE, valid for ten years from one day before now. Plaintext clients are untouched, since the device port still splits plaintext from TLS by sniffing the first six bytes of a connection. The certificate and its PKCS#8 private key are stored side by side in the config under [tls] BuiltinCert / BuiltinKey as single-line base64 DER. Single line, because the server has two config backends -- the registry for Release, settings.ini for a Debug master -- and only a line without newlines means the same read/write code serves both. That in turn required fixing the registry reader: iniFile::GetStr copied into a 512 byte stack buffer, so a 1.5 KB value came back as a truncated or empty string. The two-phase dynamic read now lives in common/iniFile.h as ReadRegistryValueSz / ReadRegistrySz, and the copy that client/TlsChannel.cpp had been carrying for its own trust anchor is gone. This also makes the built-in certificate self-checking: Ensure() re-reads what it just wrote and fails loudly if the round trip did not survive. Import has to go through NCRYPT_PKCS8_PRIVATE_KEY_BLOB, matching the import path in BuildIdentityFromDer. NCRYPT_PKCS8_PRIV_KEY_INFO_BLOB, which most samples reach for, is not implemented by the Microsoft Software KSP and returns NTE_INVALID_PARAMETER; a probe confirmed it, and the export type that works is the one the importer already expected. Building an identity is now split into a file front-end (PEM, fullchain, PKCS#1 hints) and a shared DER core, so the built-in and file paths cannot drift apart. That key also exposed a second problem worth fixing here. The identity binds its private key to the certificate by name -- CRYPT_KEY_PROV_INFO with pwszContainerName -- and Schannel resolves that name on every handshake through CryptAcquireCertificatePrivateKey. With the fixed name "YamaServerTlsKey", two server processes under the same Windows user shared one key slot: whichever loaded last overwrote it, and the other process's next handshake picked up a private key that does not match its certificate. That is exactly the debug-plus-release pairing used here, and defaulting to a built-in certificate is what makes it reachable, since the debug instance no longer points at the same PEM as the release instance. The name is now the base name plus the first six bytes of the certificate's SHA-1 thumbprint, e.g. YamaServerTlsKey-c0d469eae8a4: different certificates get different keys, instances sharing one certificate still share one key. MCP picks this up too. The effective name goes to the trace log so a collision is visible without a debugger. A stale key from an older build may still sit in the key store under the old name; nothing references it and it is not deleted automatically, since a running instance of an older build could be using it. The trust anchor still has to be pushed. The client pins exactly one root through an exclusive-root chain engine and checks no host name, so a self-signed CA:TRUE leaf chains cleanly to itself -- but only if the client is told about it. That is the existing 启用 TLS / 切换到 WSS command, which now takes the PEM from ServerTlsIdentity::AnchorPem instead of re-reading the configured cert file, so it reports the same certificate the server actually serves for both sources. Losing the stored certificate (cleared registry, new Windows user) regenerates it, and every client must be re-pushed the anchor. Two places that used to fall back to [tls] CertPath now skip that fallback while the built-in certificate is active: the MCP HTTPS front end at startup and the prefill in its settings dialog. A self-signed certificate cannot pass validation at a public MCP client, and the retained CertPath is only a leftover from switching back to a custom certificate, so pretending to use it would fail later with a worse message. MCP HTTPS with empty paths already fails closed with a log line. The TLS dialog gains a 内置证书 checkbox, ticked by default and unticked when certificate paths are present; ticking it greys out the path rows without clearing them, and shows either "generated on first use" or the expiry date read back from the stored certificate. Saving writes four keys -- Enabled, UseBuiltIn, CertPath, KeyPath -- and an explicit UseBuiltIn keeps the paths from being used as an implicit switch. Every reader of [tls] Enabled now defaults to 1, so the menu check, the dialog and the loader agree on a fresh install. The status bar panes on 无 / 有 grew a third state, 内置, and the pane width is measured across all three. Translations were added to en_US, zh_TW and de_DE; skipping the German file would have left the new dialog text in Chinese there, as de_DE is loaded from disk rather than embedded. Verified with the debug server against openssl s_client. Both the generated built-in certificate (CN=yama-server) and an existing custom one (CN=localhost) complete a TLS 1.2 handshake with the pinned certificate, and their log lines show distinct key names, c0d469eae8a4 and 272f2adfb19c. An unmodified client still runs in plaintext without an anchor, an existing custom certificate deployment behaves exactly as before, and client and server both build clean at Debug x64. Co-Authored-By: deepseek-flash |
||
|
|
27b5431130 |
Feature: Add the file-write tools behind their own switch
P10-B adds delete_path, move_path and create_folder, and the switch they need. Reusing McpFileTransfer would have been wrong: uploading overwrites a file, deleting destroys a tree, and an operator who wants one may well not want the other. McpFileWrite is therefore a separate key, off by default, wired the way every other switch is - read from settings.ini at startup, reported as get_server_status.switches.file_write, and exposed with its own checkbox in the MCP settings dialog. The tools additionally require readonly to be off: a read-only server has no business modifying a host. No client change was needed: COMMAND_DELETE_FILE, COMMAND_DELETE_DIRECTORY, COMMAND_CREATE_FOLDER and COMMAND_RENAME_FILE already existed in the Windows file manager. The chain reuses the file-manager sub-connection and adds a phase - the main connection asks for the drive list, the sub-connection's first packet hands it to OnDriveList which sends the write command, and the client's TOKEN_*_FINISH ack moves the pending request from phase 0 to 1, where the tool sends COMMAND_LIST_FILES for the parent so the ack and the confirmation share one timeout. Only the IO thread touches the sub-connection; the tool thread just waits on the shared condvar, which keeps the sub-connection's lifetime out of its reach. The confirmation exists because the client answers unconditionally: it ignores the return values of DeleteFile, MoveFile and MakeSureDirectoryPathExists and there is no error token. ok therefore only means "the command arrived", and verified is the real answer - true when the parent listing shows the expected post-state, false when it shows the opposite, null when the listing itself did not come back (timeout or disconnect), since reporting that as false would be a lie. Linux, macOS and Android hosts are refused outright: those clients decode these paths as GBK while the server speaks UTF-8 to them for list_files, so a non-ASCII path would corrupt rather than fail. Paths are validated as UTF-8, converted to GBK exactly once, and reject %VAR%, relative paths, drive and share roots, and - for delete_path and for move_path's source - the Windows, Program Files, ProgramData, $Recycle.Bin and System Volume Information trees. create_folder gets no system-directory ban, because writing there is the same permission upload_file already has. Two defects surfaced while exercising this against a real client: create_folder's wire path has to end with a backslash, because MakeSureDirectoryPathExists treats a non-terminated last component as a file name and only creates the intermediate levels; and ResolveFileOpVerified(LookupInListing(...), isDir, ...) read isDir before the lookup ever set it - argument evaluation order is unspecified and MSVC evaluates right to left - so every create_folder reported verified=false even when the directory existed. Verified on a Debug x64 build against a Windows client over MCP: nested create_folder, upload, rename, delete, delete a tree, the failure shapes (delete with recursive=false on a directory, create_folder onto an existing file name, delete of a non-existent target) and every refusal (drive root, C:\Windows\Temp, C:\Users, %TEMP%, relative, empty, over-long, from==to, offline host, non-numeric id), with a Chinese-named directory created, renamed and deleted end to end; no file-manager window appeared in the server process during any of it. The smoke test gained section [4c], opt-in through -FileWriteDir, which asserts verified and never ok and walks a sandbox through the same path; two runs passed 69 checks with the sandbox removed afterwards. Bin/settings.ini was restored byte-exact and the Release instance was left alone. Co-Authored-By: deepseek-flash |
||
|
|
a7dd86ff0f |
Feature: Terminate TLS for the MCP endpoint inside YAMA
MCP was served by a plain httplib::Server, so remote clients could only use cleartext HTTP. YAMA now terminates TLS itself: a small front-end owns the MCP port, sniffs the first byte and either runs a Schannel handshake and forwards the decrypted bytes or passes plaintext through, with httplib moving to a loopback-only internal port. No OpenSSL, no frp change, existing local HTTP clients keep working, and an unusable certificate fails closed instead of falling back to cleartext. The identity loader grew the two things a public certificate needs. ECDSA (P-256/P-384/P-521) keys are persisted by importing PKCS#8 with an NCRYPTBUFFER_PKCS_KEY_NAME parameter, the only route MS Software KSP supports for Schannel; RSA keeps its old export-and-repersist path. Fullchains are accepted, and the intermediates are added to the current user's CA store so Schannel, which builds chains only from system stores, actually sends them. The shared handshake also now buffers a full TLS record before the first AcceptSecurityContext, which a partial ClientHello would otherwise poison (SEC_E_UNKNOWN_CREDENTIALS). Session resumption exposed a second trap: when a client resumes a session, ChangeCipherSpec, Finished and the first application record arrive in one segment and AcceptSecurityContext leaves the application record pending in the session. Nothing drained it, because both callers only decrypt when new ciphertext arrives, so the request waited until the peer gave up (the MCP front-end saw no request at all and the client reported "fetch failed (other side closed)"; the device port had the same hole behind its occasional login timeouts). Decrypt now drains pending data on len == 0, and both the front-end and the device port's handshake thread use it before entering their receive loops. Configuration is McpHttps, McpCertPath, McpKeyPath and McpInternalPort, the first three editable in the MCP settings dialog (the certificate rows stay greyed out until HTTPS is enabled and saving rejects missing files). Verified with a real Let's Encrypt ECDSA fullchain (53 tools over TLS, 401 with no or bad token), a local three-level chain whose intermediate was absent from the store, Node 24's fetch on a resumed session (initialize, notifications/initialized and tools/list all complete), and the device port's RSA handshake as a regression check. Details in docs/Mcp_Design.md section 13. Co-Authored-By: deepseek-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 |
||
|
|
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 |
||
|
|
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 |
||
|
|
9eed43bc8d |
Feature: Add MCP device management-control tools (kill/window/service/power)
Add P7 management-control tools behind a single McpManage flag (plus
McpReadonly=0): kill_process, operate_window, control_service and
power_action. The write tools run a ready->confirm lifecycle on their
sub-connection, using a new followUp/followUpSent field to tell the two
arrivals of the same TOKEN_*LIST apart; the write command and the follow-up
refresh command go out as two separate Send2Client calls, with a new
WaitSendIdle() (context.h / Server.h) draining the outbound buffer in between
so the same buffer is never WSASend'd concurrently.
McpSettingsDlg gains a "management operations" checkbox (IDC_MCP_MANAGE), the
main toolbar gains an MCP entry button, and en/de/zh-TW strings are synced.
power_action is fire-and-forget over the main connection (no confirmation).
Verified end-to-end against a real Windows 10/VMware client: kill_process
returns remaining:[] and operate_window/control_service return ok:true with
their confirm packet arriving after an HTTP split. Verification surfaced a
prerequisite parser bug, fixed separately in
|
||
|
|
b41b27bfe4 | Release v1.3.9 | ||
|
|
5c77f5ce14 |
Feature: Add download_file MCP tool (V2 protocol, SHA-256 verified)
download_file pulls a remote file or directory back to the controller over the existing V2 file-transfer protocol. It reuses COMMAND_LIST_DRIVE to open the file-manager sub-link, then sends CMD_DOWN_FILES_V2 so the Windows client streams COMMAND_SEND_FILE_V2 chunks and a per-file COMMAND_FILE_COMPLETE_V2 SHA-256 checksum over its own authenticated sub-connection. The server routes those two packet types into a new per-device FileTransferSession whenever a download is pending, so the headless path never opens the GUI progress dialog; the C2C and existing GUI branches are left untouched. Files are written under a normalized local_dir, and every chunk filename is resolved and verified to stay inside local_dir (directories included) to block .. traversal; overwrite=false skips existing files and counts them as skipped. One transfer per host (mutually exclusive with the one-shot pending registry), a dedicated McpFileTransfer=0-by-default gate surfaced in the settings dialog, and audit logging complete the change. upload_file remains future work. Co-Authored-By: deepseek-v4-pro |
||
|
|
6045baadb8 |
Feature: Add MCP remote_open/remote_close remote control sessions
Add M1 of MCP remote control (docs/Mcp_RemoteControl_Design.md): the
remote_open / remote_close tools plus the ScreenCtrlSession state machine.
remote_open establishes a hidden screen sub-connection by reusing
WebService::StartRemoteDesktop (COMMAND_SCREEN_SPY -> CScreenSpyDlg ->
RegisterScreenContext), polls for the sub-connection plus its physical
resolution (TOKEN_BITMAPINFO -> NotifyResolutionChange -> GetScreenSize),
then records the session (single device, single session, reverse-mapped
subCtx for OfflineProc cleanup) and returns {session_id, screen_w,
screen_h}. remote_close validates session_id and tears down the
sub-connection idempotently. A McpRemoteControl settings checkbox (default
off, requires McpReadonly=0) gates the tools; every open/close is audited
via WM_SHOWERRORMSG.
Gating: multi-monitor hosts are rejected with -32008 (phase 1 supports only
single monitor, where Observe=main screen and Act=virtual desktop coincide);
the monitor count comes from the client heartbeat RES_RESOLUTION ("N:W*H").
Known limitations (deferred to the injection milestones): mutual exclusion
with human remote-desktop viewing is one-directional in M1 (a human who
joins during an MCP session can tear it down on disconnect), and subCtx is
not yet dereferenced so no liveness re-check is needed until
remote_mouse/remote_keyboard.
Co-Authored-By: deepseek-v4-pro
|
||
|
|
70dbb6b255 |
Feature: Add persistent remote terminal MCP tools
Add terminal_open / terminal_exec / terminal_close so an AI can hold one shell session per Windows host and run a sequence of commands with cwd and environment preserved, instead of the one-shot exec_command. The persistent terminal is a separate full-command write capability gated by McpTerminal (default off) plus McpReadonly=0, with no whitelist and full audit. One device maps to one terminal session via the shared m_TermSessions map; idle sessions are swept after 300s. terminal_exec rejects commands that contain & or | (they corrupt the sentinel control-operator chain) as well as control characters. Also harden exec_command and terminal_exec against newline/CR injection, fix a dangling subCtx after an abrupt shell disconnect, and refresh lastActiveAt on command completion. Add en/zh-TW translations for the new UI strings and a design document covering both exec_command and the persistent terminal. Co-Authored-By: deepseek-v4-pro |
||
|
|
0ddbc1aced |
Feature: Add exec_command MCP tool
Add a one-shot exec_command MCP tool that runs a command on a remote Windows host and returns stdout plus exit code, reusing the Web terminal link (main-connection COMMAND_SHELL, a shell sub-connection, and a sentinel command line located via rfind to tolerate ConPTY echo). The sentinel marker is embedded in the command line ConPTY echoes back, so it is only treated as hit when it starts a line (preceded by a newline or the buffer start); this keeps the echoed marker from being mistaken for the real sentinel when the echo packet arrives before the output. Execution is gated at Web remote-desktop sensitivity: a read-only mode (McpReadonly, default on, hides the tool) and a command whitelist (McpCmdWhitelist) with built-in read-only prefixes. Shell metacharacters (& | < > ^) are rejected before whitelist matching, and each execution is recorded in the server audit log. Extend the MCP settings dialog with the read-only checkbox and a multi-line whitelist box (commas and newlines both accepted, normalized to a comma-separated list on save), and add English and Traditional Chinese mappings for the new UI and audit-log strings. Co-Authored-By: deepseek-v4-pro |
||
|
|
13052b7cae |
Feature: Add MCP (Model Context Protocol) server integration
Add an optional MCP server (JSON-RPC 2.0 over Streamable HTTP) exposing an online-host listing tool, protected by a Bearer token. Disabled by default; configured via a new "Extensions > MCP Settings" dialog. - McpServer: httplib + JSON-RPC 2.0 dispatch (initialize/ping/tools/list/tools/call) - McpSettingsDlg: runtime-created dialog for enable/port/bind/token - HostJson: extract single-host JSON serialization shared with WebService - FRP: expose MCP port (union with listening/Web ports) when bound to 0.0.0.0 - i18n: en_US / zh_TW translations Co-Authored-By: deepseek-v4-pro |