-
-
Notifications
You must be signed in to change notification settings - Fork 590
Expand file tree
/
Copy pathresponse.rb
More file actions
1007 lines (845 loc) · 37.4 KB
/
response.rb
File metadata and controls
1007 lines (845 loc) · 37.4 KB
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
require "ruby_saml/settings"
require "ruby_saml/xml"
require "ruby_saml/attributes"
require "time"
require "nokogiri"
module RubySaml
# SAML2 Authentication Response. SAML Response
class Response < SamlMessage
include ErrorHandling
# TODO: Migrate this to RubySaml::XML
SAML_NAMESPACES = {
'p' => RubySaml::XML::NS_PROTOCOL,
'a' => RubySaml::XML::NS_ASSERTION,
'ds' => RubySaml::XML::DSIG
}.freeze
# TODO: This should not be an accessor
attr_accessor :settings
attr_reader :document
attr_reader :decrypted_document
attr_reader :response
attr_reader :options
attr_accessor :soft
# Response available options
# This is not a whitelist to allow people extending RubySaml:Response
# and pass custom options
AVAILABLE_OPTIONS = %i[
allowed_clock_drift check_duplicated_attributes matches_request_id settings skip_audience skip_authnstatement skip_conditions
skip_destination skip_recipient_check skip_subject_confirmation
].freeze
# TODO: Update the comment on initialize to describe every option
# Constructs the SAML Response. A Response Object that is an extension of the SamlMessage class.
# @param response [String] A UUEncoded SAML response from the IdP.
# @param options [Hash] :settings to provide the RubySaml::Settings object
# Or some options for the response validation process like skip the conditions validation
# with the :skip_conditions, or allow a clock_drift when checking dates with :allowed_clock_drift
# or :matches_request_id that will validate that the response matches the ID of the request,
# or skip the subject confirmation validation with the :skip_subject_confirmation option
# or skip the recipient validation of the subject confirmation element with :skip_recipient_check option
# or skip the audience validation with :skip_audience option
#
def initialize(response, options = {})
raise ArgumentError.new("Response cannot be nil") if response.nil?
@errors = []
@options = options
@soft = true
message_max_bytesize = nil
unless options[:settings].nil?
@settings = options[:settings]
raise ValidationError.new("Invalid settings type: expected RubySaml::Settings, got #{@settings.class.name}") if !@settings.is_a?(Settings) && !@settings.nil?
@soft = @settings.respond_to?(:soft) && !@settings.soft.nil? ? @settings.soft : true
message_max_bytesize = @settings.message_max_bytesize if @settings.respond_to?(:message_max_bytesize)
end
@response = RubySaml::XML::Decoder.decode_message(response, message_max_bytesize)
begin
@document = RubySaml::XML.safe_load_xml(@response, check_malformed_doc: @soft)
rescue StandardError => e
@errors << "XML load failed: #{e.message}" if e.message != 'Empty document'
return if @soft
raise ValidationError.new("XML load failed: #{e.message}") if e.message != 'Empty document'
end
if !@document.nil? && assertion_encrypted?
@decrypted_document = generate_decrypted_document
end
super()
end
# Validates the SAML Response with the default values (soft = true)
# @param collect_errors [Boolean] Stop validation when the first error appears or keep validating. (if soft=true)
# @return [Boolean] TRUE if the SAML Response is valid
#
def is_valid?(collect_errors = false)
validate(collect_errors)
end
# @return [String] the NameID provided by the SAML response from the IdP.
#
def name_id
@name_id ||= name_id_node&.text
end
alias_method :nameid, :name_id
# @return [String] the NameID Format provided by the SAML response from the IdP.
#
def name_id_format
@name_id_format ||= name_id_node&.[]('Format')
end
alias_method :nameid_format, :name_id_format
# @return [String] the NameID SPNameQualifier provided by the SAML response from the IdP.
#
def name_id_spnamequalifier
@name_id_spnamequalifier ||= name_id_node&.[]('SPNameQualifier')
end
# @return [String] the NameID NameQualifier provided by the SAML response from the IdP.
#
def name_id_namequalifier
@name_id_namequalifier ||= name_id_node&.[]('NameQualifier')
end
# Gets the SessionIndex from the AuthnStatement.
# Could be used to be stored in the local session in order
# to be used in a future Logout Request that the SP could
# send to the IdP, to set what specific session must be deleted
# @return [String] SessionIndex Value
#
def sessionindex
@sessionindex ||= xpath_first_from_signed_assertion('/a:AuthnStatement')&.[]('SessionIndex')
end
# Gets the Attributes from the AttributeStatement element.
#
# All attributes can be iterated over +attributes.each+ or returned as array by +attributes.all+
# For backwards compatibility ruby-saml returns by default only the first value for a given attribute with
# attributes['name']
# To get all of the attributes, use:
# attributes.multi('name')
# Or turn off the compatibility:
# RubySaml::Attributes.single_value_compatibility = false
# Now this will return an array:
# attributes['name']
#
# @return [Attributes] RubySaml::Attributes enumerable collection.
# @raise [ValidationError] if there are 2+ Attribute with the same Name
#
def attributes
return nil if @document.nil?
@attr_statements ||= begin
attributes = Attributes.new
stmt_elements = xpath_from_signed_assertion('/a:AttributeStatement')
stmt_elements.each do |stmt_element|
stmt_element.elements.each do |attr_element|
if attr_element.name == 'EncryptedAttribute'
node = RubySaml::XML::Decryptor.decrypt_attribute(attr_element.dup, settings&.get_sp_decryption_keys)
else
node = attr_element
end
name, values = handle_nokogiri_attribute(node, attributes)
attributes.add(name, values)
end
end
attributes
end
end
def handle_nokogiri_attribute(node, attributes)
name = node['Name']
if options[:check_duplicated_attributes] && attributes.include?(name)
raise ValidationError.new("Found an Attribute element with duplicated Name")
end
values = node.elements.map do |e|
if e.elements.empty?
# SAMLCore requires that nil AttributeValues MUST contain xsi:nil XML attribute set to "true" or "1"
# otherwise the value is to be regarded as empty.
%w[true 1].include?(e['xsi:nil']) ? nil : e&.text
else
# Explicitly support saml2:NameID with saml2:NameQualifier if supplied in attributes
# this is useful for allowing eduPersonTargetedId to be passed as an opaque identifier to use to
# identify the subject in an SP rather than email or other less opaque attributes
# NameQualifier, if present is prefixed with a "/" to the value
e.xpath('a:NameID', { "a" => RubySaml::XML::NS_ASSERTION }).map do |n|
next unless (value = n&.text)
base_path = n['NameQualifier'] ? "#{n['NameQualifier']}/" : ''
"#{base_path}#{value}"
end
end
end.flatten
[name, values]
end
# Gets the SessionNotOnOrAfter from the AuthnStatement.
# Could be used to set the local session expiration (expire at latest)
# @return [String] The SessionNotOnOrAfter value
#
def session_expires_at
@expires_at ||= begin
node = xpath_first_from_signed_assertion('/a:AuthnStatement')
parse_time(node, "SessionNotOnOrAfter") if node
end
end
# Gets the AuthnInstant from the AuthnStatement.
# Could be used to require re-authentication if a long time has passed
# since the last user authentication.
# @return [String] AuthnInstant value
#
def authn_instant
@authn_instant ||= xpath_first_from_signed_assertion('/a:AuthnStatement')&.[]('AuthnInstant')
end
# Gets the AuthnContextClassRef from the AuthnStatement
# Could be used to require re-authentication if the assertion
# did not met the requested authentication context class.
# @return [String] AuthnContextClassRef value
#
def authn_context_class_ref
@authn_context_class_ref ||= xpath_first_from_signed_assertion('/a:AuthnStatement/a:AuthnContext/a:AuthnContextClassRef')&.text
end
# Checks if the Status has the "Success" code
# @return [Boolean] True if the StatusCode is Success
#
def success?
status_code == 'urn:oasis:names:tc:SAML:2.0:status:Success'
end
# @return [String] StatusCode value from a SAML Response.
#
def status_code
@status_code ||= begin
nodes = document.xpath(
"/p:Response/p:Status/p:StatusCode",
{ "p" => RubySaml::XML::NS_PROTOCOL }
)
if nodes.size == 1
node = nodes[0]
code = node['Value'] if node
unless code == "urn:oasis:names:tc:SAML:2.0:status:Success"
nodes = document.xpath(
"/p:Response/p:Status/p:StatusCode/p:StatusCode",
{ "p" => RubySaml::XML::NS_PROTOCOL }
)
statuses = nodes.map do |inner_node|
inner_node['Value']
end
code = [code, statuses].flatten.join(" | ")
end
code
end
end
end
# @return [String] the StatusMessage value from a SAML Response.
#
def status_message
@status_message ||= begin
nodes = document.xpath(
"/p:Response/p:Status/p:StatusMessage",
{ "p" => RubySaml::XML::NS_PROTOCOL }
)
nodes.first&.text if nodes.size == 1
end
end
# Gets the Condition Element of the SAML Response if exists.
# (returns the first node that matches the supplied xpath)
# @return [Nokogiri::XML::Element] Conditions Element if exists
#
def conditions
@conditions ||= xpath_first_from_signed_assertion('/a:Conditions')
end
# Gets the NotBefore Condition Element value.
# @return [Time] The NotBefore value in Time format
#
def not_before
@not_before ||= parse_time(conditions, "NotBefore")
end
# Gets the NotOnOrAfter Condition Element value.
# @return [Time] The NotOnOrAfter value in Time format
#
def not_on_or_after
@not_on_or_after ||= parse_time(conditions, "NotOnOrAfter")
end
# Gets the Issuers (from Response and Assertion).
# (returns the first node that matches the supplied xpath from the Response and from the Assertion)
# @return [Array] Array with the Issuers (Nokogiri::XML::Element)
#
def issuers
@issuers ||= begin
issuer_response_nodes = document.xpath(
"/p:Response/a:Issuer",
SAML_NAMESPACES
)
unless issuer_response_nodes.size == 1
error_msg = "Issuer of the Response not found or multiple."
raise ValidationError.new(error_msg)
end
issuer_assertion_nodes = xpath_from_signed_assertion("/a:Issuer")
unless issuer_assertion_nodes.size == 1
error_msg = "Issuer of the Assertion not found or multiple."
raise ValidationError.new(error_msg)
end
nodes = issuer_response_nodes + issuer_assertion_nodes
nodes.map(&:text).reject(&:empty?).uniq
end
end
# @return [String|nil] The InResponseTo attribute from the SAML Response.
def in_response_to
@in_response_to ||= document.at_xpath(
"/p:Response",
{ "p" => RubySaml::XML::NS_PROTOCOL }
)&.[]('InResponseTo')
end
# @return [String|nil] Destination attribute from the SAML Response.
def destination
@destination ||= document.at_xpath(
"/p:Response",
{ "p" => RubySaml::XML::NS_PROTOCOL }
)&.[]('Destination')
end
# @return [Array] The Audience elements from the Contitions of the SAML Response.
#
def audiences
@audiences ||= begin
nodes = xpath_from_signed_assertion('/a:Conditions/a:AudienceRestriction/a:Audience')
nodes.map(&:text).reject(&:empty?)
end
end
# returns the allowed clock drift on timing validation
# @return [Float]
def allowed_clock_drift
options[:allowed_clock_drift].to_f.abs + Float::EPSILON
end
# Checks if the SAML Response contains or not an EncryptedAssertion element
# @return [Boolean] True if the SAML Response contains an EncryptedAssertion element
#
def assertion_encrypted?
!document.at_xpath(
"/p:Response/EncryptedAssertion | /p:Response/a:EncryptedAssertion",
SAML_NAMESPACES
).nil?
end
def response_id
id(document)
end
def assertion_id
@assertion_id ||= begin
node = xpath_first_from_signed_assertion('')
node.nil? ? nil : node['ID']
end
end
private
# Validates the SAML Response (calls several validation methods)
# @param collect_errors [Boolean] Stop validation when first error appears or keep validating. (if soft=true)
# @return [Boolean] True if the SAML Response is valid, otherwise False if soft=True
# @raise [ValidationError] if soft == false and validation fails
#
def validate(collect_errors = false)
reset_errors!
return append_error("Blank response") if @document.nil?
return false unless validate_response_state
validations = %i[
validate_version
validate_id
validate_success_status
validate_num_assertion
validate_signed_elements
validate_structure
validate_no_duplicated_attributes
validate_in_response_to
validate_one_conditions
validate_conditions
validate_one_authnstatement
validate_audience
validate_destination
validate_issuer
validate_session_expiration
validate_subject_confirmation
validate_name_id
validate_signature
]
if collect_errors
validations.each { |validation| send(validation) }
@errors.empty?
else
validations.all? { |validation| send(validation) }
end
end
# Validates the Status of the SAML Response
# @return [Boolean] True if the SAML Response contains a Success code, otherwise False if soft == false
# @raise [ValidationError] if soft == false and validation fails
#
def validate_success_status
return true if success?
error_msg = 'The status code of the Response was not Success'
status_error_msg = RubySaml::Utils.status_error_msg(error_msg, status_code, status_message)
append_error(status_error_msg)
end
# Validates the SAML Response against the specified schema.
# @return [Boolean] True if the XML is valid, otherwise False if soft=True
# @raise [ValidationError] if soft == false and validation fails
#
def validate_structure
structure_error_msg = "Invalid SAML Response. Not match the saml-schema-protocol-2.0.xsd"
doc_to_analize = @document.nil? ? @response : @document
check_malformed_doc = check_malformed_doc_enabled?
unless valid_saml?(doc_to_analize, soft, check_malformed_doc: check_malformed_doc)
return append_error(structure_error_msg)
end
if decrypted_document && !valid_saml?(decrypted_document, soft, check_malformed_doc: check_malformed_doc)
return append_error(structure_error_msg)
end
true
end
# Validates that the SAML Response provided in the initialization is not empty,
# also check that the settings and the IdP cert were also provided
# @return [Boolean] True if the required info is found, false otherwise
#
def validate_response_state
return append_error("Blank response") if response.nil? || response.empty?
return append_error("No settings on response") if settings.nil?
if settings.idp_cert_fingerprint.nil? && settings.idp_cert.nil? && settings.idp_cert_multi.nil?
return append_error("No fingerprint or certificate on settings")
end
true
end
# Validates that the SAML Response contains an ID
# If fails, the error is added to the errors array.
# @return [Boolean] True if the SAML Response contains an ID, otherwise returns False
#
def validate_id
return true if response_id
append_error("Missing ID attribute on SAML Response")
end
# Validates the SAML version (2.0)
# If fails, the error is added to the errors array.
# @return [Boolean] True if the SAML Response is 2.0, otherwise returns False
#
def validate_version
return true if version(document) == "2.0"
append_error("Unsupported SAML version")
end
# Validates that the SAML Response only contains a single Assertion (encrypted or not).
# If fails, the error is added to the errors array.
# @return [Boolean] True if the SAML Response contains one unique Assertion, otherwise False
#
def validate_num_assertion
error_msg = "SAML Response must contain 1 assertion"
assertions = document.xpath(
"//a:Assertion",
{ "a" => RubySaml::XML::NS_ASSERTION }
)
encrypted_assertions = document.xpath(
"//a:EncryptedAssertion",
{ "a" => RubySaml::XML::NS_ASSERTION }
)
unless assertions.size + encrypted_assertions.size == 1
return append_error(error_msg)
end
unless decrypted_document.nil?
assertions = decrypted_document.xpath(
"//a:Assertion",
{ "a" => RubySaml::XML::NS_ASSERTION }
)
unless assertions.size == 1
return append_error(error_msg)
end
end
true
end
# Validates that there are not duplicated attributes
# If fails, the error is added to the errors array
# @return [Boolean] True if there are no duplicated attribute elements, otherwise False if soft=True
# @raise [ValidationError] if soft == false and validation fails
#
def validate_no_duplicated_attributes
if options[:check_duplicated_attributes]
begin
attributes
rescue ValidationError => e
return append_error(e.message)
end
end
true
end
# Validates the Signed elements
# If fails, the error is added to the errors array
# @return [Boolean] True if there is 1 or 2 Elements signed in the SAML Response
# and are a Response or an Assertion Element, otherwise False if soft=True
#
def validate_signed_elements
signature_nodes = (decrypted_document.nil? ? document : decrypted_document).xpath(
"//ds:Signature",
{ "ds" => RubySaml::XML::DSIG }
)
signed_elements = []
verified_seis = []
verified_ids = []
signature_nodes.each do |signature_node|
signed_element = signature_node.parent.name
if signed_element != 'Response' && signed_element != 'Assertion'
return append_error("Invalid Signature Element '#{signed_element}'. SAML Response rejected")
end
if signature_node.parent['ID'].nil?
return append_error("Signed Element must contain an ID. SAML Response rejected")
end
id = signature_node.parent['ID']
if verified_ids.include?(id)
return append_error("Duplicated ID. SAML Response rejected")
end
verified_ids.push(id)
# Check that reference URI matches the parent ID and no duplicate References or IDs
ref = signature_node.at_xpath(".//ds:Reference", { "ds" => RubySaml::XML::DSIG })
if ref
uri = ref['URI']
if uri && !uri.empty?
sei = uri[1..]
unless sei == id
return append_error("Found an invalid Signed Element. SAML Response rejected")
end
if verified_seis.include?(sei)
return append_error("Duplicated Reference URI. SAML Response rejected")
end
verified_seis.push(sei)
end
end
signed_elements << signed_element
end
unless signature_nodes.size < 3 && !signed_elements.empty?
return append_error("Found an unexpected number of Signature Element. SAML Response rejected")
end
if settings.security[:want_assertions_signed] && !(signed_elements.include? "Assertion")
return append_error("The Assertion of the Response is not signed and the SP requires it")
end
true
end
# Validates if the provided request_id matches the inResponseTo value.
# If fails, the error is added to the errors array
# @return [Boolean] True if there is no request_id or it matches, otherwise False if soft=True
# @raise [ValidationError] if soft == false and validation fails
#
def validate_in_response_to
return true unless options.key? :matches_request_id
return true if options[:matches_request_id].nil?
return true unless options[:matches_request_id] != in_response_to
error_msg = "The InResponseTo of the Response: #{in_response_to}, does not match the ID of the AuthNRequest sent by the SP: #{options[:matches_request_id]}"
append_error(error_msg)
end
# Validates the Audience, (If the Audience matches the Service Provider EntityID)
# If the response was initialized with the :skip_audience option, this validation is skipped,
# If fails, the error is added to the errors array
# @return [Boolean] True if there is an Audience Element that matches the Service Provider EntityID, otherwise False if soft=True
# @raise [ValidationError] if soft == false and validation fails
#
def validate_audience
return true if options[:skip_audience]
return true if settings.sp_entity_id.nil? || settings.sp_entity_id.empty?
if audiences.empty?
return true unless settings.security[:strict_audience_validation]
return append_error("Invalid Audiences. The <AudienceRestriction> element contained only empty <Audience> elements. Expected audience #{settings.sp_entity_id}.")
end
unless audiences.include? settings.sp_entity_id
s = audiences.count > 1 ? 's' : ''
error_msg = "Invalid Audience#{s}. The audience#{s} #{audiences.join(',')}, did not match the expected audience #{settings.sp_entity_id}"
return append_error(error_msg)
end
true
end
# Validates the Destination, (If the SAML Response is received where expected).
# If the response was initialized with the :skip_destination option, this validation is skipped,
# If fails, the error is added to the errors array
# @return [Boolean] True if there is a Destination element that matches the Consumer Service URL, otherwise False
#
def validate_destination
return true if destination.nil?
return true if options[:skip_destination]
if destination.empty?
error_msg = "The response has an empty Destination value"
return append_error(error_msg)
end
return true if settings.assertion_consumer_service_url.nil? || settings.assertion_consumer_service_url.empty?
unless RubySaml::Utils.uri_match?(destination, settings.assertion_consumer_service_url)
error_msg = "The response was received at #{destination} instead of #{settings.assertion_consumer_service_url}"
return append_error(error_msg)
end
true
end
# Checks that the samlp:Response/saml:Assertion/saml:Conditions element exists and is unique.
# (If the response was initialized with the :skip_conditions option, this validation is skipped)
# If fails, the error is added to the errors array
# @return [Boolean] True if there is a conditions element and is unique
#
def validate_one_conditions
return true if options[:skip_conditions]
conditions_nodes = xpath_from_signed_assertion('/a:Conditions')
unless conditions_nodes.size == 1
error_msg = "The Assertion must include one Conditions element"
return append_error(error_msg)
end
true
end
# Checks that the samlp:Response/saml:Assertion/saml:AuthnStatement element exists and is unique.
# If fails, the error is added to the errors array
# @return [Boolean] True if there is a AuthnStatement element and is unique
#
def validate_one_authnstatement
return true if options[:skip_authnstatement]
authnstatement_nodes = xpath_from_signed_assertion('/a:AuthnStatement')
unless authnstatement_nodes.size == 1
error_msg = "The Assertion must include one AuthnStatement element"
return append_error(error_msg)
end
true
end
# Validates the Conditions. (If the response was initialized with the :skip_conditions option, this validation is skipped,
# If the response was initialized with the :allowed_clock_drift option, the timing validations are relaxed by the allowed_clock_drift value)
# @return [Boolean] True if satisfies the conditions, otherwise False if soft=True
# @raise [ValidationError] if soft == false and validation fails
#
def validate_conditions
return true if conditions.nil?
return true if options[:skip_conditions]
now = Time.now.utc
if not_before && now < (not_before - allowed_clock_drift)
error_msg = "Current time is earlier than NotBefore condition (#{now} < #{not_before}#{" - #{allowed_clock_drift.ceil}s" if allowed_clock_drift > 0})"
return append_error(error_msg)
end
if not_on_or_after && now >= (not_on_or_after + allowed_clock_drift)
error_msg = "Current time is on or after NotOnOrAfter condition (#{now} >= #{not_on_or_after}#{" + #{allowed_clock_drift.ceil}s" if allowed_clock_drift > 0})"
return append_error(error_msg)
end
true
end
# Validates the Issuer (Of the SAML Response and the SAML Assertion)
# @param soft [Boolean] soft Enable or Disable the soft mode (In order to raise exceptions when the response is invalid or not)
# @return [Boolean] True if the Issuer matches the IdP entityId, otherwise False if soft=True
# @raise [ValidationError] if soft == false and validation fails
#
def validate_issuer
return true if settings.idp_entity_id.nil?
begin
obtained_issuers = issuers
rescue ValidationError => e
return append_error(e.message)
end
obtained_issuers.each do |issuer|
unless RubySaml::Utils.uri_match?(issuer, settings.idp_entity_id)
error_msg = "Doesn't match the issuer, expected: <#{settings.idp_entity_id}>, but was: <#{issuer}>"
return append_error(error_msg)
end
end
true
end
# Validates that the Session hasn't expired (If the response was initialized with the :allowed_clock_drift option,
# this time validation is relaxed by the allowed_clock_drift value)
# If fails, the error is added to the errors array
# @param soft [Boolean] soft Enable or Disable the soft mode (In order to raise exceptions when the response is invalid or not)
# @return [Boolean] True if the SessionNotOnOrAfter of the AuthnStatement is valid, otherwise (when expired) False if soft=True
# @raise [ValidationError] if soft == false and validation fails
#
def validate_session_expiration
return true if session_expires_at.nil?
now = Time.now.utc
unless now < (session_expires_at + allowed_clock_drift)
error_msg = "The attributes have expired, based on the SessionNotOnOrAfter of the AuthnStatement of this Response"
return append_error(error_msg)
end
true
end
# Validates if a valid SubjectConfirmation (If the response was initialized with the :allowed_clock_drift option,
# timing validation are relaxed by the allowed_clock_drift value. If the response was initialized with the
# :skip_subject_confirmation option, this validation is skipped)
# There is also an optional Recipient check
# If fails, the error is added to the errors array
# @return [Boolean] True if a valid SubjectConfirmation, otherwise False if soft=True
# @raise [ValidationError] if soft == false and validation fails
#
def validate_subject_confirmation
return true if options[:skip_subject_confirmation]
valid_subject_confirmation = false
subject_confirmation_nodes = xpath_from_signed_assertion('/a:Subject/a:SubjectConfirmation')
now = Time.now.utc
subject_confirmation_nodes.each do |subject_confirmation|
if subject_confirmation['Method'] != 'urn:oasis:names:tc:SAML:2.0:cm:bearer'
next
end
confirmation_data_node = subject_confirmation.at_xpath('a:SubjectConfirmationData', { "a" => RubySaml::XML::NS_ASSERTION })
next unless confirmation_data_node
next if (confirmation_data_node['InResponseTo'] && confirmation_data_node['InResponseTo'] != in_response_to) ||
(confirmation_data_node['NotBefore'] && now < (parse_time(confirmation_data_node, "NotBefore") - allowed_clock_drift)) ||
(confirmation_data_node['NotOnOrAfter'] && now >= (parse_time(confirmation_data_node, "NotOnOrAfter") + allowed_clock_drift)) ||
(confirmation_data_node['Recipient'] && !options[:skip_recipient_check] && settings && confirmation_data_node['Recipient'] != settings.assertion_consumer_service_url)
valid_subject_confirmation = true
break
end
unless valid_subject_confirmation
error_msg = "A valid SubjectConfirmation was not found on this Response"
return append_error(error_msg)
end
true
end
# Validates the NameID element
def validate_name_id
if name_id_node.nil?
if settings.security[:want_name_id]
return append_error("No NameID element found in the assertion of the Response")
end
else
if name_id.nil? || name_id.empty?
return append_error("An empty NameID value found")
end
if !(settings.sp_entity_id.nil? || settings.sp_entity_id.empty? || name_id_spnamequalifier.nil? || name_id_spnamequalifier.empty?) && (name_id_spnamequalifier != settings.sp_entity_id)
return append_error('SPNameQualifier value does not match the SP entityID value.')
end
end
true
end
def doc_to_validate
# Validate the original SAML Response if the response contains the signature,
# and the assertion was encrypted. Otherwise, review if the decrypted assertion
# contains a signature.
subject_id = RubySaml::XML::SignedDocumentValidator.subject_id(document)
return decrypted_document unless subject_id
sig_elements = document.xpath(
"/p:Response[@ID=$id]/ds:Signature",
{ "p" => RubySaml::XML::NS_PROTOCOL, "ds" => RubySaml::XML::DSIG },
id: subject_id
)
use_original = sig_elements.size == 1 || decrypted_document.nil?
use_original ? document : decrypted_document
end
# Validates the Signature
# @return [Boolean] True if not contains a Signature or if the Signature is valid, otherwise False if soft=True
# @raise [ValidationError] if soft == false and validation fails
#
def validate_signature
error_msg = "Invalid Signature on SAML Response"
doc = doc_to_validate
# TODO: document vs doc is super confusing
subject_id = RubySaml::XML::SignedDocumentValidator.subject_id(document)
sig_elements = []
if subject_id
sig_elements = document.xpath(
"/p:Response[@ID=$id]/ds:Signature",
{ "p" => RubySaml::XML::NS_PROTOCOL, "ds" => RubySaml::XML::DSIG },
id: subject_id
)
end
# Check signature node inside assertion
if sig_elements.empty?
subject_id2 = RubySaml::XML::SignedDocumentValidator.subject_id(doc)
sig_elements = doc.xpath(
"/p:Response/a:Assertion[@ID=$id]/ds:Signature",
SAML_NAMESPACES,
id: subject_id2
)
end
if sig_elements.size != 1
if sig_elements.empty?
append_error("Signed element id ##{subject_id} is not found")
else
append_error("Signed element id ##{subject_id} is found more than once")
end
return append_error(error_msg)
end
old_errors = @errors.clone
idp_certs = settings.get_idp_cert_multi
if idp_certs.nil? || idp_certs[:signing].empty?
idp_cert = settings.get_idp_cert
fingerprint = settings.get_fingerprint
opts = {
cert: idp_cert,
fingerprint_alg: settings.idp_cert_fingerprint_algorithm
}
if fingerprint && RubySaml::XML::SignedDocumentValidator.validate_document(doc, fingerprint, @errors, soft: @soft, **opts).is_a?(TrueClass) # TODO: DANGEROUS
if settings.security[:check_idp_cert_expiration] && RubySaml::Utils.is_cert_expired(idp_cert)
return append_error("IdP x509 certificate expired")
end
else
return append_error(error_msg)
end
else
valid = false
expired = false
idp_certs[:signing].each do |idp_cert|
valid = RubySaml::XML::SignedDocumentValidator.validate_document_with_cert(doc, idp_cert, @errors, soft: @soft).is_a?(TrueClass) # TODO: DANGEROUS
next unless valid
if settings.security[:check_idp_cert_expiration] && RubySaml::Utils.is_cert_expired(idp_cert)
expired = true
end
# At least one certificate is valid, restore the old accumulated errors
@errors = old_errors
break
end
if expired
return append_error("IdP x509 certificate expired")
end
unless valid
# Remove duplicated errors
@errors = @errors.uniq
return append_error(error_msg)
end
end
true
end
def name_id_node
return nil if @document.nil?
@name_id_node ||=
begin
encrypted_node = xpath_first_from_signed_assertion('/a:Subject/a:EncryptedID')
if encrypted_node
RubySaml::XML::Decryptor.decrypt_nameid(encrypted_node, settings&.get_sp_decryption_keys)
else
xpath_first_from_signed_assertion('/a:Subject/a:NameID')
end
end
end
def cached_signed_assertion
empty_doc = Nokogiri::XML::Document.new
xml = doc_to_validate
return empty_doc if xml.nil?
subject = RubySaml::XML::SignedDocumentValidator.subject_node(xml)
return empty_doc if xml.nil? # when no signature/reference is found, return empty document
subject_id = RubySaml::XML::SignedDocumentValidator.subject_id(xml)
return nil unless subject_id
if subject['ID'] != subject_id
return empty_doc
end
assertion = empty_doc
if subject.name == "Response"
if (result = subject.at_xpath("a:Assertion", {"a" => RubySaml::XML::NS_ASSERTION}))
assertion = result
elsif (result = subject.at_xpath("a:EncryptedAssertion", {"a" => RubySaml::XML::NS_ASSERTION}))
assertion = RubySaml::XML::Decryptor.decrypt_assertion(result, settings&.get_sp_decryption_keys)
end
elsif subject.name == "Assertion"
assertion = subject
end
assertion
end
def signed_assertion
@signed_assertion ||= cached_signed_assertion
end
# Extracts the first appearance that matches the subpath (pattern)
# Searches on any Assertion that is signed, or has a Response parent signed
# @param subpath [String] The XPath pattern
# @return [Nokogiri::XML::Element | nil] If any matches, return the Element
def xpath_first_from_signed_assertion(subpath = nil)
return if !subpath || subpath.empty?
signed_assertion.at_xpath("./#{subpath}", SAML_NAMESPACES)
end
# Extracts all the appearances that matches the subpath (pattern)
# Searches on any Assertion that is signed, or has a Response parent signed
# @param subpath [String] The XPath pattern
# @return [Array of Nokogiri::XML::Element] Return all matches
def xpath_from_signed_assertion(subpath = nil)
return if !subpath || subpath.empty?
signed_assertion.xpath("./#{subpath}", SAML_NAMESPACES)
end
# Generates the decrypted_document
# @return [RubySaml::XML::SignedDocument] The SAML Response with the assertion decrypted
#
def generate_decrypted_document
RubySaml::XML::Decryptor.decrypt_document(document, settings&.get_sp_decryption_keys)
end
# Parse the attribute of a given node in Time format
# @param node [Nokogiri::XML::Element] The node
# @param attribute [String] The attribute name
# @return [Time|nil] The parsed value
#
def parse_time(node, attribute)
return unless (value = node&.[](attribute))
Time.parse(value)