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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use openssl;
use openssl::x509::X509;
use std::io::Cursor;
use xml::attribute::OwnedAttribute;
use xml::reader::{EventReader, XmlEvent};
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
pub enum NameIdFormat {
EmailAddress,
Entity,
Kerberos,
Persistent,
Transient,
Unspecified,
WindowsDomainQualifiedName,
X509SubjectName,
}
impl Default for NameIdFormat {
fn default() -> NameIdFormat {
NameIdFormat::Unspecified
}
}
impl ToString for NameIdFormat {
fn to_string(&self) -> String {
match self {
NameIdFormat::EmailAddress => {
"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress".to_string()
}
NameIdFormat::Entity => "urn:oasis:names:tc:SAML:2.0:nameid-format:entity".to_string(),
NameIdFormat::Kerberos => {
" urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos".to_string()
}
NameIdFormat::Persistent => {
"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent".to_string()
}
NameIdFormat::Transient => {
"urn:oasis:names:tc:SAML:2.0:nameid-format:transient".to_string()
}
NameIdFormat::Unspecified => {
"urn:oasis:names:tc:SAML:1.0:nameid-format:unspecified".to_string()
}
NameIdFormat::WindowsDomainQualifiedName => {
"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName".to_string()
}
NameIdFormat::X509SubjectName => {
"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName".to_string()
}
}
}
}
impl FromStr for NameIdFormat {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" => {
Ok(NameIdFormat::EmailAddress)
}
"urn:oasis:names:tc:SAML:2.0:nameid-format:entity" => Ok(NameIdFormat::Entity),
"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" => Ok(NameIdFormat::Persistent),
"urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos" => Ok(NameIdFormat::Kerberos),
"urn:oasis:names:tc:SAML:2.0:nameid-format:transient" => Ok(NameIdFormat::Transient),
"urn:oasis:names:tc:SAML:1.0:nameid-format:unspecified" => {
Ok(NameIdFormat::Unspecified)
}
"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName" => {
Ok(NameIdFormat::X509SubjectName)
}
"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName" => {
Ok(NameIdFormat::WindowsDomainQualifiedName)
}
_ => Err("Must be a valid type"),
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
pub enum SamlBindingType {
AssertionConsumerService,
SingleLogoutService,
}
impl ToString for SamlBindingType {
fn to_string(&self) -> String {
match self {
SamlBindingType::AssertionConsumerService => "AssertionConsumerService".to_string(),
SamlBindingType::SingleLogoutService => "SingleLogoutService".to_string(),
}
}
}
impl FromStr for SamlBindingType {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"AssertionConsumerService" => Ok(SamlBindingType::AssertionConsumerService),
"SingleLogoutService" => Ok(SamlBindingType::SingleLogoutService),
_ => Err("Must be a valid type"),
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
pub enum SamlBinding {
HttpPost,
HttpRedirect,
}
impl Default for SamlBinding {
fn default() -> Self {
SamlBinding::HttpPost
}
}
impl ToString for SamlBinding {
fn to_string(&self) -> String {
match self {
SamlBinding::HttpPost => "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST".to_string(),
SamlBinding::HttpRedirect => {
"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-REDIRECT".to_string()
}
}
}
}
impl FromStr for SamlBinding {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" => Ok(SamlBinding::HttpPost),
"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-REDIRECT" => Ok(SamlBinding::HttpRedirect),
_ => Err("Must be a valid type"),
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ServiceBinding {
pub servicetype: SamlBindingType,
#[serde(rename = "Binding")]
pub binding: SamlBinding,
#[serde(rename = "Location")]
pub location: String,
#[serde(rename = "Index")]
pub index: u8,
}
impl ServiceBinding {
pub fn default() -> Self {
ServiceBinding {
servicetype: SamlBindingType::AssertionConsumerService,
binding: SamlBinding::default(),
location: "http://0.0.0.0:0/SAML/acs".to_string(),
index: 0,
}
}
pub fn set_binding(self, binding: String) -> Result<Self, String> {
match SamlBinding::from_str(&binding) {
Err(_) => Err("Failed to match binding name".to_string()),
Ok(saml_binding) => Ok(ServiceBinding {
servicetype: self.servicetype,
binding: saml_binding,
location: self.location,
index: self.index,
}),
}
}
}
fn xml_indent(size: usize) -> String {
const INDENT: &str = " ";
(0..size)
.map(|_| INDENT)
.fold(String::with_capacity(size * INDENT.len()), |r, s| r + s)
}
#[derive(Debug, Clone)]
pub struct ServiceProvider {
pub entity_id: String,
pub authn_requests_signed: bool,
pub want_assertions_signed: bool,
pub x509_certificate: Option<X509>,
pub services: Vec<ServiceBinding>,
pub protocol_support_enumeration: Option<String>,
pub nameid_format: NameIdFormat,
}
impl FromStr for ServiceProvider {
type Err = &'static str;
fn from_str(source_xml: &str) -> Result<Self, Self::Err> {
let bufreader = Cursor::new(source_xml);
let parser = EventReader::new(bufreader);
let mut depth = 0;
let mut tag_name = "###INVALID###".to_string();
let mut certificate_data = None::<X509>;
let mut meta = ServiceProvider {
entity_id: "".to_string(),
authn_requests_signed: false,
want_assertions_signed: false,
x509_certificate: None,
services: vec![],
protocol_support_enumeration: None,
nameid_format: NameIdFormat::default(),
};
let upstream_tag = "";
for e in parser {
match e {
Ok(XmlEvent::StartElement {
name, attributes, ..
}) => {
tag_name = name.local_name.to_string();
meta.attrib_parser(&tag_name, attributes, &upstream_tag);
depth += 1;
}
Ok(XmlEvent::EndElement { .. }) => {
depth -= 1;
}
Ok(XmlEvent::Characters(s)) => {
match tag_name.as_str() {
"NameIDFormat" => {
debug!("Found NameIDFormat!");
match NameIdFormat::from_str(&s) {
Err(error) => eprintln!("Failed to parse NameIDFormat: {} {:?}", s, error),
Ok(value) => meta.nameid_format = value
}
}
"X509Certificate" => {
debug!("Found certificate!");
let certificate = crate::cert::init_cert_from_base64(&s);
match certificate {
Ok(value) => {
log::debug!("Parsed cert successfully.");
certificate_data = Some(value);
}
Err(error) => {
eprintln!("error! {:?}", error)
}
};
tag_name = "###INVALID###".to_string();
}
_ => {
println!("Characters: {}{}", xml_indent(depth + 1), s);
}
}
}
Err(e) => {
eprintln!("Failed to parse token: {:?}", e);
}
_ => {}
}
}
match certificate_data {
Some(value) => {
meta.x509_certificate = Some(value);
}
None => {
eprintln!("Didn't find a certificate");
}
}
Ok(meta)
}
}
impl ServiceProvider {
pub fn test_generic(entity_id: &str) -> Self {
ServiceProvider {
entity_id: entity_id.to_string(),
authn_requests_signed: false,
want_assertions_signed: false,
x509_certificate: None,
services: Vec::new(),
protocol_support_enumeration: None,
nameid_format: NameIdFormat::Transient,
}
}
fn service_attrib_parser(
&mut self,
servicetype: SamlBindingType,
attributes: Vec<OwnedAttribute>,
) -> Result<ServiceBinding, String> {
let mut tmp_sb = ServiceBinding {
servicetype,
binding: SamlBinding::HttpPost,
location: "".to_string(),
index: 0,
};
for attribute in attributes {
match attribute.name.local_name.to_lowercase().as_str() {
"binding" => {
log::debug!("Found Binding");
let binding = match SamlBinding::from_str(&attribute.value) {
Ok(value) => value,
Err(error) => {
return Err(format!(
"UNMATCHED BINDING: {}: {}",
&attribute.value, error
))
}
};
tmp_sb.binding = binding;
}
"location" => {
log::debug!("Found Location");
tmp_sb.location = attribute.value;
}
"index" => {
log::debug!("Found index");
tmp_sb.index = attribute.value.parse::<u8>().unwrap();
}
_ => {
eprintln!(
"Found unhandled attribute in AssertionConsumerService: {:?}",
attribute
);
}
}
}
log::debug!("Returning {:?}", tmp_sb);
Ok(tmp_sb)
}
pub fn find_first_acs(&self) -> Result<ServiceBinding, &'static str> {
if !self.services.is_empty() {
for service in &self.services {
if let SamlBindingType::AssertionConsumerService = service.servicetype {
return Ok(service.to_owned());
};
}
}
Err("Couldn't find ACS")
}
fn attrib_parser(&mut self, tag: &str, attributes: Vec<OwnedAttribute>, upstream_tag: &str) {
eprintln!("attrib_parser - tag={}, attr:{:?}", tag, attributes);
eprintln!("Current upstream tag: {}", upstream_tag);
match tag {
"AssertionConsumerService" => {
log::debug!("AssertionConsumerService: {:?}", attributes);
match self
.service_attrib_parser(SamlBindingType::AssertionConsumerService, attributes)
{
Ok(value) => {
let mut a = vec![value];
self.services.append(&mut a);
}
Err(error) => {
eprintln!("Failed to parse AssertionConsumerService: {:?}", error)
}
}
}
"EntityDescriptor" => {
for attribute in attributes {
log::debug!("attribute: {}", attribute);
match attribute.name.local_name.as_str() {
"entityID" => {
log::debug!("Setting entityID: {}", attribute.value);
self.entity_id = attribute.value;
}
"ID" => {
log::debug!("Setting entityID: {}", attribute.value);
self.entity_id = attribute.value;
}
_ => {
eprintln!(
"found an EntityDescriptor attribute that's not entityID: {:?}",
attribute
);
}
}
}
}
"SingleLogoutService" => {
log::debug!("SingleLogoutService: {:?}", attributes);
match self.service_attrib_parser(SamlBindingType::SingleLogoutService, attributes) {
Ok(value) => {
let mut a = vec![value];
self.services.append(&mut a);
}
Err(error) => eprintln!("Failed to parse SingleLogoutService: {:?}", error),
}
}
"SPSSODescriptor" => {
log::debug!("Dumping SPSSODescriptor: {:?}", attributes);
for attribute in attributes {
match attribute.name.local_name.to_lowercase().as_str() {
"authnrequestssigned" => {
match attribute.value.to_lowercase().as_str() {
"true" => self.authn_requests_signed = true,
"false" => self.authn_requests_signed = false,
_ => eprintln!(
"Couldn't parse value of AuthnRequestsSigned: {}",
attribute.value.to_lowercase()
),
}
}
"wantassertionssigned" => {
match attribute.value.to_lowercase().as_str() {
"true" => self.want_assertions_signed = true,
"false" => self.want_assertions_signed = false,
_ => eprintln!(
"Couldn't parse value of WantAssertionsSigned: {}",
attribute.value.to_lowercase()
),
}
}
"protocolsupportenumeration" => {
self.protocol_support_enumeration = Some(attribute.value.to_string())
}
_ => eprintln!("SPSSODescriptor attribute not handled {:?}", attribute), }
}
}
"RequestInitiator" => log::warn!("RequestInitiator is yet to be implemented, skipping"),
"SigningMethod" => log::warn!("SigningMethod is yet to be implemented, skipping"),
"DigestMethod" => log::warn!("DigestMethod is yet to be implemented, skipping"),
"NameIDFormat" => log::debug!("Don't need to parse attributes for NameIDFormat"),
"KeyDescriptor" => log::debug!("Don't need to parse attributes for KeyDescriptor"),
"KeyInfo" => log::debug!("Don't need to parse attributes for KeyInfo"),
"X509Certificate" => log::debug!("Don't need to parse attributes for X509Certificate"),
"X509Data" => log::debug!("Don't need to parse attributes for X509Data"),
"Logo" => log::debug!("Don't need to parse attributes for Logo"),
"Description" => log::debug!("Don't need to parse attributes for Description"),
_ => eprintln!(
"!!! Asked to parse attributes for tag={}, not caught by anything {:?}",
tag, attributes
),
}
}
}