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::*;
fn get_private_key() -> [u8; SECRET_KEY_LENGTH] {
let mut file = File::open("./df_st_updater/df_st_updater_ed25519.private").unwrap();
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
}
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
}
fn get_source_list(version: &str) -> Vec<String> {
vec![
format!(
"https://dfstoryteller.com/versions/{}/verifier.json",
version
),
]
}
#[derive(Serialize, Deserialize, Debug, Default)]
struct VersionVerification {
message: String,
signature: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct VerificationToken {
version: String,
status: String,
message: Option<String>,
valid_until: DateTime<Utc>,
}
#[derive(Debug, PartialEq)]
pub enum VersionStatus {
Latest,
UpdateAvailable,
UpdateRequired,
TamperProof,
CouldNotCheck,
Unknown,
}
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;
for source in source_list {
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;
}
};
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 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![]
});
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 message_string.is_empty() {
version_status = VersionStatus::TamperProof;
continue;
}
let now: DateTime<Utc> = Utc::now();
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 token.version.is_empty() {
version_status = VersionStatus::TamperProof;
continue;
}
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."
);
version_status = VersionStatus::TamperProof;
continue;
}
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;
}
if let Some(response_time) = response_headers.get(reqwest::header::DATE) {
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."
);
continue;
}
};
if let Some(message) = token.message {
info!("Message from Version Updater: {}", message);
}
break;
} else {
if version_status != VersionStatus::TamperProof {
version_status = VersionStatus::CouldNotCheck;
}
}
}
Ok(version_status)
}
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
);
}
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());
}
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)
}
fn get_public_key() -> [u8; PUBLIC_KEY_LENGTH] {
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
}