b704258ba48eab5def4e5c3ee1962854f9037503
6
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
951b4072e5 |
Feature: Embed the master's TLS certificate in generated clients
When the server has TLS enabled, the builder can now bake its certificate into the client it produces, so a distributed client speaks TLS on its very first connection instead of waiting for the anchor to be pushed after a plaintext login. The dialog gets a checkbox (IDC_CHECK_TLS_ANCHOR) that is only enabled for payloads and protocols where an embedded anchor makes sense; the choice is remembered even when the control flips to disabled and back, so switching protocols cannot silently undo a deliberate opt-out. Every label variant stays short enough to fit the 196 DLU field, including the German ones. A template that predates the anchor block no longer aborts generation: it warns, clears the checkbox and produces a plain client, so a master upgraded without rebuilding the ghost/ServerDll resources does not block every build. The certificate lands in a fixed 4 KiB block (magic, version, length, FNV-1a hash, master address, PEM) carved out of the payload at build time. The client reads its trust anchor from four sources in order: the tls_disabled marker, the certificate the server pushed into the registry, a PEM file next to the executable, and finally the embedded block. The embedded block only applies to a connection whose target matches the master recorded at generation time, compared as an address set: an exact string match when only one address is configured, or an intersection of resolved IPv4 addresses otherwise. A transferred, shared or parallel instance falls back to the old plaintext first-connect path instead of pinning itself to a certificate it can never verify. That decision is made per connection, not per process: shared and parallel instances are threads inside a single client process, so a process-wide flag let whichever instance connected first decide for all of them, and the first load of the TLS state cached that answer for good. The TLS layer now keeps two cached states (embedded anchor allowed, and not allowed), picks one per handshake, and reports the anchor source of that handshake for the login capability bit. Matching by resolved address also keeps parallel mode working, where the connection goes to the single IP the domain pool selected while the configured master is a domain or a list. Server side, generated and updated payloads get the block written in place; the client reports the capability bit on login so the console can tell which hosts are already TLS-only on first connect. Loading the anchor decodes every PEM block in the chain rather than just the leaf, and an anchor that exists but fails to load keeps the old fail-closed behaviour. A pushed anchor only reconnects when the transport of the live connection actually changes, judged against that connection's own target rather than the process-wide switch. This was verified end to end against a freshly generated client with an empty registry: the first connection was a TLS 1.2 ClientHello 0.2 s after start, and a four-certificate fullchain loaded all four blocks. Re-verified after the per-connection rework with the anchor block patched into a debug client: with a matching master the first bytes are a ClientHello, with a foreign master the client logs the skip and sends plaintext, and a domain master resolves to the IP it connects to and still matches. A master domain that no longer resolves falls back to plaintext within a second and is not looked up again for a minute, instead of stalling every reconnect on a DNS timeout while holding the lock the certificate verification needs. Co-Authored-By: deepseek-flash |
||
|
|
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 |
||
|
|
46f4bf2dfb |
Fix: Make the WebSocket transport reachable and bounded on every platform
The POSIX clients were built without a connection config - Linux, macOS and Android all construct IOCPClient without the injected CONNECT_ADDRESS - so ConnectServer saw protoType -1 and quietly dialled the master port in plain TCP. Setting protoType to WS in their settings did nothing and logged nothing, and since CLIENT_CAP_PROTO_SWITCH is Windows-only the server could not move them either. Give the client a SetDefaultProto() for that construction path and call it from all three mains before the reconnect loop, with a one-shot log when neither a conn nor a default protocol is available so the silent fallback becomes visible next time. Bound what a peer can make the client read. ReadHeader accepted the 8-byte extended length and rejected only the sign bit, so a frame length of nearly 2^63 kept the connection streaming into a frame that would never end - alive but never delivering another packet. Cap single frames at 256 MB, the same value ServerWsSession already applies to client frames, and drop the connection past it; real traffic is far below that. Stop Reset() from writing the receive thread's frame state. Disconnect() can run from the heartbeat or command thread, not just the receive thread, so Reset() now only flips the atomic ready flag and a new ResetFrames() clears m_remaining, m_masked and m_maskPos from Handshake() alone, before the receive thread starts reading the socket. Those fields keep a single owner without adding a lock to the receive hot path. Finish a dead WS session instead of leaving it to the keepalive timer. When the session had closed but wsState was still WS_Ready, sends were dropped and nothing woke the pending recv, so a peer that closed and then went quiet held the context for the 3-minute keepalive. shutdown() the socket there so the recv returns zero bytes and the normal -2 teardown runs; RemoveStaleContext would deadlock against the caller's own IoRefCount and can hand back a reused context. That shutdown only finishes the connection if a zero-byte read still tears it down, and on the plain path it no longer did. DispatchPlain answers an empty buffer with "handled", so a peer's FIN left the connection in CLOSE_WAIT until keepalive - holding an IOCP context, a pending WSARecv and a rate-limit slot - where the pre-WS code called ParseReceivedData and tore down at once. Restore that teardown on the TLS_Plain branch, matching the other two. Checked against a Debug server: a plain socket that half-closes used to sit in CLOSE_WAIT with the peer's recv timing out, and now disappears immediately with recv returning zero. Two smaller cleanups from the same review. Give the WS upgrade its own prefix buffer (wsPreClassify) instead of borrowing the TLS sniffer's, which was serially reused for two state machines and read as if it were one. And stop deriving the build dialog's protoType from the combo box index: items now carry the protocol value as item data, keyed off the index AddString returns, so inserting an option in the middle can no longer write the wrong number into the generated client without any error. ApplyProtoSwitch loses its bool return, which contradicted its own side effects and was ignored by every caller. Co-Authored-By: deepseek-flash |
||
|
|
d4f312c9d8 | Feature: Tunnel the device protocol through a reverse proxy over WebSocket | ||
|
|
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 |
||
|
|
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 |