kl-ruby-saml 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (137) hide show
  1. checksums.yaml +7 -0
  2. data/.document +5 -0
  3. data/.gitignore +14 -0
  4. data/.travis.yml +17 -0
  5. data/Gemfile +9 -0
  6. data/LICENSE +19 -0
  7. data/README.md +575 -0
  8. data/Rakefile +41 -0
  9. data/changelog.md +75 -0
  10. data/gemfiles/nokogiri-1.5.gemfile +5 -0
  11. data/lib/onelogin/ruby-saml.rb +17 -0
  12. data/lib/onelogin/ruby-saml/attribute_service.rb +57 -0
  13. data/lib/onelogin/ruby-saml/attributes.rb +128 -0
  14. data/lib/onelogin/ruby-saml/authrequest.rb +156 -0
  15. data/lib/onelogin/ruby-saml/http_error.rb +7 -0
  16. data/lib/onelogin/ruby-saml/idp_metadata_parser.rb +161 -0
  17. data/lib/onelogin/ruby-saml/logging.rb +30 -0
  18. data/lib/onelogin/ruby-saml/logoutrequest.rb +131 -0
  19. data/lib/onelogin/ruby-saml/logoutresponse.rb +241 -0
  20. data/lib/onelogin/ruby-saml/metadata.rb +123 -0
  21. data/lib/onelogin/ruby-saml/response.rb +722 -0
  22. data/lib/onelogin/ruby-saml/saml_message.rb +158 -0
  23. data/lib/onelogin/ruby-saml/settings.rb +165 -0
  24. data/lib/onelogin/ruby-saml/slo_logoutrequest.rb +258 -0
  25. data/lib/onelogin/ruby-saml/slo_logoutresponse.rb +136 -0
  26. data/lib/onelogin/ruby-saml/utils.rb +172 -0
  27. data/lib/onelogin/ruby-saml/validation_error.rb +7 -0
  28. data/lib/onelogin/ruby-saml/version.rb +5 -0
  29. data/lib/ruby-saml.rb +1 -0
  30. data/lib/schemas/saml-schema-assertion-2.0.xsd +283 -0
  31. data/lib/schemas/saml-schema-authn-context-2.0.xsd +23 -0
  32. data/lib/schemas/saml-schema-authn-context-types-2.0.xsd +821 -0
  33. data/lib/schemas/saml-schema-metadata-2.0.xsd +337 -0
  34. data/lib/schemas/saml-schema-protocol-2.0.xsd +302 -0
  35. data/lib/schemas/sstc-metadata-attr.xsd +35 -0
  36. data/lib/schemas/sstc-saml-attribute-ext.xsd +25 -0
  37. data/lib/schemas/sstc-saml-metadata-algsupport-v1.0.xsd +41 -0
  38. data/lib/schemas/sstc-saml-metadata-ui-v1.0.xsd +89 -0
  39. data/lib/schemas/xenc-schema.xsd +136 -0
  40. data/lib/schemas/xml.xsd +287 -0
  41. data/lib/schemas/xmldsig-core-schema.xsd +309 -0
  42. data/lib/xml_security.rb +358 -0
  43. data/ruby-saml.gemspec +57 -0
  44. data/test/certificates/certificate1 +12 -0
  45. data/test/certificates/certificate_without_head_foot +1 -0
  46. data/test/certificates/formatted_certificate +14 -0
  47. data/test/certificates/formatted_private_key +12 -0
  48. data/test/certificates/formatted_rsa_private_key +12 -0
  49. data/test/certificates/invalid_certificate1 +1 -0
  50. data/test/certificates/invalid_certificate2 +1 -0
  51. data/test/certificates/invalid_certificate3 +12 -0
  52. data/test/certificates/invalid_private_key1 +1 -0
  53. data/test/certificates/invalid_private_key2 +1 -0
  54. data/test/certificates/invalid_private_key3 +10 -0
  55. data/test/certificates/invalid_rsa_private_key1 +1 -0
  56. data/test/certificates/invalid_rsa_private_key2 +1 -0
  57. data/test/certificates/invalid_rsa_private_key3 +10 -0
  58. data/test/certificates/ruby-saml.crt +14 -0
  59. data/test/certificates/ruby-saml.key +15 -0
  60. data/test/idp_metadata_parser_test.rb +95 -0
  61. data/test/logging_test.rb +62 -0
  62. data/test/logout_requests/invalid_slo_request.xml +6 -0
  63. data/test/logout_requests/slo_request.xml +4 -0
  64. data/test/logout_requests/slo_request.xml.base64 +1 -0
  65. data/test/logout_requests/slo_request_deflated.xml.base64 +1 -0
  66. data/test/logout_requests/slo_request_with_session_index.xml +5 -0
  67. data/test/logout_responses/logoutresponse_fixtures.rb +67 -0
  68. data/test/logoutrequest_test.rb +211 -0
  69. data/test/logoutresponse_test.rb +258 -0
  70. data/test/metadata_test.rb +203 -0
  71. data/test/request_test.rb +282 -0
  72. data/test/response_test.rb +1094 -0
  73. data/test/responses/adfs_response_sha1.xml +46 -0
  74. data/test/responses/adfs_response_sha256.xml +46 -0
  75. data/test/responses/adfs_response_sha384.xml +46 -0
  76. data/test/responses/adfs_response_sha512.xml +46 -0
  77. data/test/responses/adfs_response_xmlns.xml +45 -0
  78. data/test/responses/attackxee.xml +13 -0
  79. data/test/responses/idp_descriptor.xml +3 -0
  80. data/test/responses/invalids/invalid_audience.xml.base64 +1 -0
  81. data/test/responses/invalids/invalid_issuer_assertion.xml.base64 +1 -0
  82. data/test/responses/invalids/invalid_issuer_message.xml.base64 +1 -0
  83. data/test/responses/invalids/invalid_signature_position.xml.base64 +1 -0
  84. data/test/responses/invalids/invalid_subjectconfirmation_inresponse.xml.base64 +1 -0
  85. data/test/responses/invalids/invalid_subjectconfirmation_nb.xml.base64 +1 -0
  86. data/test/responses/invalids/invalid_subjectconfirmation_noa.xml.base64 +1 -0
  87. data/test/responses/invalids/invalid_subjectconfirmation_recipient.xml.base64 +1 -0
  88. data/test/responses/invalids/multiple_assertions.xml.base64 +2 -0
  89. data/test/responses/invalids/multiple_signed.xml.base64 +1 -0
  90. data/test/responses/invalids/no_id.xml.base64 +1 -0
  91. data/test/responses/invalids/no_saml2.xml.base64 +1 -0
  92. data/test/responses/invalids/no_signature.xml.base64 +1 -0
  93. data/test/responses/invalids/no_status.xml.base64 +1 -0
  94. data/test/responses/invalids/no_status_code.xml.base64 +1 -0
  95. data/test/responses/invalids/no_subjectconfirmation_data.xml.base64 +1 -0
  96. data/test/responses/invalids/no_subjectconfirmation_method.xml.base64 +1 -0
  97. data/test/responses/invalids/response_encrypted_attrs.xml.base64 +1 -0
  98. data/test/responses/invalids/response_invalid_signed_element.xml.base64 +1 -0
  99. data/test/responses/invalids/status_code_responder.xml.base64 +1 -0
  100. data/test/responses/invalids/status_code_responer_and_msg.xml.base64 +1 -0
  101. data/test/responses/no_signature_ns.xml +48 -0
  102. data/test/responses/open_saml_response.xml +56 -0
  103. data/test/responses/response_assertion_wrapped.xml.base64 +93 -0
  104. data/test/responses/response_encrypted_nameid.xml.base64 +1 -0
  105. data/test/responses/response_eval.xml +7 -0
  106. data/test/responses/response_no_cert_and_encrypted_attrs.xml +29 -0
  107. data/test/responses/response_unsigned_xml_base64 +1 -0
  108. data/test/responses/response_with_ampersands.xml +139 -0
  109. data/test/responses/response_with_ampersands.xml.base64 +93 -0
  110. data/test/responses/response_with_multiple_attribute_values.xml +67 -0
  111. data/test/responses/response_with_saml2_namespace.xml.base64 +102 -0
  112. data/test/responses/response_with_signed_assertion.xml.base64 +66 -0
  113. data/test/responses/response_with_signed_assertion_2.xml.base64 +1 -0
  114. data/test/responses/response_with_undefined_recipient.xml.base64 +1 -0
  115. data/test/responses/response_without_attributes.xml.base64 +79 -0
  116. data/test/responses/response_wrapped.xml.base64 +150 -0
  117. data/test/responses/signed_message_encrypted_signed_assertion.xml.base64 +1 -0
  118. data/test/responses/signed_message_encrypted_unsigned_assertion.xml.base64 +1 -0
  119. data/test/responses/simple_saml_php.xml +71 -0
  120. data/test/responses/starfield_response.xml.base64 +1 -0
  121. data/test/responses/test_sign.xml +43 -0
  122. data/test/responses/unsigned_message_aes128_encrypted_signed_assertion.xml.base64 +1 -0
  123. data/test/responses/unsigned_message_aes192_encrypted_signed_assertion.xml.base64 +1 -0
  124. data/test/responses/unsigned_message_aes256_encrypted_signed_assertion.xml.base64 +1 -0
  125. data/test/responses/unsigned_message_des192_encrypted_signed_assertion.xml.base64 +1 -0
  126. data/test/responses/unsigned_message_encrypted_assertion_without_saml_namespace.xml.base64 +1 -0
  127. data/test/responses/unsigned_message_encrypted_signed_assertion.xml.base64 +1 -0
  128. data/test/responses/unsigned_message_encrypted_unsigned_assertion.xml.base64 +1 -0
  129. data/test/responses/valid_response.xml.base64 +1 -0
  130. data/test/saml_message_test.rb +56 -0
  131. data/test/settings_test.rb +218 -0
  132. data/test/slo_logoutrequest_test.rb +275 -0
  133. data/test/slo_logoutresponse_test.rb +185 -0
  134. data/test/test_helper.rb +252 -0
  135. data/test/utils_test.rb +145 -0
  136. data/test/xml_security_test.rb +329 -0
  137. metadata +415 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: dca6cdd7235817f6c743cdc5772c7e789fa4557e
4
+ data.tar.gz: 9b8636dfd9eabd7a20a66d4290a607978ad055c3
5
+ SHA512:
6
+ metadata.gz: 9ade3f457cb68de71766f80d21c84785487505224431d92869e420fe16d562a87fe7503227291fb5ae8aebc75c8db1b522914a78c243c34aa2780a2558c0f025
7
+ data.tar.gz: 8b384251a915cdbf9bc0fe3dab4f0426172584a5ec86cf0cec096368986d31e75bb92f2a6eddc9f281a87406fc50988748221747f5ae787da42f16902bc46765
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
data/.gitignore ADDED
@@ -0,0 +1,14 @@
1
+ *.sw?
2
+ .DS_Store
3
+ coverage
4
+ rdoc
5
+ pkg
6
+ Gemfile.lock
7
+ gemfiles/*.lock
8
+ .idea/*
9
+ lib/Lib.iml
10
+ test/Test.iml
11
+ .rvmrc
12
+ *.gem
13
+ .bundle
14
+ *.patch
data/.travis.yml ADDED
@@ -0,0 +1,17 @@
1
+ language: ruby
2
+ rvm:
3
+ - 1.8.7
4
+ - 1.9.3
5
+ - 2.0.0
6
+ - 2.1.5
7
+ - 2.2.0
8
+ - ree
9
+ gemfile:
10
+ - Gemfile
11
+ - gemfiles/nokogiri-1.5.gemfile
12
+ matrix:
13
+ exclude:
14
+ - rvm: 1.8.7
15
+ gemfile: Gemfile
16
+ - rvm: ree
17
+ gemfile: Gemfile
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ #
2
+ # Please keep this file alphabetized and organized
3
+ #
4
+ source 'https://rubygems.org'
5
+
6
+ gemspec
7
+
8
+ gem 'json'
9
+ gem 'timecop'
data/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2010-2015 OneLogin, LLC
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,575 @@
1
+ # Ruby SAML [![Build Status](https://secure.travis-ci.org/onelogin/ruby-saml.png)](http://travis-ci.org/onelogin/ruby-saml) [![Coverage Status](https://coveralls.io/repos/onelogin/ruby-saml/badge.svg?branch=master%0A)](https://coveralls.io/r/onelogin/ruby-saml?branch=master%0A) [![Gem Version](https://badge.fury.io/rb/ruby-saml.svg)](http://badge.fury.io/rb/ruby-saml)
2
+
3
+
4
+ ## Updating from 0.9.x to 1.0.X
5
+
6
+ Version `1.0` is a recommended update for all Ruby SAML users as it includes security fixes.
7
+
8
+ Version `1.0` adds security improvements like entity expansion limitation, more SAML message validations, and other important improvements like decrypt support.
9
+
10
+ For more details, please review [the changelog](changelog.md).
11
+
12
+ ### Important Changes
13
+ Please note the `get_idp_metadata` method raises an exception when it is not able to fetch the idp metadata, so review your integration if you are using this functionality.
14
+
15
+ ## Updating from 0.8.x to 0.9.x
16
+ Version `0.9` adds many new features and improvements.
17
+
18
+ ## Updating from 0.7.x to 0.8.x
19
+ Version `0.8.x` changes the namespace of the gem from `OneLogin::Saml` to `OneLogin::RubySaml`. Please update your implementations of the gem accordingly.
20
+
21
+ ## Overview
22
+
23
+ The Ruby SAML library is for implementing the client side of a SAML authorization, i.e. it provides a means for managing authorization initialization and confirmation requests from identity providers.
24
+
25
+ SAML authorization is a two step process and you are expected to implement support for both.
26
+
27
+ We created a demo project for Rails4 that uses the latest version of this library: [ruby-saml-example](https://github.com/onelogin/ruby-saml-example)
28
+
29
+ ### Supported versions of Ruby
30
+ * 1.8.7
31
+ * 1.9.x
32
+ * 2.1.x
33
+ * 2.2.x
34
+
35
+ ## Adding Features, Pull Requests
36
+ * Fork the repository
37
+ * Make your feature addition or bug fix
38
+ * Add tests for your new features. This is important so we don't break any features in a future version unintentionally.
39
+ * Ensure all tests pass.
40
+ * Do not change rakefile, version, or history.
41
+ * Open a pull request, following [this template](https://gist.github.com/Lordnibbler/11002759).
42
+
43
+ ## Getting Started
44
+ In order to use the toolkit you will need to install the gem (either manually or using Bundler), and require the library in your Ruby application:
45
+
46
+ Using `Gemfile`
47
+
48
+ ```ruby
49
+ # latest stable
50
+ gem 'ruby-saml', '~> 1.0.0'
51
+
52
+ # or track master for bleeding-edge
53
+ gem 'ruby-saml', :github => 'onelogin/ruby-saml'
54
+ ```
55
+
56
+ Using RubyGems
57
+
58
+ ```sh
59
+ gem install ruby-saml
60
+ ```
61
+
62
+ When requiring the gem, you can add the whole toolkit
63
+ ```ruby
64
+ require 'onelogin/ruby-saml'
65
+ ```
66
+
67
+ or just the required components individually:
68
+
69
+ ```ruby
70
+ require 'onelogin/ruby-saml/authrequest'
71
+ ```
72
+
73
+ ### Installation on Ruby 1.8.7
74
+
75
+ This gem has a dependency on Nokogiri, which dropped support for Ruby 1.8.x in Nokogiri 1.6. When installing this gem on Ruby 1.8.7, you will need to make sure a version of Nokogiri prior to 1.6 is installed or specified if it hasn't been already.
76
+
77
+ Using `Gemfile`
78
+
79
+ ```ruby
80
+ gem 'nokogiri', '~> 1.5.10'
81
+ ```
82
+
83
+ Using RubyGems
84
+
85
+ ```sh
86
+ gem install nokogiri --version '~> 1.5.10'
87
+ ````
88
+
89
+ ### Configuring Logging
90
+
91
+ When troubleshooting SAML integration issues, you will find it extremely helpful to examine the
92
+ output of this gem's business logic. By default, log messages are emitted to RAILS_DEFAULT_LOGGER
93
+ when the gem is used in a Rails context, and to STDOUT when the gem is used outside of Rails.
94
+
95
+ To override the default behavior and control the destination of log messages, provide
96
+ a ruby Logger object to the gem's logging singleton:
97
+
98
+ ```ruby
99
+ OneLogin::RubySaml::Logging.logger = Logger.new(File.open('/var/log/ruby-saml.log', 'w')
100
+ ```
101
+
102
+ ## The Initialization Phase
103
+
104
+ This is the first request you will get from the identity provider. It will hit your application at a specific URL (that you've announced as being your SAML initialization point). The response to this initialization, is a redirect back to the identity provider, which can look something like this (ignore the saml_settings method call for now):
105
+
106
+ ```ruby
107
+ def init
108
+ request = OneLogin::RubySaml::Authrequest.new
109
+ redirect_to(request.create(saml_settings))
110
+ end
111
+ ```
112
+
113
+ Once you've redirected back to the identity provider, it will ensure that the user has been authorized and redirect back to your application for final consumption, this is can look something like this (the authorize_success and authorize_failure methods are specific to your application):
114
+
115
+ ```ruby
116
+ def consume
117
+ response = OneLogin::RubySaml::Response.new(params[:SAMLResponse], :settings => saml_settings)
118
+
119
+ # We validate the SAML Response and check if the user already exists in the system
120
+ if response.is_valid?
121
+ # authorize_success, log the user
122
+ session[:userid] = response.nameid
123
+ session[:attributes] = response.attributes
124
+ else
125
+ authorize_failure # This method shows an error message
126
+ end
127
+ end
128
+ ```
129
+
130
+ In the above there are a few assumptions in place, one being that the response.nameid is an email address. This is all handled with how you specify the settings that are in play via the saml_settings method. That could be implemented along the lines of this:
131
+
132
+ If the assertion of the SAMLResponse is not encrypted, you can initialize the Response without the :settings parameter and set it later,
133
+
134
+ ```
135
+ response = OneLogin::RubySaml::Response.new(params[:SAMLResponse])
136
+ response.settings = saml_settings
137
+ ```
138
+ but if the SAMLResponse contains an encrypted assertion, you need to provide the settings in the
139
+ initialize method in order to be able to obtain the decrypted assertion, using the service provider private key in order to decrypt.
140
+ If you don't know what expect, use always the first proposed way (always set the settings on the initialize method).
141
+
142
+ ```ruby
143
+ def saml_settings
144
+ settings = OneLogin::RubySaml::Settings.new
145
+
146
+ settings.assertion_consumer_service_url = "http://#{request.host}/saml/consume"
147
+ settings.issuer = "http://#{request.host}/saml/metadata"
148
+ settings.idp_sso_target_url = "https://app.onelogin.com/saml/metadata/#{OneLoginAppId}"
149
+ settings.idp_entity_id = "https://app.onelogin.com/saml/metadata/#{OneLoginAppId}"
150
+ settings.idp_sso_target_url = "https://app.onelogin.com/trust/saml2/http-post/sso/#{OneLoginAppId}"
151
+ settings.idp_slo_target_url = "https://app.onelogin.com/trust/saml2/http-redirect/slo/#{OneLoginAppId}"
152
+ settings.idp_cert_fingerprint = OneLoginAppCertFingerPrint
153
+ settings.idp_cert_fingerprint_algorithm = "http://www.w3.org/2000/09/xmldsig#sha1"
154
+ settings.name_identifier_format = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
155
+
156
+ # Optional for most SAML IdPs
157
+ settings.authn_context = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
158
+
159
+ # Optional bindings (defaults to Redirect for logout POST for acs)
160
+ settings.assertion_consumer_service_binding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
161
+ settings.assertion_consumer_logout_service_binding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
162
+
163
+ settings
164
+ end
165
+ ```
166
+
167
+ What's left at this point, is to wrap it all up in a controller and point the initialization and consumption URLs in OneLogin at that. A full controller example could look like this:
168
+
169
+ ```ruby
170
+ # This controller expects you to use the URLs /saml/init and /saml/consume in your OneLogin application.
171
+ class SamlController < ApplicationController
172
+ def init
173
+ request = OneLogin::RubySaml::Authrequest.new
174
+ redirect_to(request.create(saml_settings))
175
+ end
176
+
177
+ def consume
178
+ response = OneLogin::RubySaml::Response.new(params[:SAMLResponse])
179
+ response.settings = saml_settings
180
+
181
+ # We validate the SAML Response and check if the user already exists in the system
182
+ if response.is_valid?
183
+ # authorize_success, log the user
184
+ session[:userid] = response.nameid
185
+ session[:attributes] = response.attributes
186
+ else
187
+ authorize_failure # This method shows an error message
188
+ end
189
+ end
190
+
191
+ private
192
+
193
+ def saml_settings
194
+ settings = OneLogin::RubySaml::Settings.new
195
+
196
+ settings.assertion_consumer_service_url = "http://#{request.host}/saml/consume"
197
+ settings.issuer = "http://#{request.host}/saml/metadata"
198
+ settings.idp_sso_target_url = "https://app.onelogin.com/saml/signon/#{OneLoginAppId}"
199
+ settings.idp_cert_fingerprint = OneLoginAppCertFingerPrint
200
+ settings.name_identifier_format = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
201
+
202
+ # Optional for most SAML IdPs
203
+ settings.authn_context = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
204
+
205
+ # Optional. Describe according to IdP specification (if supported) which attributes the SP desires to receive in SAMLResponse.
206
+ settings.attributes_index = 5
207
+ # Optional. Describe an attribute consuming service for support of additional attributes.
208
+ settings.attribute_consuming_service.configure do
209
+ service_name "Service"
210
+ service_index 5
211
+ add_attribute :name => "Name", :name_format => "Name Format", :friendly_name => "Friendly Name"
212
+ end
213
+
214
+ settings
215
+ end
216
+ end
217
+ ```
218
+ ## Metadata Based Configuration
219
+
220
+ The method above requires a little extra work to manually specify attributes about the IdP. (And your SP application) There's an easier method -- use a metadata exchange. Metadata is just an XML file that defines the capabilities of both the IdP and the SP application. It also contains the X.509 public
221
+ key certificates which add to the trusted relationship. The IdP administrator can also configure custom settings for an SP based on the metadata.
222
+
223
+ Using ```idp_metadata_parser.parse_remote``` IdP metadata will be added to the settings withouth further ado.
224
+
225
+ ```ruby
226
+ def saml_settings
227
+
228
+ idp_metadata_parser = OneLogin::RubySaml::IdpMetadataParser.new
229
+ # Returns OneLogin::RubySaml::Settings prepopulated with idp metadata
230
+ settings = idp_metadata_parser.parse_remote("https://example.com/auth/saml2/idp/metadata")
231
+
232
+ settings.assertion_consumer_service_url = "http://#{request.host}/saml/consume"
233
+ settings.issuer = "http://#{request.host}/saml/metadata"
234
+ settings.name_identifier_format = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
235
+ # Optional for most SAML IdPs
236
+ settings.authn_context = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
237
+
238
+ settings
239
+ end
240
+ ```
241
+ The following attributes are set:
242
+ * id_sso_target_url
243
+ * idp_slo_target_url
244
+ * id_cert_fingerpint
245
+
246
+ If you are using saml:AttributeStatement to transfer metadata, like the user name, you can access all the attributes through response.attributes. It contains all the saml:AttributeStatement with its 'Name' as a indifferent key the one/more saml:AttributeValue as value. The value returned depends on the value of the
247
+ `single_value_compatibility` (when activate, only one value returned, the first one)
248
+
249
+ ```ruby
250
+ response = OneLogin::RubySaml::Response.new(params[:SAMLResponse])
251
+ response.settings = saml_settings
252
+
253
+ response.attributes[:username]
254
+ ```
255
+
256
+ Imagine this saml:AttributeStatement
257
+
258
+ ```xml
259
+ <saml:AttributeStatement>
260
+ <saml:Attribute Name="uid">
261
+ <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">demo</saml:AttributeValue>
262
+ </saml:Attribute>
263
+ <saml:Attribute Name="another_value">
264
+ <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">value1</saml:AttributeValue>
265
+ <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">value2</saml:AttributeValue>
266
+ </saml:Attribute>
267
+ <saml:Attribute Name="role">
268
+ <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">role1</saml:AttributeValue>
269
+ </saml:Attribute>
270
+ <saml:Attribute Name="role">
271
+ <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">role2</saml:AttributeValue>
272
+ <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">role3</saml:AttributeValue>
273
+ </saml:Attribute>
274
+ <saml:Attribute Name="attribute_with_nil_value">
275
+ <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
276
+ </saml:Attribute>
277
+ <saml:Attribute Name="attribute_with_nils_and_empty_strings">
278
+ <saml:AttributeValue/>
279
+ <saml:AttributeValue>valuePresent</saml:AttributeValue>
280
+ <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
281
+ <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="1"/>
282
+ </saml:Attribute>
283
+ </saml:AttributeStatement>
284
+ ```
285
+
286
+ ```ruby
287
+ pp(response.attributes) # is an OneLogin::RubySaml::Attributes object
288
+ # => @attributes=
289
+ {"uid"=>["demo"],
290
+ "another_value"=>["value1", "value2"],
291
+ "role"=>["role1", "role2", "role3"],
292
+ "attribute_with_nil_value"=>[nil],
293
+ "attribute_with_nils_and_empty_strings"=>["", "valuePresent", nil, nil]}>
294
+
295
+ # Active single_value_compatibility
296
+ OneLogin::RubySaml::Attributes.single_value_compatibility = true
297
+
298
+ pp(response.attributes[:uid])
299
+ # => "demo"
300
+
301
+ pp(response.attributes[:role])
302
+ # => "role1"
303
+
304
+ pp(response.attributes.single(:role))
305
+ # => "role1"
306
+
307
+ pp(response.attributes.multi(:role))
308
+ # => ["role1", "role2", "role3"]
309
+
310
+ pp(response.attributes[:attribute_with_nil_value])
311
+ # => nil
312
+
313
+ pp(response.attributes[:attribute_with_nils_and_empty_strings])
314
+ # => ""
315
+
316
+ pp(response.attributes[:not_exists])
317
+ # => nil
318
+
319
+ pp(response.attributes.single(:not_exists))
320
+ # => nil
321
+
322
+ pp(response.attributes.multi(:not_exists))
323
+ # => nil
324
+
325
+ # Deactive single_value_compatibility
326
+ OneLogin::RubySaml::Attributes.single_value_compatibility = false
327
+
328
+ pp(response.attributes[:uid])
329
+ # => ["demo"]
330
+
331
+ pp(response.attributes[:role])
332
+ # => ["role1", "role2", "role3"]
333
+
334
+ pp(response.attributes.single(:role))
335
+ # => "role1"
336
+
337
+ pp(response.attributes.multi(:role))
338
+ # => ["role1", "role2", "role3"]
339
+
340
+ pp(response.attributes[:attribute_with_nil_value])
341
+ # => [nil]
342
+
343
+ pp(response.attributes[:attribute_with_nils_and_empty_strings])
344
+ # => ["", "valuePresent", nil, nil]
345
+
346
+ pp(response.attributes[:not_exists])
347
+ # => nil
348
+
349
+ pp(response.attributes.single(:not_exists))
350
+ # => nil
351
+
352
+ pp(response.attributes.multi(:not_exists))
353
+ # => nil
354
+ ```
355
+
356
+ The saml:AuthnContextClassRef of the AuthNRequest can be provided by `settings.authn_context` , possible values are described at [SAMLAuthnCxt]. The comparison method can be set using the parameter `settings.authn_context_comparison` (the possible values are: 'exact', 'better', 'maximum' and 'minimum'), 'exact' is the default value.
357
+ If we want to add a saml:AuthnContextDeclRef, define a `settings.authn_context_decl_ref`.
358
+
359
+
360
+ ## Signing
361
+
362
+ The Ruby Toolkit supports 2 different kinds of signature: Embeded and as GET parameter
363
+
364
+ In order to be able to sign we need first to define the private key and the public cert of the service provider
365
+
366
+ ```ruby
367
+ settings.certificate = "CERTIFICATE TEXT WITH HEAD AND FOOT"
368
+ settings.private_key = "PRIVATE KEY TEXT WITH HEAD AND FOOT"
369
+ ```
370
+
371
+ The settings related to sign are stored in the `security` attribute of the settings:
372
+
373
+ ```ruby
374
+ settings.security[:authn_requests_signed] = true # Enable or not signature on AuthNRequest
375
+ settings.security[:logout_requests_signed] = true # Enable or not signature on Logout Request
376
+ settings.security[:logout_responses_signed] = true # Enable or not signature on Logout Response
377
+ settings.security[:metadata_signed] = true # Enable or not signature on Metadata
378
+
379
+ settings.security[:digest_method] = XMLSecurity::Document::SHA1
380
+ settings.security[:signature_method] = XMLSecurity::Document::RSA_SHA1
381
+
382
+ # Embeded signature or HTTP GET parameter signature
383
+ # Note that metadata signature is always embedded regardless of this value.
384
+ settings.security[:embed_sign] = false
385
+ ```
386
+
387
+ Notice that the RelayState parameter is used when creating the Signature on the HTTP-Redirect Binding,
388
+ remember to provide it to the Signature builder if you are sending a GET RelayState parameter or
389
+ Signature validation process will fail at the Identity Provider.
390
+
391
+ The Service Provider will sign the request/responses with its private key.
392
+ The Identity Provider will validate the sign of the received request/responses with the public x500 cert of the
393
+ Service Provider.
394
+
395
+ Notice that this toolkit uses 'settings.certificate' and 'settings.private_key' for the sign and the decrypt process.
396
+
397
+ Enable/disable the soft mode by the settings.soft parameter. When is set false, the saml validations errors will raise an exception.
398
+
399
+ ## Decrypting
400
+
401
+ The Ruby Toolkit supports EncryptedAssertion.
402
+
403
+ In order to be able to decrypt a SAML Response that contains a EncryptedAssertion we need first to define the private key and the public cert of the service provider, and share this with the Identity Provider.
404
+
405
+ ```ruby
406
+ settings.certificate = "CERTIFICATE TEXT WITH HEAD AND FOOT"
407
+ settings.private_key = "PRIVATE KEY TEXT WITH HEAD AND FOOT"
408
+ ```
409
+
410
+ The Identity Provider will encrypt the Assertion with the public cert of the Service Provider.
411
+ The Service Provider will decrypt the EncryptedAssertion with its private key.
412
+
413
+ Notice that this toolkit uses 'settings.certificate' and 'settings.private_key' for the sign and the decrypt process.
414
+
415
+ ## Single Log Out
416
+
417
+ The Ruby Toolkit supports SP-initiated Single Logout and IdP-Initiated Single Logout.
418
+
419
+ Here is an example that we could add to our previous controller to generate and send a SAML Logout Request to the IdP
420
+
421
+ ```ruby
422
+ # Create a SP initiated SLO
423
+ def sp_logout_request
424
+ # LogoutRequest accepts plain browser requests w/o paramters
425
+ settings = saml_settings
426
+
427
+ if settings.idp_slo_target_url.nil?
428
+ logger.info "SLO IdP Endpoint not found in settings, executing then a normal logout'"
429
+ delete_session
430
+ else
431
+
432
+ # Since we created a new SAML request, save the transaction_id
433
+ # to compare it with the response we get back
434
+ logout_request = OneLogin::RubySaml::Logoutrequest.new()
435
+ session[:transaction_id] = logout_request.uuid
436
+ logger.info "New SP SLO for userid '#{session[:userid]}' transactionid '#{session[:transaction_id]}'"
437
+
438
+ if settings.name_identifier_value.nil?
439
+ settings.name_identifier_value = session[:userid]
440
+ end
441
+
442
+ relayState = url_for controller: 'saml', action: 'index'
443
+ redirect_to(logout_request.create(settings, :RelayState => relayState))
444
+ end
445
+ end
446
+ ```
447
+
448
+ and this method process the SAML Logout Response sent by the IdP as reply of the SAML Logout Request
449
+
450
+ ```ruby
451
+ # After sending an SP initiated LogoutRequest to the IdP, we need to accept
452
+ # the LogoutResponse, verify it, then actually delete our session.
453
+ def process_logout_response
454
+ settings = Account.get_saml_settings
455
+
456
+ if session.has_key? :transation_id
457
+ logout_response = OneLogin::RubySaml::Logoutresponse.new(params[:SAMLResponse], settings, :matches_request_id => session[:transation_id])
458
+ else
459
+ logout_response = OneLogin::RubySaml::Logoutresponse.new(params[:SAMLResponse], settings)
460
+ end
461
+
462
+ logger.info "LogoutResponse is: #{logout_response.to_s}"
463
+
464
+ # Validate the SAML Logout Response
465
+ if not logout_response.validate
466
+ logger.error "The SAML Logout Response is invalid"
467
+ else
468
+ # Actually log out this session
469
+ if logout_response.success?
470
+ logger.info "Delete session for '#{session[:userid]}'"
471
+ delete_session
472
+ end
473
+ end
474
+ end
475
+
476
+ # Delete a user's session.
477
+ def delete_session
478
+ session[:userid] = nil
479
+ session[:attributes] = nil
480
+ end
481
+ ```
482
+
483
+ Here is an example that we could add to our previous controller to process a SAML Logout Request from the IdP and reply a SAML Logout Response to the IdP
484
+
485
+ ```ruby
486
+ # Method to handle IdP initiated logouts
487
+ def idp_logout_request
488
+ settings = Account.get_saml_settings
489
+ logout_request = OneLogin::RubySaml::SloLogoutrequest.new(params[:SAMLRequest])
490
+ if !logout_request.is_valid?
491
+ logger.error "IdP initiated LogoutRequest was not valid!"
492
+ render :inline => logger.error
493
+ end
494
+ logger.info "IdP initiated Logout for #{logout_request.name_id}"
495
+
496
+ # Actually log out this session
497
+ delete_session
498
+
499
+ # Generate a response to the IdP.
500
+ logout_request_id = logout_request.id
501
+ logout_response = OneLogin::RubySaml::SloLogoutresponse.new.create(settings, logout_request_id, nil, :RelayState => params[:RelayState])
502
+ redirect_to logout_response
503
+ end
504
+ ```
505
+
506
+ All the mentioned methods could be handled in a unique view:
507
+
508
+ ```ruby
509
+ # Trigger SP and IdP initiated Logout requests
510
+ def logout
511
+ # If we're given a logout request, handle it in the IdP logout initiated method
512
+ if params[:SAMLRequest]
513
+ return idp_logout_request
514
+ # We've been given a response back from the IdP, process it
515
+ elsif params[:SAMLResponse]
516
+ return process_logout_response
517
+ # Initiate SLO (send Logout Request)
518
+ else
519
+ return sp_logout_request
520
+ end
521
+ end
522
+ ```
523
+
524
+
525
+
526
+ ## Service Provider Metadata
527
+
528
+ To form a trusted pair relationship with the IdP, the SP (you) need to provide metadata XML
529
+ to the IdP for various good reasons. (Caching, certificate lookups, relaying party permissions, etc)
530
+
531
+ The class `OneLogin::RubySaml::Metadata` takes care of this by reading the Settings and returning XML. All you have to do is add a controller to return the data, then give this URL to the IdP administrator.
532
+
533
+ The metdata will be polled by the IdP every few minutes, so updating your settings should propagate
534
+ to the IdP settings.
535
+
536
+ ```ruby
537
+ class SamlController < ApplicationController
538
+ # ... the rest of your controller definitions ...
539
+ def metadata
540
+ settings = Account.get_saml_settings
541
+ meta = OneLogin::RubySaml::Metadata.new
542
+ render :xml => meta.generate(settings), :content_type => "application/samlmetadata+xml"
543
+ end
544
+ end
545
+ ```
546
+
547
+ ## Clock Drift
548
+
549
+ Server clocks tend to drift naturally. If during validation of the response you get the error "Current time is earlier than NotBefore condition" then this may be due to clock differences between your system and that of the Identity Provider.
550
+
551
+ First, ensure that both systems synchronize their clocks, using for example the industry standard [Network Time Protocol (NTP)](http://en.wikipedia.org/wiki/Network_Time_Protocol).
552
+
553
+ Even then you may experience intermittent issues though, because the clock of the Identity Provider may drift slightly ahead of your system clocks. To allow for a small amount of clock drift you can initialize the response passing in an option named `:allowed_clock_drift`. Its value must be given in a number (and/or fraction) of seconds. The value given is added to the current time at which the response is validated before it's tested against the `NotBefore` assertion. For example:
554
+
555
+ ```ruby
556
+ response = OneLogin::RubySaml::Response.new(params[:SAMLResponse], :allowed_clock_drift => 1.second)
557
+ ```
558
+
559
+ Make sure to keep the value as comfortably small as possible to keep security risks to a minimum.
560
+
561
+ ## Attribute Service
562
+
563
+ To request attributes from the IdP the SP needs to provide an attribute service within it's metadata and reference the index in the assertion.
564
+
565
+ ```ruby
566
+ settings = OneLogin::RubySaml::Settings.new
567
+
568
+ settings.attributes_index = 5
569
+ settings.attribute_consuming_service.configure do
570
+ service_name "Service"
571
+ service_index 5
572
+ add_attribute :name => "Name", :name_format => "Name Format", :friendly_name => "Friendly Name"
573
+ add_attribute :name => "Another Attribute", :name_format => "Name Format", :friendly_name => "Friendly Name", :attribute_value => "Attribute Value"
574
+ end
575
+ ```