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
use std;
use std::marker::Send;
use std::fmt::{Debug, Formatter};
use std::result::Result;
use openssl::{x509, nid::Nid};
use chrono::{DateTime, Utc, TimeZone};
use opcua_types::ByteString;
use opcua_types::service_types::ApplicationDescription;
use opcua_types::status_code::StatusCode;
use crate::crypto::pkey::PublicKey;
use crate::crypto::thumbprint::Thumbprint;
const DEFAULT_KEYSIZE: u32 = 2048;
const DEFAULT_COUNTRY: &str = "IE";
const DEFAULT_STATE: &str = "Dublin";
#[derive(Debug)]
pub struct X509Data {
pub key_size: u32,
pub common_name: String,
pub organization: String,
pub organizational_unit: String,
pub country: String,
pub state: String,
pub alt_host_names: Vec<String>,
pub certificate_duration_days: u32,
}
impl From<ApplicationDescription> for X509Data {
fn from(application_description: ApplicationDescription) -> Self {
let alt_host_names = Self::alt_host_names(application_description.application_uri.as_ref(), false, true);
X509Data {
key_size: DEFAULT_KEYSIZE,
common_name: application_description.application_name.to_string(),
organization: application_description.application_name.to_string(),
organizational_unit: application_description.application_name.to_string(),
country: DEFAULT_COUNTRY.to_string(),
state: DEFAULT_STATE.to_string(),
alt_host_names,
certificate_duration_days: 365,
}
}
}
impl X509Data {
pub fn computer_hostnames() -> Vec<String> {
let mut result = Vec::with_capacity(2);
if let Ok(machine_name) = std::env::var("COMPUTERNAME") {
result.push(machine_name);
}
if let Ok(machine_name) = std::env::var("NAME") {
result.push(machine_name);
}
result
}
pub fn alt_host_names(application_uri: &str, add_localhost: bool, add_computer_name: bool) -> Vec<String> {
let mut result = vec![application_uri.to_string()];
if add_localhost {
result.push("localhost".to_string());
result.push("127.0.0.1".to_string());
result.push("::1".to_string());
}
if add_computer_name {
let mut computer_hostnames = Self::computer_hostnames();
computer_hostnames.drain(..).for_each(|h| result.push(h));
}
result
}
pub fn sample_cert() -> X509Data {
let alt_host_names = Self::alt_host_names("urn:OPCUADemo", true, true);
X509Data {
key_size: 2048,
common_name: "OPC UA Demo Key".to_string(),
organization: "OPC UA for Rust".to_string(),
organizational_unit: "OPC UA for Rust".to_string(),
country: DEFAULT_COUNTRY.to_string(),
state: DEFAULT_STATE.to_string(),
alt_host_names,
certificate_duration_days: 365,
}
}
}
#[derive(Clone)]
pub struct X509 {
value: x509::X509,
}
impl Debug for X509 {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "[x509]")
}
}
unsafe impl Send for X509 {}
unsafe impl std::marker::Sync for X509 {}
impl X509 {
pub fn wrap(value: x509::X509) -> X509 {
X509 { value }
}
pub fn from_der(der: &[u8]) -> Result<Self, ()> {
if let Ok(value) = x509::X509::from_der(der) {
Ok(X509 { value })
} else {
error!("Cannot produce an x509 cert from the data supplied");
Err(())
}
}
pub fn from_byte_string(data: &ByteString) -> Result<X509, StatusCode> {
if data.is_null() {
error!("Can't make certificate from null bytestring");
Err(StatusCode::BadCertificateInvalid)
} else if let Ok(cert) = x509::X509::from_der(&data.value.as_ref().unwrap()) {
Ok(X509::wrap(cert))
} else {
error!("Can't make certificate, does bytestring contain .der?");
Err(StatusCode::BadCertificateInvalid)
}
}
pub fn as_byte_string(&self) -> ByteString {
let der = self.value.to_der().unwrap();
ByteString::from(&der)
}
pub fn public_key(&self) -> Result<PublicKey, StatusCode> {
if let Ok(pkey) = self.value.public_key() {
let pkey = PublicKey::wrap_public_key(pkey);
Ok(pkey)
} else {
error!("Can't obtain public key from certificate");
Err(StatusCode::BadCertificateInvalid)
}
}
fn get_subject_entry(&self, nid: Nid) -> Result<String, ()> {
let subject_name = self.value.subject_name();
let mut entries = subject_name.entries_by_nid(nid);
if let Some(entry) = entries.next() {
if let Ok(value) = entry.data().as_utf8() {
use std::ops::Deref;
Ok(value.deref().to_string())
} else {
Err(())
}
} else {
Err(())
}
}
pub fn common_name(&self) -> Result<String, ()> {
self.get_subject_entry(Nid::COMMONNAME)
}
pub fn is_time_valid(&self, now: &DateTime<Utc>) -> StatusCode {
let not_before = self.not_before();
if let Ok(not_before) = not_before {
if now.lt(¬_before) {
error!("Certificate < before date)");
return StatusCode::BadCertificateTimeInvalid;
}
} else {
error!("Certificate has no before date");
return StatusCode::BadCertificateInvalid;
}
let not_after = self.not_after();
if let Ok(not_after) = not_after {
if now.gt(¬_after) {
error!("Certificate has expired (> after date)");
return StatusCode::BadCertificateTimeInvalid;
}
} else {
error!("Certificate has no after date");
return StatusCode::BadCertificateInvalid;
}
info!("Certificate is valid for this time");
StatusCode::Good
}
pub fn is_hostname_valid(&self, hostname: &str) -> StatusCode {
trace!("is_hostname_valid against {} on cert", hostname);
if let Some(ref alt_names) = self.value.subject_alt_names() {
let found = alt_names.iter().skip(1).find(|n| {
if let Some(dns) = n.dnsname() {
dns.eq_ignore_ascii_case(hostname)
} else {
false
}
});
if found.is_some() {
info!("Certificate host name {} is good", hostname);
StatusCode::Good
} else {
error!("Cannot find a matching hostname for input {}", hostname);
StatusCode::BadCertificateHostNameInvalid
}
} else {
error!("Cert has no subject alt names at all");
StatusCode::BadCertificateHostNameInvalid
}
}
pub fn is_application_uri_valid(&self, application_uri: &str) -> StatusCode {
trace!("is_application_uri_valid against {} on cert", application_uri);
if let Some(ref alt_names) = self.value.subject_alt_names() {
if alt_names.len() > 0 {
if let Some(cert_application_uri) = alt_names[0].uri() {
if cert_application_uri == application_uri {
info!("Certificate application uri {} is good", application_uri);
StatusCode::Good
} else {
error!("Cert application uri {} does not match supplied uri {}", cert_application_uri, application_uri);
StatusCode::BadCertificateUriInvalid
}
} else {
error!("Cert's first subject alt name is not a uri and cannot be compared");
StatusCode::BadCertificateUriInvalid
}
} else {
error!("Cert has zero subject alt names");
StatusCode::BadCertificateUriInvalid
}
} else {
error!("Cert has no subject alt names at all");
StatusCode::BadCertificateUriInvalid
}
}
pub fn thumbprint(&self) -> Thumbprint {
use openssl::hash::{MessageDigest, hash};
let der = self.value.to_der().unwrap();
let digest = hash(MessageDigest::sha1(), &der).unwrap();
Thumbprint::new(&digest)
}
pub fn not_before(&self) -> Result<DateTime<Utc>, ()> {
let date = self.value.not_before().to_string();
Self::parse_asn1_date(&date)
}
pub fn not_after(&self) -> Result<DateTime<Utc>, ()> {
let date = self.value.not_after().to_string();
Self::parse_asn1_date(&date)
}
pub fn to_der(&self) -> Result<Vec<u8>, ()> {
if let Ok(der) = self.value.to_der() {
Ok(der)
} else {
error!("Cannot turn X509 cert to DER");
Err(())
}
}
fn parse_asn1_date(date: &str) -> Result<DateTime<Utc>, ()> {
let date = if date.ends_with(" GMT") {
&date[..date.len() - 4]
} else {
&date
};
let result = Utc.datetime_from_str(date, "%b %d %H:%M:%S %Y");
if result.is_err() {
error!("Error = {:?}", result.unwrap_err());
Err(())
} else {
Ok(result.unwrap())
}
}
}
#[test]
fn parse_asn1_date_test() {
use chrono::{Datelike, Timelike};
assert!(X509::parse_asn1_date("").is_err());
assert!(X509::parse_asn1_date("Jan 69 00:00:00 1970").is_err());
assert!(X509::parse_asn1_date("Feb 21 00:00:00 1970").is_ok());
assert!(X509::parse_asn1_date("Feb 21 00:00:00 1970 GMT").is_ok());
let dt: DateTime<Utc> = X509::parse_asn1_date("Feb 21 12:45:30 1999 GMT").unwrap();
assert_eq!(dt.month(), 2);
assert_eq!(dt.day(), 21);
assert_eq!(dt.hour(), 12);
assert_eq!(dt.minute(), 45);
assert_eq!(dt.second(), 30);
assert_eq!(dt.year(), 1999);
}