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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use serde::Serialize;
use crate::utils::*;
use crate::xml::write_event;
use chrono::{DateTime, SecondsFormat, Utc};
use openssl::x509::X509;
use std::io::Write;
use std::str::from_utf8;
use xml::writer::{EmitterConfig, EventWriter, XmlEvent};
#[allow(dead_code)]
enum AssertionType {
Statement,
AuthnStatement,
AuthzDecisionStatement,
AttributeStatement,
}
#[allow(dead_code)]
enum StatusCode {
Success,
}
#[derive(Clone, Debug)]
pub struct Assertion {
pub assertion_id: String,
pub issuer: String,
pub signing_algorithm: crate::sign::SigningAlgorithm,
pub digest_algorithm: crate::sign::DigestAlgorithm,
pub issue_instant: DateTime<Utc>,
pub subject_data: SubjectData,
pub conditions_not_before: DateTime<Utc>,
pub conditions_not_after: DateTime<Utc>,
pub audience: String,
pub attributes: Vec<AssertionAttribute>,
pub sign_assertion: bool,
pub signing_key: Option<openssl::pkey::PKey<openssl::pkey::Private>>,
pub signing_cert: Option<X509>,
}
fn write_assertion_tmpdir(buffer: &[u8]) {
let mut assertionpath = std::env::temp_dir();
let mut assertionfilename: String = chrono::Utc::now().timestamp().to_string();
assertionfilename.push_str("-assertionout.xml");
assertionpath.set_file_name(assertionfilename);
log::debug!("Assertion filename: {:?}", &assertionpath);
let mut assertionfile = match std::fs::OpenOptions::new()
.create(true)
.write(true)
.open(assertionpath.into_os_string())
{
Ok(value) => value,
Err(e) => {
log::error!("Failed to open assertionout {:?}", e);
std::process::exit(1)
}
};
match assertionfile.write_all(&buffer) {
Ok(value) => log::debug!("{:?}", value),
Err(e) => log::error!("{:?}", e),
};
}
#[allow(clippy::from_over_into)]
impl Into<Vec<u8>> for Assertion {
fn into(self) -> Vec<u8> {
let mut buffer = Vec::new();
let mut writer = EmitterConfig::new()
.perform_indent(true)
.pad_self_closing(false)
.write_document_declaration(false)
.normalize_empty_elements(false)
.create_writer(&mut buffer);
self.add_assertion_to_xml(&mut writer);
log::debug!("Assertion into vec result:");
log::debug!("{}", from_utf8(&buffer).unwrap());
write_assertion_tmpdir(&buffer);
buffer
}
}
impl Assertion {
pub fn without_signature(self) -> Self {
Self {
assertion_id: self.assertion_id,
issuer: self.issuer,
signing_algorithm: self.signing_algorithm,
digest_algorithm: self.digest_algorithm,
issue_instant: self.issue_instant,
subject_data: self.subject_data,
conditions_not_before: self.conditions_not_before,
conditions_not_after: self.conditions_not_after,
audience: self.audience,
attributes: self.attributes,
sign_assertion: false,
signing_key: self.signing_key,
signing_cert: self.signing_cert,
}
}
pub fn build_assertion(&self, sign: bool) -> String {
if sign {
unimplemented!("Still need to refactor building the signed assertion")
} else {
unimplemented!("Still need to refactor building the assertion")
}
}
fn add_conditions<W: Write>(&self, writer: &mut EventWriter<W>) {
write_event(
XmlEvent::start_element(("saml", "Conditions"))
.attr("NotBefore", &self.conditions_not_before.to_rfc3339())
.attr("NotOnOrAfter", &self.conditions_not_after.to_rfc3339())
.into(),
writer,
);
write_event(
XmlEvent::start_element(("saml", "AudienceRestriction")).into(),
writer,
);
write_event(XmlEvent::start_element(("saml", "Audience")).into(), writer);
write_event(XmlEvent::characters(&self.audience), writer);
write_event(XmlEvent::end_element().into(), writer);
write_event(XmlEvent::end_element().into(), writer);
write_event(XmlEvent::end_element().into(), writer);
}
pub fn add_assertion_to_xml<W: Write>(&self, writer: &mut EventWriter<W>) {
log::debug!("sign_assertion: {}", self.sign_assertion);
write_event(
XmlEvent::start_element(("saml", "Assertion"))
.attr("xmlns:saml", "urn:oasis:names:tc:SAML:2.0:assertion")
.attr("ID", &self.assertion_id)
.attr(
"IssueInstant",
&self
.issue_instant
.to_rfc3339_opts(SecondsFormat::Secs, true),
)
.attr("Version", "2.0") .into(),
writer,
);
write_event(XmlEvent::start_element(("saml", "Issuer")).into(), writer);
write_event(XmlEvent::characters(&self.issuer), writer);
write_event(XmlEvent::end_element().into(), writer);
if self.sign_assertion {
log::debug!("Signing assertion");
if self.signing_key.is_none() {
panic!("You tried to sign an assertion without setting a signing key...");
}
let unsigned_assertion = self.clone().without_signature();
let xmldata: Vec<u8> = unsigned_assertion.into();
let digest_bytes = self.digest_algorithm.hash(&xmldata).unwrap();
let base64_encoded_digest = base64::encode(&digest_bytes);
let mut signedinfo_buffer = Vec::new();
let mut signedinfo_writer = EmitterConfig::new()
.perform_indent(true)
.write_document_declaration(false)
.normalize_empty_elements(true)
.pad_self_closing(false)
.create_writer(&mut signedinfo_buffer);
crate::xml::generate_signedinfo(self, &base64_encoded_digest, &mut signedinfo_writer);
log::debug!("SignedInfo Element:");
log::debug!("{}", from_utf8(&signedinfo_buffer).unwrap());
let hashed_signedinfo = base64::encode(signedinfo_buffer);
log::debug!("Hashed Signedinfo: {}", hashed_signedinfo);
let key = self.signing_key.as_ref().unwrap();
let signed_result =
crate::sign::sign_data(self.signing_algorithm, key, &hashed_signedinfo.as_bytes());
log::debug!("Signature result: {:?}", &signed_result);
let base64_encoded_signature = base64::encode(&signed_result);
log::debug!(
"Base64 encoded signature result: {:?}",
&base64_encoded_signature
);
crate::xml::add_assertion_signature(
self,
base64_encoded_digest,
base64_encoded_signature,
writer,
);
} else {
write_event(XmlEvent::characters("\n \n "), writer);
log::warn!("Unsigned assertion was built, this seems bad!");
}
add_subject(&self.subject_data, writer);
self.add_conditions(writer);
write_event(
XmlEvent::start_element(("saml", "AttributeStatement")).into(),
writer,
);
for attribute in &self.attributes.to_vec() {
add_attribute(attribute, writer);
}
write_event(XmlEvent::end_element().into(), writer);
write_event(XmlEvent::end_element().into(), writer);
}
}
#[derive(Debug, Copy, Clone)]
pub enum BaseIDAbstractType {
NameQualifier,
SPNameQualifier,
}
impl From<String> for BaseIDAbstractType {
fn from(name: String) -> Self {
let name = name.as_str();
match name {
"NameQualifier" => BaseIDAbstractType::NameQualifier,
"SPNameQualifier" => BaseIDAbstractType::SPNameQualifier,
_ => panic!("how did you even get here"),
}
}
}
impl ToString for BaseIDAbstractType {
fn to_string(&self) -> String {
match self {
BaseIDAbstractType::NameQualifier => String::from("NameQualifier"),
BaseIDAbstractType::SPNameQualifier => String::from("SPNameQualifier"),
}
}
}
#[derive(Clone, Debug)]
pub struct SubjectData {
pub relay_state: String,
pub qualifier: Option<BaseIDAbstractType>,
pub qualifier_value: Option<String>,
pub nameid_format: crate::sp::NameIdFormat,
pub nameid_value: &'static str,
pub acs: String,
pub subject_not_on_or_after: DateTime<Utc>,
}
fn add_subject<W: Write>(subjectdata: &SubjectData, writer: &mut EventWriter<W>) {
write_event(XmlEvent::start_element(("saml", "Subject")).into(), writer);
write_event(
XmlEvent::start_element(("saml", "NameID"))
.attr("Format", &subjectdata.nameid_format.to_string())
.attr(
subjectdata.qualifier.unwrap().to_string().as_str(),
subjectdata.qualifier_value.as_ref().unwrap(),
)
.into(),
writer,
);
write_event(XmlEvent::characters(&subjectdata.nameid_value), writer);
write_event(XmlEvent::end_element().into(), writer);
write_event(
XmlEvent::start_element(("saml", "SubjectConfirmation"))
.attr("Method", "urn:oasis:names:tc:SAML:2.0:cm:bearer")
.into(),
writer,
);
write_event(
XmlEvent::start_element(("saml", "SubjectConfirmationData"))
.attr("InResponseTo", &subjectdata.relay_state)
.attr(
"NotOnOrAfter",
&subjectdata
.subject_not_on_or_after
.to_saml_datetime_string(),
)
.attr("Recipient", &subjectdata.acs)
.into(),
writer,
);
write_event(XmlEvent::end_element().into(), writer);
write_event(XmlEvent::end_element().into(), writer);
write_event(XmlEvent::end_element().into(), writer);
}
#[derive(Debug, Default, Serialize, Clone)]
pub struct AssertionAttribute {
name: String,
nameformat: String,
values: Vec<&'static str>,
}
impl AssertionAttribute {
pub fn basic(name: &str, values: Vec<&'static str>) -> AssertionAttribute {
AssertionAttribute {
name: name.to_string(),
nameformat: "urn:oasis:names:tc:SAML:2.0:attrname-format:basic".to_string(),
values,
}
}
}
pub fn add_attribute<W: Write>(attr: &AssertionAttribute, writer: &mut EventWriter<W>) {
write_event(
XmlEvent::start_element(("saml", "Attribute"))
.attr("Name", attr.name.as_str())
.attr("NameFormat", attr.nameformat.as_str())
.into(),
writer,
);
for value in &attr.values {
write_event(
XmlEvent::start_element(("saml", "AttributeValue"))
.attr("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") .attr("xsi:type", "xs:string")
.into(),
writer,
);
write_event(XmlEvent::characters(value), writer);
write_event(XmlEvent::end_element().into(), writer);
}
write_event(XmlEvent::end_element().into(), writer);
}