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
use chrono::prelude::*;
use chrono::{DateTime, Utc};
use ed25519_dalek::{
    Keypair, PublicKey, SecretKey, Signature, Signer, Verifier, PUBLIC_KEY_LENGTH,
    SECRET_KEY_LENGTH,
};
use failure::Error;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::fs::File;
use std::io::prelude::*;

/// Getting the private key from file.
fn get_private_key() -> [u8; SECRET_KEY_LENGTH] {
    let mut file = File::open("./df_st_updater/df_st_updater_ed25519.private").unwrap();
    // read the same file back into a Vec of bytes
    let mut buffer = Vec::<u8>::new();
    file.read_to_end(&mut buffer).unwrap();

    let mut private_key_array: [u8; SECRET_KEY_LENGTH] = [0; SECRET_KEY_LENGTH];
    private_key_array.copy_from_slice(&buffer);
    private_key_array
}

/// Get the version verification sample.
fn get_version_verification() -> String {
    let mut file = File::open("./df_st_updater/verifier_sample.json").unwrap();
    let mut contents = String::new();
    file.read_to_string(&mut contents).unwrap();
    contents
}

/// Get a list of sources to get updates status from.
fn get_source_list(version: &str) -> Vec<String> {
    vec![
        format!(
            "https://dfstoryteller.com/versions/{}/verifier.json",
            version
        ),
        // TODO Add GitLab and/or other sources
    ]
}

/// Version verification message.
/// These message are stored on servers with a message and a signature.
#[derive(Serialize, Deserialize, Debug, Default)]
struct VersionVerification {
    /// The message a `VerificationToken` message as json encoded as base64
    /// This message is NOT encrypted. It is just base64 encoded to store json in
    /// another json message.
    message: String,
    /// A signature signed with private key stored by the developers.
    /// This signature proofs that the message is not changed and comes from the developer,
    /// not a man in the middle.
    /// This is signed with a `ed25519` key pair.
    signature: String,
}

/// A verification token. This object is stored in the `VersionVerification.message` field.
#[derive(Serialize, Deserialize, Debug)]
struct VerificationToken {
    /// The version of the current token
    /// This is check to prevent tampering.
    /// This prevent some kind of replay attack.
    version: String,
    /// The status of this version.
    /// This can be: "latest", "update_available" or "update_required"
    status: String,
    /// An optional message to alert the user of something.
    message: Option<String>,
    /// A RFC3339 timestamp until when this token is valid.
    /// This is checked with the local time to prevent tokens to be used forever.
    /// Tokens will usually expire in ~6 months.
    valid_until: DateTime<Utc>,
}

/// A list of status returned when checking for updates.
#[derive(Debug, PartialEq)]
pub enum VersionStatus {
    /// This is the latest version.
    Latest,
    /// There is an update available.
    UpdateAvailable,
    /// There is an update available and the version is marked as unsafe
    /// This is probably because a security vulnerability is found.
    UpdateRequired,
    /// The application things that someone is tampering with the tokens,
    /// the connection or the source.
    TamperProof,
    /// The application could not check for updates because of some reason.
    /// This might be because the pc does not have an internet connection.
    CouldNotCheck,
    /// This is a catch all for then something happens that is not supposed to happen.
    Unknown,
}

/// Download a token from one of the provided sources.
/// It will check if there is an update available and if this version is not marked as unsafe.
pub async fn check_version() -> Result<VersionStatus, Error> {
    let df_st_version = env!("CARGO_PKG_VERSION");
    let source_list = get_source_list(df_st_version);
    let mut version_status = VersionStatus::Unknown;

    // All errors in this loop should handled so to not prevent the application
    // from starting unnecessarily. It should be decided what error will do what.
    for source in source_list {
        // TODO maybe decrease timeout of request so it quickly opens the application.
        let response = match reqwest::blocking::get(&source) {
            Ok(rep) => rep,
            Err(_) => {
                warn!(
                    "Could not request version validator. Please check your internet connection.\n\
                    If you have an internet connection please update DF Storyteller."
                );
                version_status = VersionStatus::CouldNotCheck;
                continue;
            }
        };
        // Check if request succeeded
        if response.status() == 200 {
            let response_headers = response.headers().clone();
            let version_verification: VersionVerification = response.json().unwrap_or_else(|_| {
                warn!(
                    "The requested version verification could not be parsed. This file is invalid."
                );
                VersionVerification::default()
            });
            // If message is empty, go to next source
            if version_verification.message.is_empty() {
                version_status = VersionStatus::TamperProof;
                continue;
            }

            let signature = base64::decode(version_verification.signature).unwrap_or_else(|_| {
                warn!("Signature is not a valid base64 string.");
                vec![]
            });
            let message = base64::decode(version_verification.message).unwrap_or_else(|_| {
                warn!("Message is not a valid base64 string.");
                vec![]
            });
            // Check if signature matches for message
            match validate_message_signature(&signature, &message) {
                Ok(result) => {
                    if !result {
                        warn!("Signature does not match!");
                        version_status = VersionStatus::TamperProof;
                        continue;
                    }
                }
                Err(_err) => {
                    warn!("Signature does not match!");
                    version_status = VersionStatus::TamperProof;
                    continue;
                }
            }

            let message_string = String::from_utf8(message).unwrap_or_else(|_| {
                warn!("Message contains non-utf-8 characters.");
                "".to_owned()
            });
            // If decoded message is empty, go to next source
            if message_string.is_empty() {
                version_status = VersionStatus::TamperProof;
                continue;
            }
            let now: DateTime<Utc> = Utc::now();
            // Convert the message.
            // If it can not be parsed it will use the default,
            // and return `VersionStatus::TamperProof` in the next check.
            let token: VerificationToken =
                serde_json::from_str(&message_string).unwrap_or_else(|_| {
                    warn!("The requested version token could not be parsed. This file is invalid.");
                    VerificationToken {
                        version: "".to_owned(),
                        status: "".to_owned(),
                        message: None,
                        valid_until: Utc::now(),
                    }
                });
            // If version is empty, go to next source
            if token.version.is_empty() {
                version_status = VersionStatus::TamperProof;
                continue;
            }
            // Check if correct version
            if df_st_version != token.version {
                warn!(
                    "Version in token is not the same as current version.\n\
                    This is a bug and should be reported.\n\
                    The application will continue checking with outer sources."
                );
                //TODO Create GitLab issue template for this.
                version_status = VersionStatus::TamperProof;
                continue;
            }
            // Compare `valid_until` with system time
            if now >= token.valid_until {
                error!(
                    "This update token is expired.\n\
                    This is might be a bug and should be reported.\n\
                    The application will continue checking with outer sources."
                );
                version_status = VersionStatus::UpdateRequired;
                continue;
            }
            // Compare `valid_until` with response `Date` header.
            // If header is not set, do not check
            if let Some(response_time) = response_headers.get(reqwest::header::DATE) {
                // Convert to Chrono datetime
                let date_string = response_time.to_str().unwrap_or("");
                let date = Utc
                    .datetime_from_str(date_string, "%a, %d %b %Y %H:%M:%S GMT")
                    .unwrap_or(now);
                if date >= token.valid_until {
                    error!(
                        "This update token is expired.\n\
                        This is might be a bug and should be reported.\n\
                        The application will continue checking with outer sources."
                    );
                    version_status = VersionStatus::TamperProof;
                    continue;
                }
            }

            version_status = match token.status.as_ref() {
                "latest" => VersionStatus::Latest,
                "update_available" => VersionStatus::UpdateAvailable,
                "update_required" => VersionStatus::UpdateRequired,
                _ => {
                    warn!(
                        "Unknown status found in version token.\n\
                        This is a bug and should be reported."
                    );
                    //TODO Create GitLab issue template for this.
                    continue;
                }
            };
            if let Some(message) = token.message {
                info!("Message from Version Updater: {}", message);
            }
            break;
        } else {
            // Change only if not set as tampered
            if version_status != VersionStatus::TamperProof {
                version_status = VersionStatus::CouldNotCheck;
            }
        }
    }
    Ok(version_status)
}

/// Create a new token using the `verifier_sample.json`
/// This is used when tokens are updated or when a new version is released.
pub fn create_signed_message() {
    let keypair: Keypair = Keypair {
        secret: SecretKey::from_bytes(&get_private_key()).unwrap(),
        public: PublicKey::from_bytes(&get_public_key()).unwrap(),
    };

    let message: Vec<u8> = get_version_verification().into_bytes();
    let signature: Signature = keypair.sign(&message);
    let signature_bytes: Vec<u8> = signature.to_bytes().to_vec();

    assert!(keypair.verify(&message, &signature).is_ok());

    let version_verification = VersionVerification {
        message: base64::encode(message),
        signature: base64::encode(signature_bytes),
    };

    let json_string: String = serde_json::to_string_pretty(&version_verification).unwrap();

    let df_st_version = env!("CARGO_PKG_VERSION");
    let mut file = File::create(format!(
        "./df_st_updater/verifiers/verifier_{}.json",
        df_st_version
    ))
    .unwrap();
    file.write_all(&json_string.into_bytes()).unwrap();
    info!(
        "New verifier created: `./df_st_updater/verifiers/verifier_{}.json`",
        df_st_version
    );
}

/// Create a new pair of keys used for signing messages.
pub fn create_keypair() {
    use rand::rngs::OsRng;

    let mut csprng = OsRng {};
    let keypair: Keypair = Keypair::generate(&mut csprng);

    let mut file = File::create("./df_st_updater/df_st_updater_ed25519.pub").unwrap();
    file.write_all(&keypair.public.to_bytes()).unwrap();

    let mut file = File::create("./df_st_updater/df_st_updater_ed25519.private").unwrap();
    file.write_all(&keypair.secret.to_bytes()).unwrap();

    println!("Public key: {:?}", keypair.public.to_bytes());
}

/// Check if the signature matches for the provided message
fn validate_message_signature(signature: &[u8], message: &[u8]) -> Result<bool, Error> {
    let public_key: PublicKey = PublicKey::from_bytes(&get_public_key())?;
    let signature_obj: Signature = Signature::try_from(signature)?;

    let result = public_key.verify(message, &signature_obj).is_ok();
    Ok(result)
}

/// Get the included public key
/// This key is embedded in the source and used to verify tokens.
fn get_public_key() -> [u8; PUBLIC_KEY_LENGTH] {
    // The key below is created on 2020/06/12 by Ralph Bisschops
    // This key should not be updated unless a new main developer is assigned.
    let public_key_array: [u8; PUBLIC_KEY_LENGTH] = [
        244, 240, 178, 56, 163, 188, 54, 168, 77, 103, 81, 226, 166, 148, 92, 248, 214, 62, 184,
        202, 200, 48, 86, 1, 241, 212, 8, 134, 74, 138, 134, 185,
    ];

    public_key_array
}