Linux + iPhone Continuity / iMessage / SMS
device pairing mtls
Zack Bartel1e1ca3030a1d
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 20e0da2..ba220cf 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -6,6 +6,7 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)find_package(PkgConfig REQUIRED)pkg_check_modules(WAYLAND REQUIRED IMPORTED_TARGET wayland-client)+find_package(OpenSSL REQUIRED)include(FetchContent)diff --git a/README.md b/README.mdindex 3c6e6cf..53c78fb 100644--- a/README.md+++ b/README.md@@ -8,15 +8,16 @@ If you have migrated away from macOS but still carry an iPhone, Tether provides* **Clipboard Sync:** Seamlessly shares your Wayland compositor (`wlr-data-control`) clipboard over the Tether network so copied text propagates instantly to the iPhone app, and vice-versa.* **File Transfer:** Drag and drop files from Linux directly into the iPhone app natively, or Vice Versa using Base64 JSON chunking automatically deposited to your `$XDG_DOWNLOAD_DIR`.+* **Device Pairing:** Securely pair devices using **Mutually Authenticated TLS (mTLS)**, restricting TCP traffic securely employing X.509 RSA Certificates dynamically.* **TOTP/OTP Vault (WIP):** Encrypted TOTP secret management synced across your daemon and phone, with Safari autofill via `ASCredentialProviderExtension` on iOS, and Wayland browser autofill via a WebExtension.## ArchitectureTether operates using a tri-component architecture:-1. **`tetherd` (The Linux Daemon):** A background C++ process built cleanly on top of `epoll` and Wayland protocols via `hyprwayland-scanner`. It anchors the Linux clipboard and broadcasts events over UNIX Domain Sockets (`$XDG_RUNTIME_DIR/tether/tetherd.sock`) and local TCP.-2. **`tether` (The CLI):** A lightweight C++ cli program to communicate locally with the daemon.-3. **iPhone App (WIP):** A native SwiftUI iOS 16+ app discovering the daemon via Bonjour/mDNS.+1. **`tetherd` (The Linux Daemon):** A background C++ process built on top of `epoll` and Wayland protocols via `hyprwayland-scanner`. It anchors the Linux clipboard and broadcasts events over UNIX Domain Sockets (`$XDG_RUNTIME_DIR/tether/tetherd.sock`). Network traffic securely traverses local TCP via OpenSSL.+2. **`tether` (The CLI):** A lightweight C++ cli program to communicate natively with the daemon. Also features built-in TLS wrapping for testing the network stack via `--host`.+3. **iPhone App (WIP):** A native SwiftUI iOS 16+ app discovering the daemon via Bonjour/mDNS, utilizing Apple's `Network.framework` to securely negotiate TLS.4. **Browser Extension (WIP):** A WebExtension that interfaces with the daemon via native messaging.## Building `tetherd`@@ -25,6 +26,7 @@ Tether uses standard modern CMake (C++20).**Dependencies:**- `wayland-client`+- `openssl`- `pkg_config`- `ninja`diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.mdindex 22bec63..85ac463 100644--- a/docs/PROTOCOL.md+++ b/docs/PROTOCOL.md@@ -100,3 +100,34 @@ Tether supports streaming large binary files seamlessly through JSON using Base6"status": "success"}```++---++## 3. Device Pairing (mTLS)++Because the `tetherd` daemon natively binds to `0.0.0.0:5134` over TCP, it explicitly employs OpenSSL **Mutually Authenticated TLS (mTLS)** to natively reject malicious local-network payloads.++### `pair_request` (Untrusted Client -> Daemon)++**Description**: Emitted natively by a new client over standard TLS to gracefully present its identity and X.509 fingerprint. The Daemon immediately intercepts the payload, extracts the fingerprint natively from the `SSL*` pipe, and flags it locally as "Pending Authentication". Anything other than `pair_request` results in the TLS socket securely disconnecting.++**Payload**:+```json+{+ "command": "pair_request",+ "device_name": "My iPhone"+}+```++### `pair_pending` (Daemon -> Untrusted Client)++**Description**: Emitted immediately by the Daemon natively over the pending TLS pipe confirming the Request is actively intercepting user approval on local stdout.++**Payload**:+```json+{+ "command": "pair_pending"+}+```++Once explicitly paired (via `tether --accept <fingerprint>`), native mTLS fingerprint-matching activates permanently, unblocking future payload operations instantly!diff --git a/src/cli/main.cpp b/src/cli/main.cppindex 87be7c2..2123889 100644--- a/src/cli/main.cpp+++ b/src/cli/main.cpp@@ -7,8 +7,10 @@#include <sys/socket.h>#include <sys/un.h>#include <sys/wait.h>+#include <arpa/inet.h>#include <tether/base64.hpp>-#include <tether/net.hpp> // for get_runtime_dir+#include <tether/net.hpp>+#include <tether/crypto.hpp>#include <unistd.h>#include <vector>@@ -18,12 +20,17 @@ void print_help() {<< " -h, --help Show this help message.\n"<< " -g, --get-clipboard Retrieve the current Wayland clipboard text.\n"<< " -s, --set-clipboard Take string input and copy it to the local Wayland clipboard.\n"- << " If no argument is given, it reads from STDIN.\n"- << " -f, --send-file Send a file securely to the local Wayland download directory.\n\n"+ << " -f, --send-file Send a file securely to the local Wayland download directory.\n"+ << " --host <ip> Connect over TCP to daemon ip instead of UNIX Socket.\n"+ << " --port <num> Connect over TCP port (default 5134).\n"+ << " --list-devices List all paired connection devices.\n"+ << " --accept <fingerprint> Accept a pending pairing request locally.\n"+ << " --pair Send a pair_request over TCP to the daemon.\n\n"<< "Examples:\n"<< " tether -g\n"- << " tether -s \"Hello world\"\n"- << " echo \"pipe me\" | tether -s\n";+ << " tether -g --host 127.0.0.1\n"+ << " echo \"pipe\" | tether -s\n"+ << " tether --accept 9a4f21...\n";}int connect_to_daemon(bool retry = true) {@@ -75,13 +82,27 @@ int connect_to_daemon(bool retry = true) {return sock;}-std::string send_and_wait(int sock, const std::string& cmd) {- write(sock, cmd.c_str(), cmd.size());- char buf[4096];- ssize_t n = read(sock, buf, sizeof(buf) - 1);- if (n > 0) {- buf[n] = '\0';- return std::string(buf);+SSL* g_ssl = nullptr;+int g_sock = -1;++std::string send_and_wait(const std::string& cmd) {+ char buf[65536];++ if (g_ssl) {+ int w = SSL_write(g_ssl, cmd.c_str(), cmd.size());+ if (w <= 0) return "";+ int n = SSL_read(g_ssl, buf, sizeof(buf) - 1);+ if (n > 0) {+ buf[n] = '\0';+ return std::string(buf);+ }+ } else {+ write(g_sock, cmd.c_str(), cmd.size());+ ssize_t n = read(g_sock, buf, sizeof(buf) - 1);+ if (n > 0) {+ buf[n] = '\0';+ return std::string(buf);+ }}return "";}@@ -94,6 +115,8 @@ int main(int argc, char* argv[]) {std::string action;std::string arg_val;+ std::string host = "";+ int port = 5134;for (int i = 1; i < argc; ++i) {std::string arg = argv[i];@@ -102,6 +125,17 @@ int main(int argc, char* argv[]) {return 0;} else if (arg == "-g" || arg == "--get-clipboard") {action = "get";+ } else if (arg == "--list-devices") {+ action = "list";+ } else if (arg == "--accept") {+ action = "accept";+ if (i + 1 < argc && argv[i + 1][0] != '-') arg_val = argv[++i];+ } else if (arg == "--pair") {+ action = "pair";+ } else if (arg == "--host") {+ if (i + 1 < argc && argv[i + 1][0] != '-') host = argv[++i];+ } else if (arg == "--port") {+ if (i + 1 < argc && argv[i + 1][0] != '-') port = std::stoi(argv[++i]);} else if (arg == "-f" || arg == "--send-file") {action = "file";if (i + 1 < argc && argv[i + 1][0] != '-') {@@ -109,7 +143,6 @@ int main(int argc, char* argv[]) {}} else if (arg == "-s" || arg == "--set-clipboard") {action = "set";- // Check if there is an argument immediately following the flagif (i + 1 < argc && argv[i + 1][0] != '-') {arg_val = argv[++i];}@@ -121,21 +154,68 @@ int main(int argc, char* argv[]) {return 1;}+ if (action == "list") {+ tether::Crypto::instance().init();+ std::cout << tether::Crypto::instance().get_known_hosts_dump() << "\n";+ return 0;+ } else if (action == "accept") {+ tether::Crypto::instance().init();+ tether::Crypto::instance().add_known_host("Paired Device", arg_val);+ std::cout << "Successfully paired device: " << arg_val << "\n";+ return 0;+ }+if (action == "set" && arg_val.empty()) {- // Read from stdin+ // Read from stdin ...std::string line;while (std::getline(std::cin, line)) {arg_val += line + "\n";}if (!arg_val.empty() && arg_val.back() == '\n') {- arg_val.pop_back(); // clip final stray newline from stream end+ arg_val.pop_back();}}- int sock = connect_to_daemon();- if (sock < 0) {- std::cerr << "Failed to connect to daemon and automatic launch failed.\n";- return 1;+ if (!host.empty()) {+ // TCP TLS Connection+ g_sock = socket(AF_INET, SOCK_STREAM, 0);+ sockaddr_in addr{};+ addr.sin_family = AF_INET;+ addr.sin_port = htons(port);+ inet_pton(AF_INET, host.c_str(), &addr.sin_addr);++ if (connect(g_sock, (sockaddr*)&addr, sizeof(addr)) < 0) {+ std::cerr << "Failed to connect strictly over TCP.\n";+ return 1;+ }++ tether::Crypto::instance().init();+ SSL* ssl = SSL_new(tether::Crypto::instance().get_client_context());+ SSL_set_fd(ssl, g_sock);+ if (SSL_connect(ssl) <= 0) {+ std::cerr << "Network paired strictly rejected: SSL Handshake Failed.\n";+ return 1;+ }+ g_ssl = ssl;+ } else {+ // Unix Socket Fallback+ g_sock = connect_to_daemon();+ if (g_sock < 0) {+ std::cerr << "Failed to connect to daemon and automatic launch failed.\n";+ return 1;+ }+ }++ if (action == "pair") {+ nlohmann::json j;+ j["command"] = "pair_request";+ j["device_name"] = "CLI Test Tools";+ std::string payload = j.dump() + "\n";+ std::string response = send_and_wait(payload);+ std::cout << "Pairing response: " << response << std::flush;+ if (g_ssl) SSL_free(g_ssl);+ close(g_sock);+ return 0;}if (action == "get") {@@ -143,21 +223,21 @@ int main(int argc, char* argv[]) {j["command"] = "clipboard_get";std::string payload = j.dump() + "\n";- std::string response = send_and_wait(sock, payload);+ std::string response = send_and_wait(payload);try {nlohmann::json r = nlohmann::json::parse(response);if (r.contains("content")) {std::cout << r["content"].get<std::string>() << std::flush;+ } else if (r.contains("message") && r["message"] == "unauthorized") {+ std::cerr << "Unauthorized. You must pair this device first using a pair_request.\n";}- } catch (...) {- // fallback if protocol didn't match / ignore error- }+ } catch (...) {}} else if (action == "set") {nlohmann::json j;j["command"] = "clipboard_set";j["content"] = arg_val;std::string payload = j.dump() + "\n";- send_and_wait(sock, payload); // Ignore daemon's "OK\n"+ send_and_wait(payload);} else if (action == "file") {if (arg_val.empty() || !std::filesystem::exists(arg_val)) {std::cerr << "Invalid or missing file path: " << arg_val << "\n";@@ -181,7 +261,11 @@ int main(int argc, char* argv[]) {j_start["filename"] = filename;j_start["size"] = file_size;j_start["transfer_id"] = transfer_id;- send_and_wait(sock, j_start.dump() + "\n");+ std::string s_resp = send_and_wait(j_start.dump() + "\n");+ if (s_resp.find("unauthorized") != std::string::npos) {+ std::cerr << "Unauthorized. Device not paired.\n";+ return 1;+ }const size_t chunk_size = 512 * 1024;std::vector<unsigned char> buffer(chunk_size);@@ -199,14 +283,14 @@ int main(int argc, char* argv[]) {j_chunk["transfer_id"] = transfer_id;j_chunk["data"] = tether::base64_encode(buffer.data(), bytes_read);- send_and_wait(sock, j_chunk.dump() + "\n");+ send_and_wait(j_chunk.dump() + "\n");}nlohmann::json j_end;j_end["command"] = "file_end";j_end["transfer_id"] = transfer_id;- std::string resp = send_and_wait(sock, j_end.dump() + "\n");+ std::string resp = send_and_wait(j_end.dump() + "\n");try {nlohmann::json r = nlohmann::json::parse(resp);if (r.contains("status") && r["status"] == "success") {@@ -216,6 +300,7 @@ int main(int argc, char* argv[]) {}}- close(sock);+ if (g_ssl) SSL_free(g_ssl);+ close(g_sock);return 0;}diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txtindex df7bec0..e6492d6 100644--- a/src/core/CMakeLists.txt+++ b/src/core/CMakeLists.txt@@ -5,6 +5,7 @@ add_library(tether_core STATICsrc/clipboard.cppsrc/base64.cppsrc/file_transfer.cpp+ src/crypto.cppsrc/wayland.cppsrc/wayland_protocols/wayland.cppsrc/wayland_protocols/wlr-data-control-unstable-v1.cpp@@ -17,4 +18,6 @@ target_include_directories(tether_core PUBLICtarget_link_libraries(tether_core PUBLICnlohmann_json::nlohmann_jsonPkgConfig::WAYLAND+ OpenSSL::SSL+ OpenSSL::Crypto)diff --git a/src/core/include/tether/crypto.hpp b/src/core/include/tether/crypto.hppnew file mode 100644index 0000000..7b7afcf--- /dev/null+++ b/src/core/include/tether/crypto.hpp@@ -0,0 +1,44 @@+#pragma once++#include <openssl/err.h>+#include <openssl/ssl.h>+#include <string>+#include <vector>++namespace tether {++ class Crypto {+ public:+ static Crypto& instance();++ bool init();+ SSL_CTX* get_server_context();+ SSL_CTX* get_client_context();++ std::string get_my_fingerprint();+ bool is_host_known(const std::string& fingerprint);+ void add_known_host(const std::string& name, const std::string& fingerprint);+ std::string get_known_hosts_dump() const;++ static std::string get_peer_fingerprint(SSL* ssl);+ static std::string generate_fingerprint(X509* cert);++ private:+ Crypto() = default;+ ~Crypto();++ bool ensure_certificates();+ void load_known_hosts();+ void save_known_hosts();++ std::string cert_path_;+ std::string key_path_;+ std::string hosts_path_;++ SSL_CTX* server_ctx_ = nullptr;+ SSL_CTX* client_ctx_ = nullptr;++ std::string my_fingerprint_;+ };++} // namespace tetherdiff --git a/src/core/include/tether/net.hpp b/src/core/include/tether/net.hppindex 4bad1c7..1532d38 100644--- a/src/core/include/tether/net.hpp+++ b/src/core/include/tether/net.hpp@@ -1,6 +1,8 @@#pragma once#include "tether/event_loop.hpp"+#include <map>+#include <openssl/ssl.h>#include <string>namespace tether {@@ -52,6 +54,9 @@ namespace tether {int server_fd_ = -1;int bind_port_;std::map<int, std::string> client_buffers_;+ std::map<int, SSL*> active_ssl_;+ std::map<int, bool> ssl_handshake_complete_;+ std::map<int, bool> client_paired_;};} // namespace tetherdiff --git a/src/core/src/crypto.cpp b/src/core/src/crypto.cppnew file mode 100644index 0000000..6bbd74e--- /dev/null+++ b/src/core/src/crypto.cpp@@ -0,0 +1,193 @@+#include "tether/crypto.hpp"+#include <nlohmann/json.hpp>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <iomanip>+#include <sstream>+#include <openssl/x509.h>+#include <openssl/pem.h>+#include <openssl/rsa.h>+#include <openssl/evp.h>+#include <cstdlib>++namespace tether {++Crypto& Crypto::instance() {+ static Crypto inst;+ return inst;+}++Crypto::~Crypto() {+ if (server_ctx_) SSL_CTX_free(server_ctx_);+ if (client_ctx_) SSL_CTX_free(client_ctx_);+}++SSL_CTX* Crypto::get_server_context() { return server_ctx_; }+SSL_CTX* Crypto::get_client_context() { return client_ctx_; }++bool Crypto::init() {+ std::filesystem::path config_dir = std::string(getenv("HOME")) + "/.config/tether";+ std::filesystem::create_directories(config_dir);+ cert_path_ = (config_dir / "cert.pem").string();+ key_path_ = (config_dir / "key.pem").string();+ hosts_path_ = (config_dir / "known_hosts.json").string();++ if (!ensure_certificates()) return false;++ // server context+ const SSL_METHOD* server_method = TLS_server_method();+ server_ctx_ = SSL_CTX_new(server_method);+ if (!server_ctx_) return false;++ SSL_CTX_use_certificate_file(server_ctx_, cert_path_.c_str(), SSL_FILETYPE_PEM);+ SSL_CTX_use_PrivateKey_file(server_ctx_, key_path_.c_str(), SSL_FILETYPE_PEM);+ if (!SSL_CTX_check_private_key(server_ctx_)) return false;++ // Mutually Authenticate, but accept anything to allow pairing request processing+ SSL_CTX_set_verify(server_ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, [](int, X509_STORE_CTX*) {+ return 1;+ });++ // client context+ const SSL_METHOD* client_method = TLS_client_method();+ client_ctx_ = SSL_CTX_new(client_method);+ if (!client_ctx_) return false;++ SSL_CTX_use_certificate_file(client_ctx_, cert_path_.c_str(), SSL_FILETYPE_PEM);+ SSL_CTX_use_PrivateKey_file(client_ctx_, key_path_.c_str(), SSL_FILETYPE_PEM);++ SSL_CTX_set_verify(client_ctx_, SSL_VERIFY_PEER, [](int, X509_STORE_CTX*) {+ return 1;+ });++ // Derive my fingerprint+ FILE* f = fopen(cert_path_.c_str(), "r");+ if (f) {+ X509* x = PEM_read_X509(f, nullptr, nullptr, nullptr);+ fclose(f);+ if (x) {+ my_fingerprint_ = generate_fingerprint(x);+ X509_free(x);+ }+ }++ load_known_hosts();+ return true;+}++bool Crypto::ensure_certificates() {+ if (std::filesystem::exists(cert_path_) && std::filesystem::exists(key_path_)) {+ return true;+ }++ std::cout << "Crypto: Generating native mTLS RSA/X509 Keypair into ~/.config/tether/..." << std::endl;++ EVP_PKEY* pkey = EVP_PKEY_new();+ BIGNUM* bne = BN_new();+ BN_set_word(bne, RSA_F4);+ RSA* rsa = RSA_new();+ RSA_generate_key_ex(rsa, 2048, bne, nullptr);+ EVP_PKEY_assign_RSA(pkey, rsa); // pkey owns rsa now+ BN_free(bne);++ X509* x509 = X509_new();+ ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);+ X509_gmtime_adj(X509_get_notBefore(x509), 0);+ X509_gmtime_adj(X509_get_notAfter(x509), 315360000L); // 10 years++ X509_set_pubkey(x509, pkey);+ X509_NAME* name = X509_get_subject_name(x509);+ X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char*)"Tether", -1, -1, 0);+ X509_set_issuer_name(x509, name);++ X509_sign(x509, pkey, EVP_sha256());++ FILE* f_key = fopen(key_path_.c_str(), "wb");+ if (f_key) {+ PEM_write_PrivateKey(f_key, pkey, nullptr, nullptr, 0, nullptr, nullptr);+ fclose(f_key);+ }++ FILE* f_cert = fopen(cert_path_.c_str(), "wb");+ if (f_cert) {+ PEM_write_X509(f_cert, x509);+ fclose(f_cert);+ }++ X509_free(x509);+ EVP_PKEY_free(pkey);++ std::filesystem::permissions(key_path_, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write);+ return true;+}++void Crypto::load_known_hosts() {+ if (!std::filesystem::exists(hosts_path_)) {+ nlohmann::json empty = nlohmann::json::object();+ std::ofstream off(hosts_path_);+ off << empty.dump(4);+ }+}++void Crypto::save_known_hosts() {+ // We do it directly in add_known_host right now+}++bool Crypto::is_host_known(const std::string& fingerprint) {+ std::ifstream iff(hosts_path_);+ if (!iff.is_open()) return false;+ try {+ nlohmann::json j = nlohmann::json::parse(iff);+ return j.contains(fingerprint);+ } catch (...) { return false; }+}++void Crypto::add_known_host(const std::string& name, const std::string& fingerprint) {+ nlohmann::json j;+ std::ifstream iff(hosts_path_);+ if (iff.is_open()) {+ try { j = nlohmann::json::parse(iff); } catch (...) {}+ }+ j[fingerprint] = name;++ std::ofstream off(hosts_path_);+ off << j.dump(4);+}++std::string Crypto::get_known_hosts_dump() const {+ std::ifstream iff(hosts_path_);+ if (iff.is_open()) {+ try {+ nlohmann::json j = nlohmann::json::parse(iff);+ return j.dump();+ } catch (...) {}+ }+ return "{}";+}++std::string Crypto::get_my_fingerprint() {+ return my_fingerprint_;+}++std::string Crypto::generate_fingerprint(X509* cert) {+ unsigned char hash[SHA256_DIGEST_LENGTH];+ unsigned int len = 0;+ X509_digest(cert, EVP_sha256(), hash, &len);++ std::stringstream ss;+ for (unsigned int i = 0; i < len; ++i) {+ ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];+ }+ return ss.str();+}++std::string Crypto::get_peer_fingerprint(SSL* ssl) {+ X509* cert = SSL_get_peer_certificate(ssl);+ if (!cert) return "";+ std::string print = generate_fingerprint(cert);+ X509_free(cert);+ return print;+}++} // namespace tetherdiff --git a/src/core/src/net.cpp b/src/core/src/net.cppindex 5763067..a9db107 100644--- a/src/core/src/net.cpp+++ b/src/core/src/net.cpp@@ -11,6 +11,7 @@#include "tether/file_transfer.hpp"#include "tether/wayland.hpp"+#include "tether/crypto.hpp"#include <cstring>#include <filesystem>#include <iostream>@@ -252,28 +253,63 @@ namespace tether {sockaddr_in client_addr{};socklen_t addrlen = sizeof(client_addr);int client_fd = accept(fd, reinterpret_cast<sockaddr*>(&client_addr), &addrlen);- if (client_fd < 0) {- if (errno != EAGAIN && errno != EWOULDBLOCK) {- std::cerr << "TcpServer accept error: " << std::strerror(errno) << std::endl;- }- return;- }+ if (client_fd < 0) return;// Set non-blockingint flags = fcntl(client_fd, F_GETFL, 0);fcntl(client_fd, F_SETFL, flags | O_NONBLOCK);- register_client_fd(client_fd);- loop_.addFd(client_fd, [this](int cfd) { handle_client(cfd); });-char ip[INET_ADDRSTRLEN];inet_ntop(AF_INET, &(client_addr.sin_addr), ip, INET_ADDRSTRLEN);std::cout << "TcpServer: New connection from " << ip << " (fd: " << client_fd << ")" << std::endl;++ // SSL Wrapping+ SSL* ssl = SSL_new(Crypto::instance().get_server_context());+ SSL_set_fd(ssl, client_fd);+ SSL_set_accept_state(ssl);++ active_ssl_[client_fd] = ssl;+ ssl_handshake_complete_[client_fd] = false;+ client_paired_[client_fd] = false;++ register_client_fd(client_fd);+ loop_.addFd(client_fd, [this](int cfd) { handle_client(cfd); });}void TcpServer::handle_client(int client_fd) {+ SSL* ssl = active_ssl_[client_fd];++ if (!ssl_handshake_complete_[client_fd]) {+ int ret = SSL_accept(ssl);+ if (ret == 1) {+ ssl_handshake_complete_[client_fd] = true;+ std::string print = Crypto::get_peer_fingerprint(ssl);+ if (Crypto::instance().is_host_known(print)) {+ client_paired_[client_fd] = true;+ } else {+ std::cout << "TcpServer: Untrusted client connected. Fingerprint: " << print << std::endl;+ }+ } else {+ int err = SSL_get_error(ssl, ret);+ if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {+ return; // Wait for Epoll to re-trigger+ }++ // Handshake strictly failed+ SSL_free(ssl);+ active_ssl_.erase(client_fd);+ client_buffers_.erase(client_fd);+ ssl_handshake_complete_.erase(client_fd);+ client_paired_.erase(client_fd);+ unregister_client_fd(client_fd);+ loop_.removeFd(client_fd);+ close(client_fd);+ return;+ }+ }+char buf[65536];- ssize_t n = read(client_fd, buf, sizeof(buf) - 1);+ int n = SSL_read(ssl, buf, sizeof(buf) - 1);if (n > 0) {buf[n] = '\0';client_buffers_[client_fd] += std::string(buf, n);@@ -286,6 +322,24 @@ namespace tether {try {nlohmann::json j = nlohmann::json::parse(msg);+ if (!client_paired_[client_fd]) {+ if (j.contains("command") && j["command"] == "pair_request") {+ std::string print = Crypto::get_peer_fingerprint(ssl);+ std::string dev_name = j.value("device_name", "Unknown Device");+ std::cout << "[Pairing Request Pending] from " << dev_name+ << ". Accept by running: tether --accept " << print << std::endl;++ nlohmann::json resp;+ resp["command"] = "pair_pending";+ std::string payload = resp.dump() + "\n";+ SSL_write(ssl, payload.c_str(), payload.size());+ } else {+ std::string rej = "{\"command\":\"error\",\"message\":\"unauthorized\"}\n";+ SSL_write(ssl, rej.c_str(), rej.size());+ }+ continue;+ }+if (j.contains("command") && j["command"] == "clipboard_set" && j.contains("content")) {std::string content = j["content"];if (g_wayland)@@ -296,7 +350,7 @@ namespace tether {resp["command"] = "clipboard_content";resp["content"] = g_wayland->get_clipboard();std::string payload = resp.dump() + "\n";- write(client_fd, payload.c_str(), payload.size());+ SSL_write(ssl, payload.c_str(), payload.size());continue;}} else if (j.contains("command") && j["command"] == "file_start") {@@ -312,7 +366,7 @@ namespace tether {resp["transfer_id"] = j["transfer_id"];resp["status"] = "success";std::string payload = resp.dump() + "\n";- write(client_fd, payload.c_str(), payload.size());+ SSL_write(ssl, payload.c_str(), payload.size());continue;}}@@ -320,11 +374,20 @@ namespace tether {}std::string response = "OK\n";- write(client_fd, response.c_str(), response.size());+ SSL_write(ssl, response.c_str(), response.size());}- } else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {+ } else {+ int err = SSL_get_error(ssl, n);+ if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {+ return;+ }+std::cout << "TcpServer: Client disconnected (fd: " << client_fd << ")" << std::endl;+ SSL_free(ssl);+ active_ssl_.erase(client_fd);client_buffers_.erase(client_fd);+ ssl_handshake_complete_.erase(client_fd);+ client_paired_.erase(client_fd);unregister_client_fd(client_fd);loop_.removeFd(client_fd);close(client_fd);diff --git a/src/daemon/main.cpp b/src/daemon/main.cppindex 837ac5e..88e83a4 100644--- a/src/daemon/main.cpp+++ b/src/daemon/main.cpp@@ -4,6 +4,7 @@#include <tether/event_loop.hpp>#include <tether/wayland.hpp>#include <tether/file_transfer.hpp>+#include <tether/crypto.hpp>#include <nlohmann/json.hpp>#include <csignal>@@ -26,6 +27,11 @@ int main(int argc, char** argv) {return 1;}+ if (!tether::Crypto::instance().init()) {+ std::cerr << "Fatal: Failed to initialize OpenSSL mTLS engine." << std::endl;+ return 1;+ }+// Capture Ctrl-C gracefully and stop the event loopstd::signal(SIGINT, signal_handler);std::signal(SIGTERM, signal_handler);