licenz-core 0.2.0

Offline software license verification with RSA signatures, hardware binding, and anti-tamper detection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Hardware detection for license binding
//!
//! This module provides functionality to detect hardware identifiers
//! for binding licenses to specific machines.
//!
//! ## Pluggable environment
//!
//! Use [`HardwareEnvironment`] to supply [`HardwareInfo`] for verification and attestation.
//! The default implementation calls [`detect_hardware`]. Integrators can provide a custom
//! implementation (for example TPM-derived material in the license `HardwareBinding` `custom` map) without
//! modifying this crate.

use crate::license::HardwareBinding;
use std::sync::Arc;

/// Supplies a snapshot of the current machine for license binding checks.
///
/// Implement this type in your application or a companion crate if the default
/// OS-visible probe ([`detect_hardware`]) is not sufficient.
pub trait HardwareEnvironment: Send + Sync {
    /// Current hardware identifiers as seen by the licensing layer.
    fn snapshot(&self) -> HardwareInfo;
}

/// Default probe: MAC addresses, disk IDs, hostname, machine ID via [`detect_hardware`].
#[derive(Debug, Clone, Copy, Default)]
pub struct DefaultHardwareEnvironment;

impl HardwareEnvironment for DefaultHardwareEnvironment {
    fn snapshot(&self) -> HardwareInfo {
        detect_hardware()
    }
}

/// Fixed snapshot (tests, diagnostics, or air-gapped override).
#[derive(Debug, Clone)]
pub struct FixedHardwareEnvironment(pub HardwareInfo);

impl HardwareEnvironment for FixedHardwareEnvironment {
    fn snapshot(&self) -> HardwareInfo {
        self.0.clone()
    }
}

/// Shared default implementation used by [`LicenseVerifier`](crate::verifier::LicenseVerifier) and [`WitnessConfig`](crate::witness::WitnessConfig).
pub fn default_hardware_environment() -> Arc<dyn HardwareEnvironment> {
    Arc::new(DefaultHardwareEnvironment)
}

/// Detected hardware information from the current machine
#[derive(Debug, Clone, Default)]
pub struct HardwareInfo {
    /// All detected MAC addresses
    pub mac_addresses: Vec<String>,

    /// Detected disk/volume serial numbers
    pub disk_ids: Vec<String>,

    /// System hostname
    pub hostname: Option<String>,

    /// Machine UUID (if available)
    pub machine_id: Option<String>,
}

impl HardwareInfo {
    /// Convert to a HardwareBinding (for creating hardware-bound licenses)
    pub fn to_binding(&self) -> HardwareBinding {
        let mut binding = HardwareBinding::new();

        if !self.mac_addresses.is_empty() {
            binding.mac_addresses = self.mac_addresses.clone();
        }

        if !self.disk_ids.is_empty() {
            binding.disk_ids = self.disk_ids.clone();
        }

        if let Some(ref hostname) = self.hostname {
            binding.hostnames.push(hostname.clone());
        }

        if let Some(ref machine_id) = self.machine_id {
            binding
                .custom
                .insert("machine_id".to_string(), vec![machine_id.clone()]);
        }

        binding
    }
}

/// Detect hardware information from the current machine
///
/// When the `hardware-detect` feature is disabled, this returns empty/None for all fields.
pub fn detect_hardware() -> HardwareInfo {
    #[cfg(feature = "hardware-detect")]
    {
        HardwareInfo {
            mac_addresses: detect_mac_addresses(),
            hostname: detect_hostname(),
            disk_ids: detect_disk_ids(),
            machine_id: detect_machine_id(),
        }
    }
    #[cfg(not(feature = "hardware-detect"))]
    {
        HardwareInfo {
            mac_addresses: vec![],
            hostname: None,
            disk_ids: vec![],
            machine_id: None,
        }
    }
}

#[cfg(feature = "hardware-detect")]
/// Detect all MAC addresses on the system
fn detect_mac_addresses() -> Vec<String> {
    let mut macs = Vec::new();

    // Try to get MAC addresses using mac_address crate
    if let Ok(Some(mac)) = mac_address::get_mac_address() {
        macs.push(mac.to_string().to_uppercase());
    }

    // Also try to get all interfaces
    if let Ok(Some(mac)) = mac_address::mac_address_by_name("eth0") {
        let mac_str = mac.to_string().to_uppercase();
        if !macs.contains(&mac_str) {
            macs.push(mac_str);
        }
    }

    // Use sysinfo for additional network info
    use sysinfo::Networks;
    let networks = Networks::new_with_refreshed_list();

    for (interface_name, _data) in networks.iter() {
        // Try to get MAC for each interface
        if let Ok(Some(mac)) = mac_address::mac_address_by_name(interface_name) {
            let mac_str = mac.to_string().to_uppercase();
            if !macs.contains(&mac_str) && !mac_str.starts_with("00:00:00") {
                macs.push(mac_str);
            }
        }
    }

    macs
}

#[cfg(feature = "hardware-detect")]
/// Detect the system hostname
fn detect_hostname() -> Option<String> {
    hostname::get()
        .ok()
        .and_then(|h| h.into_string().ok())
        .map(|s| s.to_lowercase())
}

#[cfg(feature = "hardware-detect")]
/// Detect disk serial numbers
fn detect_disk_ids() -> Vec<String> {
    let mut disk_ids = Vec::new();

    use sysinfo::Disks;
    let disks = Disks::new_with_refreshed_list();

    for disk in disks.iter() {
        // Get the disk name/mount point as an identifier
        let name = disk.name().to_string_lossy().to_string();
        if !name.is_empty() && !disk_ids.contains(&name) {
            disk_ids.push(name);
        }
    }

    // On Linux, try to read disk serial from /sys
    #[cfg(target_os = "linux")]
    {
        if let Ok(entries) = std::fs::read_dir("/sys/block") {
            for entry in entries.flatten() {
                let path = entry.path().join("device/serial");
                if let Ok(serial) = std::fs::read_to_string(&path) {
                    let serial = serial.trim().to_string();
                    if !serial.is_empty() && !disk_ids.contains(&serial) {
                        disk_ids.push(serial);
                    }
                }
            }
        }
    }

    disk_ids
}

#[cfg(feature = "hardware-detect")]
/// Detect machine ID (platform-specific)
fn detect_machine_id() -> Option<String> {
    // Linux: /etc/machine-id
    #[cfg(target_os = "linux")]
    {
        if let Ok(id) = std::fs::read_to_string("/etc/machine-id") {
            return Some(id.trim().to_string());
        }
        if let Ok(id) = std::fs::read_to_string("/var/lib/dbus/machine-id") {
            return Some(id.trim().to_string());
        }
    }

    // macOS: Use IOPlatformSerialNumber
    #[cfg(target_os = "macos")]
    {
        use std::process::Command;
        if let Ok(output) = Command::new("ioreg")
            .args(["-rd1", "-c", "IOPlatformExpertDevice"])
            .output()
        {
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines() {
                if line.contains("IOPlatformUUID") {
                    if let Some(start) = line.find('"') {
                        if let Some(end) = line.rfind('"') {
                            if start < end {
                                return Some(line[start + 1..end].to_string());
                            }
                        }
                    }
                }
            }
        }
    }

    // Windows: Use wmic or registry
    #[cfg(target_os = "windows")]
    {
        use std::process::Command;
        if let Ok(output) = Command::new("wmic")
            .args(["csproduct", "get", "UUID"])
            .output()
        {
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines().skip(1) {
                let uuid = line.trim();
                if !uuid.is_empty() && uuid != "UUID" {
                    return Some(uuid.to_string());
                }
            }
        }
    }

    None
}

/// Check if the current hardware matches the binding
pub fn verify_hardware_binding(
    binding: &HardwareBinding,
    current: &HardwareInfo,
) -> Result<(), HardwareBindingError> {
    // If no binding is set, always pass
    if binding.is_empty() {
        return Ok(());
    }

    // Check MAC addresses (any match is valid)
    if !binding.mac_addresses.is_empty() {
        let current_macs: Vec<String> = current
            .mac_addresses
            .iter()
            .map(|m| m.to_uppercase())
            .collect();

        let has_match = binding
            .mac_addresses
            .iter()
            .any(|bound| current_macs.contains(&bound.to_uppercase()));

        if !has_match {
            return Err(HardwareBindingError::MacAddressMismatch {
                expected: binding.mac_addresses.clone(),
                found: current.mac_addresses.clone(),
            });
        }
    }

    // Check hostnames (any match is valid)
    if !binding.hostnames.is_empty() {
        if let Some(ref current_hostname) = current.hostname {
            let has_match = binding
                .hostnames
                .iter()
                .any(|bound| bound.eq_ignore_ascii_case(current_hostname));

            if !has_match {
                return Err(HardwareBindingError::HostnameMismatch {
                    expected: binding.hostnames.clone(),
                    found: current_hostname.clone(),
                });
            }
        } else {
            return Err(HardwareBindingError::HostnameMismatch {
                expected: binding.hostnames.clone(),
                found: "<unknown>".to_string(),
            });
        }
    }

    // Check disk IDs (any match is valid)
    if !binding.disk_ids.is_empty() {
        let has_match = binding
            .disk_ids
            .iter()
            .any(|bound| current.disk_ids.contains(bound));

        if !has_match {
            return Err(HardwareBindingError::DiskIdMismatch {
                expected: binding.disk_ids.clone(),
                found: current.disk_ids.clone(),
            });
        }
    }

    // Check custom bindings
    for (key, expected_values) in &binding.custom {
        if key == "machine_id" {
            if let Some(ref current_id) = current.machine_id {
                if !expected_values.contains(current_id) {
                    return Err(HardwareBindingError::CustomMismatch {
                        key: key.clone(),
                        expected: expected_values.clone(),
                        found: current_id.clone(),
                    });
                }
            }
        }
    }

    Ok(())
}

/// Hardware binding verification errors
#[derive(Debug, Clone)]
pub enum HardwareBindingError {
    MacAddressMismatch {
        expected: Vec<String>,
        found: Vec<String>,
    },
    HostnameMismatch {
        expected: Vec<String>,
        found: String,
    },
    DiskIdMismatch {
        expected: Vec<String>,
        found: Vec<String>,
    },
    CustomMismatch {
        key: String,
        expected: Vec<String>,
        found: String,
    },
}

impl std::fmt::Display for HardwareBindingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MacAddressMismatch { expected, found } => {
                write!(
                    f,
                    "MAC address mismatch: expected one of {:?}, found {:?}",
                    expected, found
                )
            }
            Self::HostnameMismatch { expected, found } => {
                write!(
                    f,
                    "Hostname mismatch: expected one of {:?}, found {}",
                    expected, found
                )
            }
            Self::DiskIdMismatch { expected, found } => {
                write!(
                    f,
                    "Disk ID mismatch: expected one of {:?}, found {:?}",
                    expected, found
                )
            }
            Self::CustomMismatch {
                key,
                expected,
                found,
            } => {
                write!(
                    f,
                    "Custom binding '{}' mismatch: expected one of {:?}, found {}",
                    key, expected, found
                )
            }
        }
    }
}

impl std::error::Error for HardwareBindingError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_binding_always_passes() {
        let binding = HardwareBinding::new();
        let hardware = HardwareInfo::default();

        assert!(verify_hardware_binding(&binding, &hardware).is_ok());
    }

    #[test]
    fn test_mac_address_binding() {
        let binding = HardwareBinding::new().with_mac_address("AA:BB:CC:DD:EE:FF");

        let mut hardware = HardwareInfo {
            mac_addresses: vec!["AA:BB:CC:DD:EE:FF".to_string()],
            ..Default::default()
        };

        assert!(verify_hardware_binding(&binding, &hardware).is_ok());

        hardware.mac_addresses = vec!["11:22:33:44:55:66".to_string()];
        assert!(verify_hardware_binding(&binding, &hardware).is_err());
    }

    #[test]
    fn test_hostname_binding() {
        let binding = HardwareBinding::new().with_hostname("my-server");

        let mut hardware = HardwareInfo {
            hostname: Some("my-server".to_string()),
            ..Default::default()
        };

        assert!(verify_hardware_binding(&binding, &hardware).is_ok());

        hardware.hostname = Some("other-server".to_string());
        assert!(verify_hardware_binding(&binding, &hardware).is_err());
    }
}