DevelopmentNodeEnvironment_MicrosoftVSCodeDependency_22NodeVersion_Bundle_Clean_Debug_ElectronProfile_EsbuildCompiler_Mountain/IPC/WindServiceHandlers/Encryption/Key.rs
1#![allow(non_snake_case)]
2
3//! Machine-stable 256-bit key derivation for AES-256-GCM.
4//!
5//! The key is derived once per process from the host's hardware UUID using
6//! SHA-256: `key = SHA-256("Land-Encryption-v1" ++ machine_id)`.
7//!
8//! Rationale: using the machine ID means ciphertext produced by
9//! `encryption:encrypt` survives process restarts (same key each time) but
10//! cannot be decrypted on a different machine, matching VS Code's
11//! `dpapi`/`safeStorage` semantics. No HSM or external key storage required.
12
13use std::sync::OnceLock;
14
15use ring::digest::{SHA256, digest};
16
17static DERIVED_KEY:[OnceLock<[u8; 32]>; 1] = [OnceLock::new()];
18
19/// Returns the process-wide 256-bit encryption key.
20pub fn DeriveKey() -> [u8; 32] { *DERIVED_KEY[0].get_or_init(ComputeKey) }
21
22fn ComputeKey() -> [u8; 32] {
23 let MachineId = ReadMachineId();
24
25 let Input = format!("Land-Encryption-v1{}", MachineId);
26
27 let Hash = digest(&SHA256, Input.as_bytes());
28
29 let mut Key = [0u8; 32];
30
31 Key.copy_from_slice(Hash.as_ref());
32
33 Key
34}
35
36fn ReadMachineId() -> String {
37 #[cfg(target_os = "macos")]
38 {
39 if let Ok(Out) = std::process::Command::new("ioreg")
40 .args(["-rd1", "-c", "IOPlatformExpertDevice"])
41 .output()
42 {
43 let S = String::from_utf8_lossy(&Out.stdout);
44 for Line in S.lines() {
45 if Line.contains("IOPlatformUUID") {
46 if let Some(Start) = Line.rfind('"') {
47 let Rest = &Line[..Start];
48 if let Some(End) = Rest.rfind('"') {
49 return Rest[End + 1..].to_string();
50 }
51 }
52 }
53 }
54 }
55 }
56
57 #[cfg(target_os = "linux")]
58 {
59 if let Ok(Id) = std::fs::read_to_string("/etc/machine-id") {
60 let Trimmed = Id.trim().to_string();
61 if !Trimmed.is_empty() {
62 return Trimmed;
63 }
64 }
65 if let Ok(Id) = std::fs::read_to_string("/var/lib/dbus/machine-id") {
66 let Trimmed = Id.trim().to_string();
67 if !Trimmed.is_empty() {
68 return Trimmed;
69 }
70 }
71 }
72
73 #[cfg(target_os = "windows")]
74 {
75 use std::process::Command;
76 if let Ok(Out) = Command::new("reg")
77 .args(["query", "HKLM\\SOFTWARE\\Microsoft\\Cryptography", "/v", "MachineGuid"])
78 .output()
79 {
80 let S = String::from_utf8_lossy(&Out.stdout);
81 if let Some(Line) = S.lines().find(|L| L.contains("MachineGuid")) {
82 if let Some(Id) = Line.split_whitespace().last() {
83 return Id.to_string();
84 }
85 }
86 }
87 }
88
89 // Fallback: use the executable path hash so at least different installs
90 // produce different keys.
91 std::env::current_exe()
92 .map(|P| format!("{:?}", P))
93 .unwrap_or_else(|_| "fallback-land-key-seed".to_string())
94}