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
//! Get an encrypted unique MachineID/HWID/UUID. 
//! 
//! This crate is inspired by .Net DeviceId
//! 
//! You can add all the components you need without admin permissions.
//! 
//! ```
//! use machineid_rs::{IdBuilder, Encryption, HWIDComponent};
//! 
//! // There are 3 different encryption types: MD5, SHA1 and SHA256.
//! let mut builder = IdBuilder::new(Encryption::MD5);
//! 
//! builder.add_component(HWIDComponent::SystemID).add_component(HWIDComponent::CPUCores);
//! 
//! let hwid = builder.build("mykey").unwrap();

#![allow(non_snake_case)]

mod errors;
mod windows;
mod linux;
mod utils;

use errors::HWIDError;
#[cfg(target_os="linux")]
use linux::{get_hwid, get_mac_address, get_disk_id};
#[cfg(target_os="windows")]
use windows::{get_hwid, get_disk_id, get_mac_address};

use sysinfo::{SystemExt, System, ProcessorExt};
use crypto::{hmac::Hmac, mac::Mac, md5::Md5, sha1::Sha1, sha2::Sha256};
use utils::file_token;


/// The components that can be used to build the HWID.
#[derive(PartialEq, Eq, Hash)]
pub enum HWIDComponent{
    /// System UUID
    SystemID,
    /// Number of CPU Cores
    CPUCores,
    /// Name of the OS
    OSName,
    /// Current Username
    Username,
    /// Host machine name
    MachineName,
    /// Mac Address
    MacAddress,
    /// CPU Vendor ID
    CPUID,
    /// The contents of a file
    FileToken(&'static str),
    /// UUID of the root disk
    DriveSerial
}

impl HWIDComponent{
    fn to_string(&self) -> Result<String, HWIDError>{
        use HWIDComponent::*;
        return match self{
            SystemID => get_hwid(),
            CPUCores => {
                let sys = System::new_all();
                let cores = sys.physical_core_count().unwrap_or(2);
                Ok(cores.to_string())
            },
            OSName => {
                let sys = System::new_all();
                let name = sys
                .long_os_version()
                .ok_or(HWIDError::new("OSName", "Could not retrieve OS Name"))?;
                Ok(name)
            },
            Username => Ok(whoami::username()),
            MachineName => {
                let sys = System::new_all();
                let name = sys
                .host_name()
                .ok_or(HWIDError::new("HostName", "Could not retrieve Host Name"))?;
                Ok(name)
            },
            MacAddress => get_mac_address(),
            CPUID => {
                let sys = System::new_all();
                let processor = sys.global_processor_info();
                Ok(processor.vendor_id().to_string())
            },
            FileToken(filename) => file_token(filename),
            DriveSerial => get_disk_id()
        }
    }
}

/// The encryptions that can be used to build the HWID.
pub enum Encryption{
    MD5,
    SHA256,
    SHA1
}

impl Encryption{
    fn generate_hash(&self, key:&[u8], text:String) -> String{
        match self{
            Encryption::MD5 => {
                let mut mac = Hmac::new(Md5::new(), key);
                mac.input(text.as_bytes());
                let hash = mac.result();
                hex::encode(hash.code())
            },
            Encryption::SHA1 => {
                let mut mac = Hmac::new(Sha1::new(), key);
                mac.input(text.as_bytes());
                let hash = mac.result();
                hex::encode(hash.code())
            },
            Encryption::SHA256 => {
                let mut mac = Hmac::new(Sha256::new(), key);
                mac.input(text.as_bytes());
                let hash = mac.result();
                hex::encode(hash.code())
            }
        }
    }
}

/// `IdBuilder` is the constructor for the HWID. It can be used with the 3 different options of the `Encryption` enum.
pub struct IdBuilder{
    parts: Vec<HWIDComponent>,
    pub hash: Encryption,
}

impl IdBuilder{

    /// Joins every part together and returns a `Result` that may be the hashed HWID or a `HWIDError`.
    /// 
    /// # Errors
    /// 
    /// Returns [`Err`] if there is an error while retrieving the component's strings.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use machineid_rs::{IdBuilder, Encryption, HWIDComponent};
    /// 
    /// let mut builder = IdBuilder::new(Encryption::MD5);
    /// 
    /// builder.add_component(HWIDComponent::SystemID);
    /// 
    /// 
    /// // Will panic if there is an error when the components return his values.
    /// let key = builder.build("mykey").unwrap();
    /// ```
    pub fn build(&mut self, key:&str) -> Result<String, HWIDError>{
        if self.parts.len() == 0 {
            panic!("You must add at least one element to make a machine id");
        }
        let final_string = self.parts.iter().map(|p|p.to_string()).collect::<Result<String, HWIDError>>()?;
        Ok(self.hash.generate_hash(key.as_bytes(), final_string))
    }

    /// Adds a component to the `IdBuilder` that will be hashed once you call the [`IdBuilder::build`] function.
    /// 
    /// You can't add the same component twice.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use machineid_rs::{IdBuilder, Encryption, HWIDComponent};
    /// 
    /// let mut builder = IdBuilder::new(Encryption::MD5);
    /// 
    /// builder.add_component(HWIDComponent::SystemID);
    /// ```
    pub fn add_component(&mut self, component:HWIDComponent) -> &mut Self{
        if !self.parts.contains(&component){
            self.parts.push(component);
        }
        return self
    }

    /// Makes a new IdBuilder with the selected Encryption
    /// 
    /// # Examples
    /// 
    /// ```
    /// use machineid_rs::{IdBuilder, Encryption};
    /// 
    /// let mut builder = IdBuilder::new(Encryption::MD5);
    /// ```
    pub fn new(hash:Encryption) -> Self{
        IdBuilder{
            parts: vec![],
            hash,
        }
    }
}

#[cfg(test)]
mod test{
    use super::*;
    use std::env;
    #[test]
    fn every_option_sha256(){
        let mut builder = IdBuilder::new(Encryption::SHA256);
        builder
        .add_component(HWIDComponent::SystemID)
        .add_component(HWIDComponent::OSName)
        .add_component(HWIDComponent::CPUCores)
        .add_component(HWIDComponent::CPUID)
        .add_component(HWIDComponent::DriveSerial)
        .add_component(HWIDComponent::MacAddress)
        .add_component(HWIDComponent::FileToken("test.txt"))
        .add_component(HWIDComponent::Username)
        .add_component(HWIDComponent::MachineName);
        let hash = builder.build("mykey").unwrap();
        let expected = env::var("SHA256_MACHINEID_HASH").unwrap();
        assert_eq!(expected, hash);
    }

    #[test]
    fn every_option_sha1(){
        let mut builder = IdBuilder::new(Encryption::SHA1);
        builder
        .add_component(HWIDComponent::SystemID)
        .add_component(HWIDComponent::OSName)
        .add_component(HWIDComponent::CPUCores)
        .add_component(HWIDComponent::CPUID)
        .add_component(HWIDComponent::DriveSerial)
        .add_component(HWIDComponent::MacAddress)
        .add_component(HWIDComponent::FileToken("test.txt"))
        .add_component(HWIDComponent::Username)
        .add_component(HWIDComponent::MachineName);
        let hash = builder.build("mykey").unwrap();
        let expected = env::var("SHA1_MACHINEID_HASH").unwrap();
        assert_eq!(expected, hash);
    }

    #[test]
    fn every_option_md5(){
        let mut builder = IdBuilder::new(Encryption::MD5);
        builder
        .add_component(HWIDComponent::SystemID)
        .add_component(HWIDComponent::OSName)
        .add_component(HWIDComponent::CPUCores)
        .add_component(HWIDComponent::CPUID)
        .add_component(HWIDComponent::DriveSerial)
        .add_component(HWIDComponent::MacAddress)
        .add_component(HWIDComponent::FileToken("test.txt"))
        .add_component(HWIDComponent::Username)
        .add_component(HWIDComponent::MachineName);
        let hash = builder.build("mykey").unwrap();
        let expected = env::var("MD5_MACHINEID_HASH").unwrap();
        assert_eq!(expected, hash);
    }
}