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
//! Anti-tamper and clock manipulation detection
//!
//! This module provides countermeasures against common license bypass techniques.

use crate::error::{LicenseError, Result};
use chrono::{DateTime, Duration, Utc};
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::path::Path;

type HmacSha256 = Hmac<Sha256>;

/// Prefix for HMAC-protected state files (see [`LicenseState::save`]).
pub const STATE_HMAC_PREFIX: &str = "hmac1:";

/// Persistent state for detecting clock manipulation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LicenseState {
    /// Last successful validation timestamp
    pub last_validated: DateTime<Utc>,

    /// Last observed system time
    pub last_system_time: DateTime<Utc>,

    /// Monotonic counter (always increases)
    pub validation_count: u64,

    /// Hash of license ID being tracked
    pub license_id_hash: String,

    /// State file integrity checksum
    #[serde(skip)]
    checksum: Option<String>,
}

impl LicenseState {
    /// Create new state for a license
    pub fn new(license_id: &str) -> Self {
        let now = Utc::now();
        Self {
            last_validated: now,
            last_system_time: now,
            validation_count: 1,
            license_id_hash: hash_string(license_id),
            checksum: None,
        }
    }

    /// Load state from file. The file must use HMAC integrity ([`LicenseState::save`]);
    /// `key` must match the key used at save time.
    pub fn load(path: &Path, license_id: &str, key: &[u8; 32]) -> Result<Option<Self>> {
        if !path.exists() {
            return Ok(None);
        }

        let contents = std::fs::read_to_string(path)?;

        let lines: Vec<&str> = contents.lines().collect();
        if lines.len() < 2 {
            return Ok(None);
        }

        let json_data = lines[..lines.len() - 1].join("\n");
        let stored_line = lines.last().unwrap_or(&"").trim();

        if !stored_line.starts_with(STATE_HMAC_PREFIX) {
            return Err(LicenseError::Validation(
                "License state file must use HMAC integrity (hmac1: prefix); re-save with LicenseState::save"
                    .into(),
            ));
        }

        let hex_part = stored_line
            .strip_prefix(STATE_HMAC_PREFIX)
            .unwrap_or("")
            .trim();
        verify_state_hmac(key, json_data.as_bytes(), hex_part)?;

        let mut state: Self = serde_json::from_str(&json_data)
            .map_err(|e| LicenseError::InvalidLicenseFormat(e.to_string()))?;

        if state.license_id_hash != hash_string(license_id) {
            return Err(LicenseError::StateLicenseMismatch);
        }

        state.checksum = Some(stored_line.to_string());
        Ok(Some(state))
    }

    /// Save state with HMAC-SHA256 over the JSON (`key` from secure application storage).
    pub fn save(&self, path: &Path, key: &[u8; 32]) -> Result<()> {
        let json_data = serde_json::to_string_pretty(self)
            .map_err(|e| LicenseError::SerializationError(e.to_string()))?;

        let mac_hex = compute_state_hmac_hex(key, json_data.as_bytes());
        let contents = format!("{}\n{}{}", json_data, STATE_HMAC_PREFIX, mac_hex);

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        std::fs::write(path, contents)?;
        Ok(())
    }

    /// Check for clock manipulation
    pub fn detect_clock_manipulation(&self, tolerance: Duration) -> Result<ClockStatus> {
        let now = Utc::now();

        // Check if clock went backwards significantly
        if now < self.last_system_time {
            let drift = self.last_system_time - now;

            if drift > tolerance {
                return Ok(ClockStatus::Backwards {
                    drift,
                    last_seen: self.last_system_time,
                    current: now,
                });
            }
        }

        // Check for suspicious forward jump (could indicate tampering then reset)
        let time_since_last = now - self.last_system_time;
        if time_since_last > Duration::days(365) {
            return Ok(ClockStatus::SuspiciousJump {
                jump: time_since_last,
                last_seen: self.last_system_time,
                current: now,
            });
        }

        Ok(ClockStatus::Ok { current: now })
    }

    /// Update state after successful validation
    pub fn record_validation(&mut self) {
        let now = Utc::now();
        self.last_validated = now;
        self.last_system_time = now;
        self.validation_count += 1;
    }
}

/// Result of clock manipulation check
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ClockStatus {
    /// Clock is within acceptable range
    Ok { current: DateTime<Utc> },

    /// Clock moved backwards (possible manipulation)
    Backwards {
        drift: Duration,
        last_seen: DateTime<Utc>,
        current: DateTime<Utc>,
    },

    /// Clock jumped forward suspiciously far
    SuspiciousJump {
        jump: Duration,
        last_seen: DateTime<Utc>,
        current: DateTime<Utc>,
    },
}

impl ClockStatus {
    pub fn is_ok(&self) -> bool {
        matches!(self, ClockStatus::Ok { .. })
    }
}

/// Multi-factor hardware fingerprint for stronger binding
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HardwareFingerprint {
    /// Hashed MAC addresses
    pub mac_hashes: Vec<String>,

    /// Hashed disk serial numbers
    pub disk_hashes: Vec<String>,

    /// Hashed hostname
    pub hostname_hash: Option<String>,

    /// Hashed machine GUID (OS-level)
    pub machine_guid_hash: Option<String>,

    /// Combined fingerprint hash
    pub combined_hash: String,
}

impl HardwareFingerprint {
    /// Generate fingerprint using the default OS-visible [`crate::hardware::HardwareEnvironment`].
    pub fn generate() -> Self {
        Self::generate_with(&crate::hardware::DefaultHardwareEnvironment)
    }

    /// Generate fingerprint from a [`crate::hardware::HardwareEnvironment`] snapshot.
    pub fn generate_with(env: &dyn crate::hardware::HardwareEnvironment) -> Self {
        Self::from_hardware_info(&env.snapshot())
    }

    /// Build fingerprint from a [`crate::hardware::HardwareInfo`] snapshot.
    pub fn from_hardware_info(hw: &crate::hardware::HardwareInfo) -> Self {
        let mac_hashes: Vec<String> = hw.mac_addresses.iter().map(|m| hash_string(m)).collect();

        let disk_hashes: Vec<String> = hw.disk_ids.iter().map(|d| hash_string(d)).collect();

        let hostname_hash = hw.hostname.as_ref().map(|h| hash_string(h));
        let machine_guid_hash = hw.machine_id.as_ref().map(|m| hash_string(m));

        let mut combined = String::new();
        for hash in &mac_hashes {
            combined.push_str(hash);
        }
        for hash in &disk_hashes {
            combined.push_str(hash);
        }
        if let Some(ref h) = hostname_hash {
            combined.push_str(h);
        }
        if let Some(ref m) = machine_guid_hash {
            combined.push_str(m);
        }

        let combined_hash = hash_string(&combined);

        Self {
            mac_hashes,
            disk_hashes,
            hostname_hash,
            machine_guid_hash,
            combined_hash,
        }
    }

    /// Calculate match score against a binding
    pub fn match_score(&self, other: &HardwareFingerprint) -> MatchResult {
        let mut score = 0u32;
        let mut max_score = 0u32;

        // MAC addresses (weight: 2)
        max_score += 2;
        if self.mac_hashes.iter().any(|h| other.mac_hashes.contains(h)) {
            score += 2;
        }

        // Disk serials (weight: 3) - harder to spoof
        max_score += 3;
        if self
            .disk_hashes
            .iter()
            .any(|h| other.disk_hashes.contains(h))
        {
            score += 3;
        }

        // Hostname (weight: 1) - easy to change
        if self.hostname_hash.is_some() || other.hostname_hash.is_some() {
            max_score += 1;
            if self.hostname_hash == other.hostname_hash {
                score += 1;
            }
        }

        // Machine GUID (weight: 4) - OS-level, hardest to spoof
        if self.machine_guid_hash.is_some() || other.machine_guid_hash.is_some() {
            max_score += 4;
            if self.machine_guid_hash == other.machine_guid_hash {
                score += 4;
            }
        }

        let percentage = if max_score > 0 {
            (score as f32 / max_score as f32) * 100.0
        } else {
            100.0
        };

        MatchResult {
            score,
            max_score,
            percentage,
        }
    }
}

/// Result of hardware fingerprint matching
///
/// Note: This struct provides attestation data only. The policy layer
/// (e.g., `licenz-policy` crate) decides whether the match percentage
/// is sufficient based on configurable thresholds.
#[derive(Debug, Clone)]
pub struct MatchResult {
    pub score: u32,
    pub max_score: u32,
    pub percentage: f32,
}

impl MatchResult {
    /// Check if the match meets a given threshold (0.0 - 100.0)
    ///
    /// This is a convenience method. Policy enforcement should use
    /// the `percentage` field directly with configurable thresholds.
    pub fn meets_threshold(&self, threshold_percent: f32) -> bool {
        self.percentage >= threshold_percent
    }
}

/// Hash a string with SHA-256 and return hex
fn hash_string(input: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(input.as_bytes());
    hex::encode(hasher.finalize())
}

fn compute_state_hmac_hex(key: &[u8; 32], data: &[u8]) -> String {
    let mut mac = HmacSha256::new_from_slice(key.as_slice()).expect("HMAC accepts 32-byte key");
    mac.update(data);
    hex::encode(mac.finalize().into_bytes())
}

fn verify_state_hmac(key: &[u8; 32], data: &[u8], expected_hex: &str) -> Result<()> {
    let expected_bin = hex::decode(expected_hex).map_err(|_| LicenseError::StateFileTampered)?;
    let mut mac = HmacSha256::new_from_slice(key.as_slice()).expect("HMAC accepts 32-byte key");
    mac.update(data);
    mac.verify_slice(&expected_bin)
        .map_err(|_| LicenseError::StateFileTampered)
}

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

    #[test]
    fn test_clock_status_ok() {
        let state = LicenseState::new("test-license");
        let status = state.detect_clock_manipulation(Duration::hours(1)).unwrap();
        assert!(status.is_ok());
    }

    #[test]
    fn test_fingerprint_match() {
        let fp1 = HardwareFingerprint {
            mac_hashes: vec![hash_string("AA:BB:CC:DD:EE:FF")],
            disk_hashes: vec![hash_string("DISK123")],
            hostname_hash: Some(hash_string("myhost")),
            machine_guid_hash: Some(hash_string("guid123")),
            combined_hash: String::new(),
        };

        let fp2 = HardwareFingerprint {
            mac_hashes: vec![hash_string("AA:BB:CC:DD:EE:FF")],
            disk_hashes: vec![hash_string("DISK123")],
            hostname_hash: Some(hash_string("myhost")),
            machine_guid_hash: Some(hash_string("guid123")),
            combined_hash: String::new(),
        };

        let result = fp1.match_score(&fp2);
        assert_eq!(result.percentage, 100.0);
        assert!(result.meets_threshold(70.0)); // Policy decision made by caller
    }

    #[test]
    fn test_partial_fingerprint_match() {
        let fp1 = HardwareFingerprint {
            mac_hashes: vec![hash_string("AA:BB:CC:DD:EE:FF")],
            disk_hashes: vec![hash_string("DISK123")],
            hostname_hash: Some(hash_string("myhost")),
            machine_guid_hash: Some(hash_string("guid123")),
            combined_hash: String::new(),
        };

        // Different hostname and GUID, same MAC and disk
        let fp2 = HardwareFingerprint {
            mac_hashes: vec![hash_string("AA:BB:CC:DD:EE:FF")],
            disk_hashes: vec![hash_string("DISK123")],
            hostname_hash: Some(hash_string("otherhost")),
            machine_guid_hash: Some(hash_string("otherguid")),
            combined_hash: String::new(),
        };

        let result = fp1.match_score(&fp2);
        // MAC (2) + Disk (3) = 5 out of 10 = 50%
        // Whether this passes depends on the policy threshold chosen by caller
        assert!(!result.meets_threshold(70.0)); // Would fail default 70% threshold
        assert!(result.meets_threshold(50.0)); // Would pass permissive 50% threshold
    }

    #[test]
    fn state_hmac_roundtrip() {
        use tempfile::TempDir;

        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");
        let key = [7u8; 32];
        let state = LicenseState::new("lic-1");
        state.save(&path, &key).unwrap();
        let loaded = LicenseState::load(&path, "lic-1", &key).unwrap().unwrap();
        assert_eq!(loaded.license_id_hash, state.license_id_hash);
    }

    #[test]
    fn state_rejects_non_hmac_file() {
        use tempfile::TempDir;

        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");
        let key = [1u8; 32];
        std::fs::write(&path, "{}\nnot_hmac_prefix").unwrap();
        let err = LicenseState::load(&path, "lic-2", &key).unwrap_err();
        assert!(matches!(err, LicenseError::Validation(_)));
    }
}