forked from SAML-Toolkits/ruby-saml
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathidp_metadata_parser.rb
More file actions
446 lines (387 loc) · 21.9 KB
/
idp_metadata_parser.rb
File metadata and controls
446 lines (387 loc) · 21.9 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
# frozen_string_literal: true
require "base64"
require "net/http"
require "net/https"
require "nokogiri"
module RubySaml
# Auxiliary class to retrieve and parse the Identity Provider Metadata.
# This class does not validate in any way the URL that is introduced,
# make sure to validate it properly before use it in a parse_remote method.
# Read the `Security warning` section of the README.md file to get more info
class IdpMetadataParser
NAMESPACES = {
"ds" => RubySaml::XML::DSIG,
"md" => RubySaml::XML::NS_METADATA,
"saml" => RubySaml::XML::NS_ASSERTION
}.freeze
attr_reader :document
attr_reader :response
attr_reader :options
# fetch IdP descriptors from a metadata document
def self.get_idps(noko_document, only_entity_id = nil)
path = "//md:EntityDescriptor#{"[@entityID=\"#{only_entity_id}\"]" if only_entity_id}/md:IDPSSODescriptor"
noko_document.xpath(path, NAMESPACES)
end
# Parse the Identity Provider metadata and update the settings with the
# IdP values
#
# @param url [String] Url where the XML of the Identity Provider Metadata is published.
# @param validate_cert [Boolean] If true and the URL is HTTPs, the cert of the domain is checked.
#
# @param options [Hash] options used for parsing the metadata and the returned Settings instance
# @option options [RubySaml::Settings, Hash] :settings the RubySaml::Settings object which gets the parsed metadata merged into or an hash for Settings overrides.
# @option options [String, nil] :entity_id when this is given, the entity descriptor for this ID is used. When omitted, the first entity descriptor is used.
# @option options [String, Array<String>, nil] :sso_binding an ordered list of bindings to detect the single signon URL. The first binding in the list that is included in the metadata will be used.
# @option options [String, Array<String>, nil] :slo_binding an ordered list of bindings to detect the single logout URL. The first binding in the list that is included in the metadata will be used.
# @option options [String, Array<String>, nil] :name_id_format an ordered list of NameIDFormats to detect a desired value. The first NameIDFormat in the list that is included in the metadata will be used.
# @option options [Numeric, nil] :open_timeout Number of seconds to wait for the connection to open. See Net::HTTP#open_timeout for more info. Default is the Net::HTTP default.
# @option options [Numeric, nil] :read_timeout Number of seconds to wait for one block to be read. See Net::HTTP#read_timeout for more info. Default is the Net::HTTP default.
# @option options [Integer, nil] :max_retries Maximum number of times to retry the request on certain errors. See Net::HTTP#max_retries= for more info. Default is the Net::HTTP default.
#
# @return [RubySaml::Settings]
#
# @raise [HttpError] Failure to fetch remote IdP metadata
def parse_remote(url, validate_cert = true, options = {})
idp_metadata = get_idp_metadata(url, validate_cert, options)
parse(idp_metadata, options)
end
# Parse the Identity Provider metadata and return the results as Hash
#
# @param url [String] Url where the XML of the Identity Provider Metadata is published.
# @param validate_cert [Boolean] If true and the URL is HTTPs, the cert of the domain is checked.
#
# @param options [Hash] options used for parsing the metadata
# @option options [String, nil] :entity_id when this is given, the entity descriptor for this ID is used. When omitted, the first entity descriptor is used.
# @option options [String, Array<String>, nil] :sso_binding an ordered list of bindings to detect the single signon URL. The first binding in the list that is included in the metadata will be used.
# @option options [String, Array<String>, nil] :slo_binding an ordered list of bindings to detect the single logout URL. The first binding in the list that is included in the metadata will be used.
# @option options [String, Array<String>, nil] :name_id_format an ordered list of NameIDFormats to detect a desired value. The first NameIDFormat in the list that is included in the metadata will be used.
# @option options [Numeric, nil] :open_timeout Number of seconds to wait for the connection to open. See Net::HTTP#open_timeout for more info. Default is the Net::HTTP default.
# @option options [Numeric, nil] :read_timeout Number of seconds to wait for one block to be read. See Net::HTTP#read_timeout for more info. Default is the Net::HTTP default.
# @option options [Integer, nil] :max_retries Maximum number of times to retry the request on certain errors. See Net::HTTP#max_retries= for more info. Default is the Net::HTTP default.
#
# @return [Hash]
#
# @raise [HttpError] Failure to fetch remote IdP metadata
def parse_remote_to_hash(url, validate_cert = true, options = {})
parse_remote_to_array(url, validate_cert, options)[0]
end
# Parse all Identity Provider metadata and return the results as Array
#
# @param url [String] Url where the XML of the Identity Provider Metadata is published.
# @param validate_cert [Boolean] If true and the URL is HTTPs, the cert of the domain is checked.
#
# @param options [Hash] options used for parsing the metadata
# @option options [String, nil] :entity_id when this is given, the entity descriptor for this ID is used. When omitted, all found IdPs are returned.
# @option options [String, Array<String>, nil] :sso_binding an ordered list of bindings to detect the single signon URL. The first binding in the list that is included in the metadata will be used.
# @option options [String, Array<String>, nil] :slo_binding an ordered list of bindings to detect the single logout URL. The first binding in the list that is included in the metadata will be used.
# @option options [String, Array<String>, nil] :name_id_format an ordered list of NameIDFormats to detect a desired value. The first NameIDFormat in the list that is included in the metadata will be used.
# @option options [Numeric, nil] :open_timeout Number of seconds to wait for the connection to open. See Net::HTTP#open_timeout for more info. Default is the Net::HTTP default.
# @option options [Numeric, nil] :read_timeout Number of seconds to wait for one block to be read. See Net::HTTP#read_timeout for more info. Default is the Net::HTTP default.
# @option options [Integer, nil] :max_retries Maximum number of times to retry the request on certain errors. See Net::HTTP#max_retries= for more info. Default is the Net::HTTP default.
#
# @return [Array<Hash>]
#
# @raise [HttpError] Failure to fetch remote IdP metadata
def parse_remote_to_array(url, validate_cert = true, options = {})
idp_metadata = get_idp_metadata(url, validate_cert, options)
parse_to_array(idp_metadata, options)
end
# Parse the Identity Provider metadata and update the settings with the IdP values
#
# @param idp_metadata [String]
#
# @param options [Hash] :settings to provide the RubySaml::Settings object or an hash for Settings overrides
# @option options [RubySaml::Settings, Hash] :settings the RubySaml::Settings object which gets the parsed metadata merged into or an hash for Settings overrides.
# @option options [String, nil] :entity_id when this is given, the entity descriptor for this ID is used. When omitted, the first entity descriptor is used.
# @option options [String, Array<String>, nil] :sso_binding an ordered list of bindings to detect the single signon URL. The first binding in the list that is included in the metadata will be used.
# @option options [String, Array<String>, nil] :slo_binding an ordered list of bindings to detect the single logout URL. The first binding in the list that is included in the metadata will be used.
# @option options [String, Array<String>, nil] :name_id_format an ordered list of NameIDFormats to detect a desired value. The first NameIDFormat in the list that is included in the metadata will be used.
#
# @return [RubySaml::Settings]
def parse(idp_metadata, options = {})
parsed_metadata = parse_to_hash(idp_metadata, options)
unless parsed_metadata[:cache_duration].nil?
cache_valid_until_timestamp = RubySaml::Utils.parse_duration(parsed_metadata[:cache_duration])
if !cache_valid_until_timestamp.nil? && (parsed_metadata[:valid_until].nil? || cache_valid_until_timestamp < Time.parse(parsed_metadata[:valid_until], Time.now.utc).to_i)
parsed_metadata[:valid_until] = Time.at(cache_valid_until_timestamp).utc.strftime("%Y-%m-%dT%H:%M:%SZ")
end
end
# Remove the cache_duration because on the settings
# we only gonna suppot valid_until
parsed_metadata.delete(:cache_duration)
settings = options[:settings]
if settings.nil?
RubySaml::Settings.new(parsed_metadata)
elsif settings.is_a?(Hash)
RubySaml::Settings.new(settings.merge(parsed_metadata))
else
merge_parsed_metadata_into(settings, parsed_metadata)
end
end
# Parse the Identity Provider metadata and return the results as Hash
#
# @param idp_metadata [String]
#
# @param options [Hash] options used for parsing the metadata and the returned Settings instance
# @option options [String, nil] :entity_id when this is given, the entity descriptor for this ID is used. When omitted, the first entity descriptor is used.
# @option options [String, Array<String>, nil] :sso_binding an ordered list of bindings to detect the single signon URL. The first binding in the list that is included in the metadata will be used.
# @option options [String, Array<String>, nil] :slo_binding an ordered list of bindings to detect the single logout URL. The first binding in the list that is included in the metadata will be used.
# @option options [String, Array<String>, nil] :name_id_format an ordered list of NameIDFormats to detect a desired value. The first NameIDFormat in the list that is included in the metadata will be used.
#
# @return [Hash]
def parse_to_hash(idp_metadata, options = {})
parse_to_array(idp_metadata, options)[0]
end
# Parse all Identity Provider metadata and return the results as Array
#
# @param idp_metadata [String]
#
# @param options [Hash] options used for parsing the metadata and the returned Settings instance
# @option options [String, nil] :entity_id when this is given, the entity descriptor for this ID is used. When omitted, all found IdPs are returned.
# @option options [String, Array<String>, nil] :sso_binding an ordered list of bindings to detect the single signon URL. The first binding in the list that is included in the metadata will be used.
# @option options [String, Array<String>, nil] :slo_binding an ordered list of bindings to detect the single logout URL. The first binding in the list that is included in the metadata will be used.
# @option options [String, Array<String>, nil] :name_id_format an ordered list of NameIDFormats to detect a desired value. The first NameIDFormat in the list that is included in the metadata will be used.
#
# @return [Array<Hash>]
def parse_to_array(idp_metadata, options = {})
parse_to_idp_metadata_array(idp_metadata, options).map { |idp_md| idp_md.to_hash(options) }
end
def parse_to_idp_metadata_array(idp_metadata, options = {})
@document = Nokogiri::XML(idp_metadata) # TODO: RubySaml::XML.safe_load_nokogiri
@options = options
idpsso_descriptors = self.class.get_idps(@document, options[:entity_id])
if idpsso_descriptors.none?
raise ArgumentError.new("idp_metadata must contain an IDPSSODescriptor element")
end
idpsso_descriptors.map { |idpsso| IdpMetadata.new(idpsso, idpsso.parent['entityID']) }
end
# Retrieve the remote IdP metadata from the URL or a cached copy.
# @param url [String] Url where the XML of the Identity Provider Metadata is published.
# @param validate_cert [Boolean] If true and the URL is HTTPs, the cert of the domain is checked.
# @param options [Hash] Options used for requesting the remote URL
# @option options [Numeric, nil] :open_timeout Number of seconds to wait for the connection to open. See Net::HTTP#open_timeout for more info. Default is the Net::HTTP default.
# @option options [Numeric, nil] :read_timeout Number of seconds to wait for one block to be read. See Net::HTTP#read_timeout for more info. Default is the Net::HTTP default.
# @option options [Integer, nil] :max_retries Maximum number of times to retry the request on certain errors. See Net::HTTP#max_retries= for more info. Default is the Net::HTTP default.
# @return [Nokogiri::XML::Document] Parsed XML IdP metadata
# @raise [HttpError] Failure to fetch remote IdP metadata
def get_idp_metadata(url, validate_cert, options = {})
uri = URI.parse(url)
raise ArgumentError.new("url must begin with http or https") unless /^https?/.match?(uri.scheme)
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == "https"
http.use_ssl = true
# Most IdPs will probably use self signed certs
http.verify_mode = validate_cert ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
end
http.open_timeout = options[:open_timeout] if options[:open_timeout]
http.read_timeout = options[:read_timeout] if options[:read_timeout]
http.max_retries = options[:max_retries] if options[:max_retries]
get = Net::HTTP::Get.new(uri.request_uri)
get.basic_auth(uri.user, uri.password) if uri.user
@response = http.request(get)
return response.body if response.is_a?(Net::HTTPSuccess)
raise RubySaml::HttpError.new("Failed to fetch idp metadata: #{response.code}: #{response.message}")
end
private
class IdpMetadata
attr_reader :idpsso_descriptor, :entity_id
# TODO: This constructor should take noko_document, noko_idpsso_descriptor as its args
# Entity ID can be found from the noko_document root.
def initialize(idpsso_descriptor, entity_id)
@idpsso_descriptor = idpsso_descriptor
@entity_id = entity_id
end
def to_hash(options = {})
sso_binding = options[:sso_binding]
slo_binding = options[:slo_binding]
{
idp_entity_id: @entity_id,
name_identifier_format: idp_name_id_format(options[:name_id_format]),
idp_sso_service_url: single_signon_service_url(sso_binding),
idp_sso_service_binding: single_signon_service_binding(sso_binding),
idp_slo_service_url: single_logout_service_url(slo_binding),
idp_slo_service_binding: single_logout_service_binding(slo_binding),
idp_slo_response_service_url: single_logout_response_service_url(slo_binding),
idp_attribute_names: attribute_names,
idp_cert: nil,
idp_cert_fingerprint: nil,
idp_cert_multi: nil,
valid_until: valid_until,
cache_duration: cache_duration
}.tap do |response_hash|
merge_certificates_into(response_hash) unless certificates.nil?
end
end
# @return [String|nil] 'validUntil' attribute of metadata
#
def valid_until
root = @idpsso_descriptor.document.root
root['validUntil'] if root
end
# @return [String|nil] 'cacheDuration' attribute of metadata
#
def cache_duration
root = @idpsso_descriptor.document.root
root['cacheDuration'] if root
end
# @param name_id_priority [String|Array<String>] The prioritized list of NameIDFormat values to select. Will select first value if nil.
# @return [String|nil] IdP NameIDFormat value if exists
#
def idp_name_id_format(name_id_priority = nil)
nodes = @idpsso_descriptor.xpath(
"md:NameIDFormat",
NAMESPACES
)
first_ranked_text(nodes, name_id_priority)
end
# @param binding_priority [String|Array<String>] The prioritized list of Binding values to select. Will select first value if nil.
# @return [String|nil] SingleSignOnService binding if exists
#
def single_signon_service_binding(binding_priority = nil)
nodes = @idpsso_descriptor.xpath(
"md:SingleSignOnService/@Binding",
NAMESPACES
)
first_ranked_value(nodes, binding_priority)
end
# @param binding_priority [String|Array<String>] The prioritized list of Binding values to select. Will select first value if nil.
# @return [String|nil] SingleLogoutService binding if exists
#
def single_logout_service_binding(binding_priority = nil)
nodes = @idpsso_descriptor.xpath(
"md:SingleLogoutService/@Binding",
NAMESPACES
)
first_ranked_value(nodes, binding_priority)
end
# @param binding_priority [String|Array<String>] The prioritized list of Binding values to select. Will select first value if nil.
# @return [String|nil] SingleSignOnService endpoint if exists
#
def single_signon_service_url(binding_priority = nil)
binding = single_signon_service_binding(binding_priority)
return if binding.nil?
@idpsso_descriptor.at_xpath(
"md:SingleSignOnService[@Binding=\"#{binding}\"]/@Location",
NAMESPACES
)&.value
end
# @param binding_priority [String|Array<String>] The prioritized list of Binding values to select. Will select first value if nil.
# @return [String|nil] SingleLogoutService endpoint if exists
#
def single_logout_service_url(binding_priority = nil)
binding = single_logout_service_binding(binding_priority)
return if binding.nil?
@idpsso_descriptor.at_xpath(
"md:SingleLogoutService[@Binding=\"#{binding}\"]/@Location",
NAMESPACES
)&.value
end
# @param binding_priority [String|Array<String>] The prioritized list of Binding values to select. Will select first value if nil.
# @return [String|nil] SingleLogoutService response url if exists
#
def single_logout_response_service_url(binding_priority = nil)
binding = single_logout_service_binding(binding_priority)
return if binding.nil?
node = @idpsso_descriptor.at_xpath(
"md:SingleLogoutService[@Binding=\"#{binding}\"]/@ResponseLocation",
NAMESPACES
)
node&.value
end
# @return [String|nil] Unformatted Certificate if exists
#
def certificates
@certificates ||= begin
signing_nodes = @idpsso_descriptor.xpath(
"md:KeyDescriptor[not(contains(@use, 'encryption'))]/ds:KeyInfo/ds:X509Data/ds:X509Certificate",
NAMESPACES
)
encryption_nodes = @idpsso_descriptor.xpath(
"md:KeyDescriptor[not(contains(@use, 'signing'))]/ds:KeyInfo/ds:X509Data/ds:X509Certificate",
NAMESPACES
)
return nil if signing_nodes.empty? && encryption_nodes.empty?
certs = {}
unless signing_nodes.empty?
certs['signing'] = []
signing_nodes.each do |cert_node|
certs['signing'] << cert_node.text
end
end
unless encryption_nodes.empty?
certs['encryption'] = []
encryption_nodes.each do |cert_node|
certs['encryption'] << cert_node.text
end
end
certs
end
end
# @return [String|nil] the fingerpint of the X509Certificate if it exists
#
def fingerprint(certificate, fingerprint_algorithm = RubySaml::XML::SHA256)
return unless certificate
cert = OpenSSL::X509::Certificate.new(Base64.decode64(certificate))
fingerprint_alg = RubySaml::XML.hash_algorithm(fingerprint_algorithm).new
fingerprint_alg.hexdigest(cert.to_der).upcase.scan(/../).join(":")
end
# @return [Array] the names of all SAML attributes if any exist
#
def attribute_names
nodes = @idpsso_descriptor.xpath(
"saml:Attribute/@Name",
NAMESPACES
)
nodes.map(&:value)
end
def merge_certificates_into(parsed_metadata)
if (certificates.size == 1 &&
(certificates_has_one('signing') || certificates_has_one('encryption'))) ||
(certificates_has_one('signing') && certificates_has_one('encryption') &&
certificates["signing"][0] == certificates["encryption"][0])
parsed_metadata[:idp_cert] = if certificates.key?("signing")
certificates["signing"][0]
else
certificates["encryption"][0]
end
parsed_metadata[:idp_cert_fingerprint] = fingerprint(
parsed_metadata[:idp_cert],
parsed_metadata[:idp_cert_fingerprint_algorithm]
)
end
# symbolize keys of certificates and pass it on
parsed_metadata[:idp_cert_multi] = certificates.transform_keys(&:to_sym)
end
def certificates_has_one(key)
certificates.key?(key) && certificates[key].size == 1
end
private
def first_ranked_text(nodes, priority = nil)
return unless nodes.any?
priority = Array(priority)
if priority.any?
values = nodes.map(&:text)
priority.detect { |candidate| values.include?(candidate) }
else
nodes.first.text
end
end
def first_ranked_value(nodes, priority = nil)
return unless nodes.any?
priority = Array(priority)
if priority.any?
values = nodes.map(&:value)
priority.detect { |candidate| values.include?(candidate) }
else
nodes.first.value
end
end
end
def merge_parsed_metadata_into(settings, parsed_metadata)
parsed_metadata.each do |key, value|
settings.send("#{key}=".to_sym, value)
end
settings
end
end
end