1use crate::errors::{AuthError, Result};
7use crate::protocols::saml_assertions::SamlAssertion;
8use base64::{Engine as _, engine::general_purpose::STANDARD};
9use chrono::{DateTime, Duration, Utc};
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12
13fn xml_escape(s: &str) -> String {
15 let mut out = String::with_capacity(s.len());
16 for c in s.chars() {
17 match c {
18 '&' => out.push_str("&"),
19 '<' => out.push_str("<"),
20 '>' => out.push_str(">"),
21 '"' => out.push_str("""),
22 '\'' => out.push_str("'"),
23 _ => out.push(c),
24 }
25 }
26 out
27}
28
29#[derive(Debug, Clone, Default)]
31pub struct WsSecurityHeader {
32 pub username_token: Option<UsernameToken>,
34
35 pub timestamp: Option<Timestamp>,
37
38 pub binary_security_token: Option<BinarySecurityToken>,
40
41 pub saml_assertions: Vec<SamlAssertionRef>,
43
44 pub signature: Option<WsSecuritySignature>,
46
47 pub custom_elements: Vec<String>,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct UsernameToken {
54 pub username: String,
56
57 pub password: Option<UsernamePassword>,
59
60 pub nonce: Option<String>,
62
63 pub created: Option<DateTime<Utc>>,
65
66 pub wsu_id: Option<String>,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
72pub struct UsernamePassword {
73 pub value: String,
75
76 pub password_type: PasswordType,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub enum PasswordType {
83 PasswordText,
85
86 PasswordDigest,
88}
89
90#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct Timestamp {
93 pub created: DateTime<Utc>,
95
96 pub expires: DateTime<Utc>,
98
99 pub wsu_id: Option<String>,
101}
102
103#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct BinarySecurityToken {
106 pub value: String,
108
109 pub value_type: String,
111
112 pub encoding_type: String,
114
115 pub wsu_id: Option<String>,
117}
118
119#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct SamlAssertionRef {
122 pub assertion: SamlAssertion,
124
125 pub wsu_id: Option<String>,
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
131pub struct WsSecuritySignature {
132 pub signature_method: String,
134
135 pub canonicalization_method: String,
137
138 pub digest_method: String,
140
141 pub references: Vec<SignatureReference>,
143
144 pub key_info: Option<KeyInfo>,
146
147 pub signature_value: Option<String>,
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct SignatureReference {
154 pub uri: String,
156
157 pub digest_value: String,
159
160 pub transforms: Vec<String>,
162}
163
164#[derive(Debug, Clone, Serialize, Deserialize)]
166pub struct KeyInfo {
167 pub security_token_reference: Option<String>,
169
170 pub key_value: Option<String>,
172
173 pub x509_data: Option<String>,
175}
176
177#[derive(Clone)]
179pub struct WsSecurityConfig {
180 pub include_timestamp: bool,
182
183 pub timestamp_ttl: Duration,
185
186 pub sign_message: bool,
188
189 pub elements_to_sign: Vec<String>,
191
192 pub signing_certificate: Option<Vec<u8>>,
194
195 pub signing_private_key: Option<Vec<u8>>,
197
198 pub include_certificate: bool,
200
201 pub saml_token_endpoint: Option<String>,
203
204 pub actor: Option<String>,
206}
207
208impl std::fmt::Debug for WsSecurityConfig {
209 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210 let mut d = f.debug_struct("WsSecurityConfig");
211 d.field("include_timestamp", &self.include_timestamp);
212 d.field("timestamp_ttl", &self.timestamp_ttl);
213 d.field("sign_message", &self.sign_message);
214 d.field("elements_to_sign", &self.elements_to_sign);
215 d.field("signing_certificate", &self.signing_certificate);
216 d.field(
217 "signing_private_key",
218 &crate::utils::redact::redacted(&self.signing_private_key),
219 );
220 d.field("include_certificate", &self.include_certificate);
221 d.field("saml_token_endpoint", &self.saml_token_endpoint);
222 d.field("actor", &self.actor);
223 d.finish()
224 }
225}
226
227pub struct WsSecurityClient {
229 config: WsSecurityConfig,
231
232 namespaces: HashMap<String, String>,
234}
235
236impl WsSecurityClient {
237 pub fn new(config: WsSecurityConfig) -> Self {
239 let mut namespaces = HashMap::new();
240 namespaces.insert(
241 "wsse".to_string(),
242 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
243 .to_string(),
244 );
245 namespaces.insert(
246 "wsu".to_string(),
247 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
248 .to_string(),
249 );
250 namespaces.insert(
251 "ds".to_string(),
252 "http://www.w3.org/2000/09/xmldsig#".to_string(),
253 );
254 namespaces.insert(
255 "saml".to_string(),
256 "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
257 );
258
259 Self { config, namespaces }
260 }
261
262 pub fn create_username_token_header(
264 &self,
265 username: &str,
266 password: Option<&str>,
267 password_type: PasswordType,
268 ) -> Result<WsSecurityHeader> {
269 let mut header = WsSecurityHeader::default();
270
271 let (nonce, created) = if password_type == PasswordType::PasswordDigest {
272 (Some(self.generate_nonce()), Some(Utc::now()))
273 } else {
274 (None, None)
275 };
276
277 let password_element = if let Some(pwd) = password {
278 let pwd_value = match password_type {
279 PasswordType::PasswordText => pwd.to_string(),
280 PasswordType::PasswordDigest => self.compute_password_digest(
281 pwd,
282 nonce
283 .as_ref()
284 .expect("nonce is Some for PasswordDigest variant"),
285 &created.expect("created is Some for PasswordDigest variant"),
286 )?,
287 };
288
289 Some(UsernamePassword {
290 value: pwd_value,
291 password_type,
292 })
293 } else {
294 None
295 };
296
297 header.username_token = Some(UsernameToken {
298 username: username.to_string(),
299 password: password_element,
300 nonce,
301 created,
302 wsu_id: Some(format!("UsernameToken-{}", uuid::Uuid::new_v4())),
303 });
304
305 if self.config.include_timestamp {
306 header.timestamp = Some(self.create_timestamp());
307 }
308
309 Ok(header)
310 }
311
312 pub fn create_certificate_header(&self, certificate: &[u8]) -> Result<WsSecurityHeader> {
314 let mut header = WsSecurityHeader::default();
315
316 let cert_b64 = STANDARD.encode(certificate);
318
319 header.binary_security_token = Some(BinarySecurityToken {
320 value: cert_b64,
321 value_type: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3".to_string(),
322 encoding_type: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary".to_string(),
323 wsu_id: Some(format!("X509Token-{}", uuid::Uuid::new_v4())),
324 });
325
326 if self.config.include_timestamp {
327 header.timestamp = Some(self.create_timestamp());
328 }
329
330 if self.config.sign_message {
331 header.signature = Some(self.create_signature_template()?);
332 }
333
334 Ok(header)
335 }
336
337 pub fn create_saml_header(&self, assertion: SamlAssertion) -> Result<WsSecurityHeader> {
339 let mut header = WsSecurityHeader::default();
340
341 let assertion_ref = SamlAssertionRef {
342 assertion,
343 wsu_id: Some(format!("SamlAssertion-{}", uuid::Uuid::new_v4())),
344 };
345
346 header.saml_assertions.push(assertion_ref);
347
348 if self.config.include_timestamp {
349 header.timestamp = Some(self.create_timestamp());
350 }
351
352 Ok(header)
353 }
354 pub fn header_to_xml(&self, header: &WsSecurityHeader) -> Result<String> {
356 let mut xml = String::new();
357
358 xml.push_str(&format!(
360 r#"<wsse:Security xmlns:wsse="{}" xmlns:wsu="{}">"#,
361 self.namespaces["wsse"], self.namespaces["wsu"]
362 ));
363
364 if let Some(ref timestamp) = header.timestamp {
366 xml.push_str(&self.timestamp_to_xml(timestamp));
367 }
368
369 if let Some(ref username_token) = header.username_token {
371 xml.push_str(&self.username_token_to_xml(username_token));
372 }
373
374 if let Some(ref bst) = header.binary_security_token {
376 xml.push_str(&self.binary_security_token_to_xml(bst));
377 }
378
379 for assertion_ref in &header.saml_assertions {
381 let assertion_xml = assertion_ref.assertion.to_xml()?;
382 xml.push_str(&assertion_xml);
383 }
384
385 if let Some(ref signature) = header.signature {
387 xml.push_str(&self.signature_to_xml(signature));
388 }
389
390 xml.push_str("</wsse:Security>");
392
393 Ok(xml)
394 }
395
396 fn generate_nonce(&self) -> String {
398 use rand::Rng;
399 let mut rng = rand::rng();
400 let mut nonce = [0u8; 16];
401 rng.fill_bytes(&mut nonce);
402 STANDARD.encode(nonce)
403 }
404
405 fn compute_password_digest(
407 &self,
408 password: &str,
409 nonce: &str,
410 created: &DateTime<Utc>,
411 ) -> Result<String> {
412 use sha1::{Digest, Sha1};
413
414 let nonce_bytes = STANDARD
415 .decode(nonce)
416 .map_err(|_| AuthError::auth_method("ws_security", "Invalid nonce encoding"))?;
417 let created_str = created.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
418
419 let mut hasher = Sha1::new();
420 hasher.update(&nonce_bytes);
421 hasher.update(created_str.as_bytes());
422 hasher.update(password.as_bytes());
423
424 let digest = hasher.finalize();
425 Ok(STANDARD.encode(digest))
426 }
427
428 fn create_timestamp(&self) -> Timestamp {
430 let now = Utc::now();
431 let expires = now + self.config.timestamp_ttl;
432
433 Timestamp {
434 created: now,
435 expires,
436 wsu_id: Some(format!("Timestamp-{}", uuid::Uuid::new_v4())),
437 }
438 }
439
440 fn create_signature_template(&self) -> Result<WsSecuritySignature> {
442 Ok(WsSecuritySignature {
443 signature_method: "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256".to_string(),
448 canonicalization_method: "http://www.w3.org/2001/10/xml-exc-c14n#".to_string(),
449 digest_method: "http://www.w3.org/2001/04/xmlenc#sha256".to_string(),
450 references: self
451 .config
452 .elements_to_sign
453 .iter()
454 .map(|element| {
455 SignatureReference {
456 uri: format!("#{}", element),
457 digest_value: String::new(), transforms: vec!["http://www.w3.org/2001/10/xml-exc-c14n#".to_string()],
459 }
460 })
461 .collect(),
462 key_info: None, signature_value: None, })
465 }
466
467 fn timestamp_to_xml(&self, timestamp: &Timestamp) -> String {
469 let mut xml = String::new();
470
471 if let Some(ref id) = timestamp.wsu_id {
472 xml.push_str(&format!(r#"<wsu:Timestamp wsu:Id="{}">"#, id));
473 } else {
474 xml.push_str("<wsu:Timestamp>");
475 }
476
477 xml.push_str(&format!(
478 "<wsu:Created>{}</wsu:Created>",
479 timestamp.created.format("%Y-%m-%dT%H:%M:%S%.3fZ")
480 ));
481
482 xml.push_str(&format!(
483 "<wsu:Expires>{}</wsu:Expires>",
484 timestamp.expires.format("%Y-%m-%dT%H:%M:%S%.3fZ")
485 ));
486
487 xml.push_str("</wsu:Timestamp>");
488 xml
489 }
490
491 fn username_token_to_xml(&self, token: &UsernameToken) -> String {
493 let mut xml = String::new();
494
495 if let Some(ref id) = token.wsu_id {
496 xml.push_str(&format!(
497 r#"<wsse:UsernameToken wsu:Id="{}">"#,
498 xml_escape(id)
499 ));
500 } else {
501 xml.push_str("<wsse:UsernameToken>");
502 }
503
504 xml.push_str(&format!(
505 "<wsse:Username>{}</wsse:Username>",
506 xml_escape(&token.username)
507 ));
508
509 if let Some(ref password) = token.password {
510 let type_attr = match password.password_type {
511 PasswordType::PasswordText => {
512 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"
513 }
514 PasswordType::PasswordDigest => {
515 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest"
516 }
517 };
518
519 xml.push_str(&format!(
520 r#"<wsse:Password Type="{}">{}</wsse:Password>"#,
521 type_attr,
522 xml_escape(&password.value)
523 ));
524 }
525
526 if let Some(ref nonce) = token.nonce {
527 xml.push_str(&format!(
528 r#"<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">{}</wsse:Nonce>"#,
529 nonce
530 ));
531 }
532
533 if let Some(ref created) = token.created {
534 xml.push_str(&format!(
535 "<wsu:Created>{}</wsu:Created>",
536 created.format("%Y-%m-%dT%H:%M:%S%.3fZ")
537 ));
538 }
539
540 xml.push_str("</wsse:UsernameToken>");
541 xml
542 }
543
544 fn binary_security_token_to_xml(&self, token: &BinarySecurityToken) -> String {
546 let mut xml = String::new();
547
548 xml.push_str(&format!(
549 r#"<wsse:BinarySecurityToken ValueType="{}" EncodingType="{}""#,
550 token.value_type, token.encoding_type
551 ));
552
553 if let Some(ref id) = token.wsu_id {
554 xml.push_str(&format!(r#" wsu:Id="{}""#, id));
555 }
556
557 xml.push('>');
558 xml.push_str(&token.value);
559 xml.push_str("</wsse:BinarySecurityToken>");
560
561 xml
562 }
563
564 fn signature_to_xml(&self, signature: &WsSecuritySignature) -> String {
570 let references_xml: String = signature
572 .references
573 .iter()
574 .map(|r| {
575 let digest_value = if !r.digest_value.is_empty() {
576 r.digest_value.clone()
577 } else if let Some(ref key_bytes) = self.config.signing_private_key {
578 use ring::hmac;
581 let key = hmac::Key::new(hmac::HMAC_SHA256, key_bytes);
582 let tag = hmac::sign(&key, r.uri.as_bytes());
583 STANDARD.encode(tag.as_ref())
584 } else {
585 String::new()
586 };
587
588 format!(
589 r#"<ds:Reference URI="{}">
590 <ds:Transforms>
591 {}
592 </ds:Transforms>
593 <ds:DigestMethod Algorithm="{}"/>
594 <ds:DigestValue>{}</ds:DigestValue>
595 </ds:Reference>"#,
596 r.uri,
597 r.transforms
598 .iter()
599 .map(|t| format!(r#"<ds:Transform Algorithm="{}"/>"#, t))
600 .collect::<Vec<_>>()
601 .join(""),
602 signature.digest_method,
603 digest_value,
604 )
605 })
606 .collect::<Vec<_>>()
607 .join("");
608
609 let signed_info_xml = format!(
611 r#"<ds:SignedInfo>
612 <ds:CanonicalizationMethod Algorithm="{}"/>
613 <ds:SignatureMethod Algorithm="{}"/>
614 {}
615 </ds:SignedInfo>"#,
616 signature.canonicalization_method, signature.signature_method, references_xml,
617 );
618
619 let signature_value = if let Some(ref sv) = signature.signature_value {
621 sv.clone()
622 } else if let Some(ref key_bytes) = self.config.signing_private_key {
623 use ring::hmac;
624 let key = hmac::Key::new(hmac::HMAC_SHA256, key_bytes);
625 let tag = hmac::sign(&key, signed_info_xml.as_bytes());
626 STANDARD.encode(tag.as_ref())
627 } else {
628 String::new()
629 };
630
631 let key_info_xml = if let Some(ref ki) = signature.key_info {
633 let mut ki_xml = String::new();
634 if let Some(ref x509) = ki.x509_data {
635 ki_xml.push_str(&format!(
636 "<ds:X509Data><ds:X509Certificate>{}</ds:X509Certificate></ds:X509Data>",
637 x509
638 ));
639 }
640 if let Some(ref str_ref) = ki.security_token_reference {
641 ki_xml.push_str(&format!(
642 "<wsse:SecurityTokenReference>{}</wsse:SecurityTokenReference>",
643 str_ref
644 ));
645 }
646 if let Some(ref kv) = ki.key_value {
647 ki_xml.push_str(&format!("<ds:KeyValue>{}</ds:KeyValue>", kv));
648 }
649 ki_xml
650 } else if let Some(ref cert) = self.config.signing_certificate {
651 let cert_b64 = STANDARD.encode(cert);
652 format!(
653 "<ds:X509Data><ds:X509Certificate>{}</ds:X509Certificate></ds:X509Data>",
654 cert_b64
655 )
656 } else {
657 "<ds:KeyName>WS-Security-Signing-Key</ds:KeyName>".to_string()
658 };
659
660 format!(
661 r#"<ds:Signature xmlns:ds="{}">
662 {}
663 <ds:SignatureValue>{}</ds:SignatureValue>
664 <ds:KeyInfo>{}</ds:KeyInfo>
665 </ds:Signature>"#,
666 self.namespaces["ds"], signed_info_xml, signature_value, key_info_xml,
667 )
668 }
669}
670
671impl Default for WsSecurityConfig {
672 fn default() -> Self {
673 Self {
674 include_timestamp: true,
675 timestamp_ttl: Duration::minutes(5),
676 sign_message: false,
677 elements_to_sign: vec!["Body".to_string(), "Timestamp".to_string()],
678 signing_certificate: None,
679 signing_private_key: None,
680 include_certificate: true,
681 saml_token_endpoint: None,
682 actor: None,
683 }
684 }
685}
686
687impl WsSecurityConfig {
688 pub fn builder() -> WsSecurityConfigBuilder {
704 WsSecurityConfigBuilder::default()
705 }
706}
707
708#[derive(Debug, Clone, Default)]
712pub struct WsSecurityConfigBuilder {
713 config: WsSecurityConfig,
714}
715
716impl WsSecurityConfigBuilder {
717 pub fn include_timestamp(mut self, include: bool) -> Self {
719 self.config.include_timestamp = include;
720 self
721 }
722
723 pub fn timestamp_ttl(mut self, ttl: Duration) -> Self {
725 self.config.timestamp_ttl = ttl;
726 self
727 }
728
729 pub fn sign_message(mut self, sign: bool) -> Self {
731 self.config.sign_message = sign;
732 self
733 }
734
735 pub fn elements_to_sign(mut self, elements: Vec<String>) -> Self {
737 self.config.elements_to_sign = elements;
738 self
739 }
740
741 pub fn signing_certificate(mut self, cert: Vec<u8>) -> Self {
743 self.config.signing_certificate = Some(cert);
744 self
745 }
746
747 pub fn signing_private_key(mut self, key: Vec<u8>) -> Self {
749 self.config.signing_private_key = Some(key);
750 self
751 }
752
753 pub fn include_certificate(mut self, include: bool) -> Self {
755 self.config.include_certificate = include;
756 self
757 }
758
759 pub fn saml_token_endpoint(mut self, endpoint: impl Into<String>) -> Self {
761 self.config.saml_token_endpoint = Some(endpoint.into());
762 self
763 }
764
765 pub fn actor(mut self, actor: impl Into<String>) -> Self {
767 self.config.actor = Some(actor.into());
768 self
769 }
770
771 pub fn build(self) -> WsSecurityConfig {
773 self.config
774 }
775}
776
777#[cfg(test)]
778mod tests {
779 use super::*;
780
781 #[test]
782 fn test_username_token_creation() {
783 let config = WsSecurityConfig::default();
784 let client = WsSecurityClient::new(config);
785
786 let header = client
787 .create_username_token_header("testuser", Some("testpass"), PasswordType::PasswordText)
788 .unwrap();
789
790 assert!(header.username_token.is_some());
791 let token = header.username_token.unwrap();
792 assert_eq!(token.username, "testuser");
793 assert!(token.password.is_some());
794 }
795
796 #[test]
797 fn test_password_digest() {
798 let config = WsSecurityConfig::default();
799 let client = WsSecurityClient::new(config);
800
801 let nonce = "MTIzNDU2Nzg5MDEyMzQ1Ng=="; let created = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
803 .unwrap()
804 .with_timezone(&Utc);
805 let password = "secret";
806
807 let digest = client
808 .compute_password_digest(password, nonce, &created)
809 .unwrap();
810 assert!(!digest.is_empty());
811 }
812
813 #[test]
814 fn test_timestamp_creation() {
815 let config = WsSecurityConfig::default();
816 let client = WsSecurityClient::new(config);
817
818 let timestamp = client.create_timestamp();
819 assert!(timestamp.expires > timestamp.created);
820 assert!(timestamp.wsu_id.is_some());
821 }
822
823 #[test]
824 fn test_xml_generation() {
825 let config = WsSecurityConfig::default();
826 let client = WsSecurityClient::new(config);
827
828 let header = client
829 .create_username_token_header("testuser", Some("testpass"), PasswordType::PasswordText)
830 .unwrap();
831
832 let xml = client.header_to_xml(&header).unwrap();
833 assert!(xml.contains("<wsse:Security"));
834 assert!(xml.contains("<wsse:UsernameToken"));
835 assert!(xml.contains("testuser"));
836 assert!(xml.contains("</wsse:Security>"));
837 }
838
839 #[test]
840 fn test_certificate_header() {
841 let config = WsSecurityConfig::default();
842 let client = WsSecurityClient::new(config);
843
844 let dummy_cert = b"dummy certificate data";
845 let header = client.create_certificate_header(dummy_cert).unwrap();
846
847 assert!(header.binary_security_token.is_some());
848 let bst = header.binary_security_token.unwrap();
849 assert_eq!(bst.value, STANDARD.encode(dummy_cert));
850 }
851
852 #[test]
853 fn test_xml_escape_special_characters() {
854 assert_eq!(xml_escape("hello"), "hello");
855 assert_eq!(xml_escape("<script>"), "<script>");
856 assert_eq!(xml_escape("a&b"), "a&b");
857 assert_eq!(xml_escape("\"quoted\""), ""quoted"");
858 assert_eq!(xml_escape("it's"), "it's");
859 assert_eq!(
860 xml_escape("<user>&\"name'"),
861 "<user>&"name'"
862 );
863 }
864
865 #[test]
866 fn test_xml_escape_empty_and_normal() {
867 assert_eq!(xml_escape(""), "");
868 assert_eq!(xml_escape("normal_user123"), "normal_user123");
869 }
870
871 #[test]
872 fn test_username_token_xml_escapes_injection() {
873 let config = WsSecurityConfig::default();
874 let client = WsSecurityClient::new(config);
875
876 let header = client
878 .create_username_token_header(
879 "<script>alert(1)</script>",
880 Some("pass&word\""),
881 PasswordType::PasswordText,
882 )
883 .unwrap();
884
885 let xml = client.header_to_xml(&header).unwrap();
886 assert!(!xml.contains("<script>"));
888 assert!(xml.contains("<script>"));
889 assert!(xml.contains("pass&word""));
890 }
891}