ruby-saml-bm 0.6.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (43) hide show
  1. data/Gemfile +12 -0
  2. data/Gemfile.lock +51 -0
  3. data/LICENSE +19 -0
  4. data/README.md +126 -0
  5. data/Rakefile +41 -0
  6. data/lib/onelogin/ruby-saml-bm/authrequest.rb +79 -0
  7. data/lib/onelogin/ruby-saml-bm/logging.rb +26 -0
  8. data/lib/onelogin/ruby-saml-bm/logoutrequest.rb +80 -0
  9. data/lib/onelogin/ruby-saml-bm/metadata.rb +47 -0
  10. data/lib/onelogin/ruby-saml-bm/response.rb +180 -0
  11. data/lib/onelogin/ruby-saml-bm/settings.rb +18 -0
  12. data/lib/onelogin/ruby-saml-bm/validation_error.rb +7 -0
  13. data/lib/onelogin/ruby-saml-bm/version.rb +5 -0
  14. data/lib/ruby-saml.rb +8 -0
  15. data/lib/schemas/saml20assertion_schema.xsd +283 -0
  16. data/lib/schemas/saml20protocol_schema.xsd +302 -0
  17. data/lib/schemas/xenc_schema.xsd +146 -0
  18. data/lib/schemas/xmldsig_schema.xsd +318 -0
  19. data/lib/xml_security.rb +165 -0
  20. data/ruby-saml-bm.gemspec +29 -0
  21. data/test/certificates/certificate1 +12 -0
  22. data/test/logoutrequest_test.rb +98 -0
  23. data/test/request_test.rb +53 -0
  24. data/test/response_test.rb +219 -0
  25. data/test/responses/adfs_response_sha1.xml +46 -0
  26. data/test/responses/adfs_response_sha256.xml +46 -0
  27. data/test/responses/adfs_response_sha384.xml +46 -0
  28. data/test/responses/adfs_response_sha512.xml +46 -0
  29. data/test/responses/no_signature_ns.xml +48 -0
  30. data/test/responses/open_saml_response.xml +56 -0
  31. data/test/responses/response1.xml.base64 +1 -0
  32. data/test/responses/response2.xml.base64 +79 -0
  33. data/test/responses/response3.xml.base64 +66 -0
  34. data/test/responses/response4.xml.base64 +93 -0
  35. data/test/responses/response5.xml.base64 +102 -0
  36. data/test/responses/response_with_ampersands.xml +139 -0
  37. data/test/responses/response_with_ampersands.xml.base64 +93 -0
  38. data/test/responses/simple_saml_php.xml +71 -0
  39. data/test/responses/wrapped_response_2.xml.base64 +150 -0
  40. data/test/settings_test.rb +43 -0
  41. data/test/test_helper.rb +66 -0
  42. data/test/xml_security_test.rb +123 -0
  43. metadata +165 -0
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ source 'http://rubygems.org'
2
+
3
+ gemspec
4
+
5
+ group :test do
6
+ gem "ruby-debug", "~> 0.10.4", :require => nil, :platforms => [:ruby_18, :jruby]
7
+ gem "debugger", "~> 1.1.1", :require => nil, :platforms => :ruby_19
8
+ gem "shoulda"
9
+ gem "rake"
10
+ gem "mocha"
11
+ gem "nokogiri"
12
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,51 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ ruby-saml-bm (0.6.0)
5
+ canonix (= 0.1.1)
6
+ nokogiri
7
+ uuid (~> 2.3)
8
+
9
+ GEM
10
+ remote: http://rubygems.org/
11
+ specs:
12
+ activesupport (3.2.9)
13
+ i18n (~> 0.6)
14
+ multi_json (~> 1.0)
15
+ canonix (0.1.1)
16
+ columnize (0.3.6)
17
+ i18n (0.6.1)
18
+ macaddr (1.6.1)
19
+ systemu (~> 2.5.0)
20
+ metaclass (0.0.1)
21
+ mocha (0.13.0)
22
+ metaclass (~> 0.0.1)
23
+ multi_json (1.3.7)
24
+ nokogiri (1.5.5)
25
+ nokogiri (1.5.5-java)
26
+ rake (10.0.2)
27
+ ruby-debug (0.10.4)
28
+ columnize (>= 0.1)
29
+ ruby-debug-base (~> 0.10.4.0)
30
+ ruby-debug-base (0.10.4-java)
31
+ shoulda (3.3.2)
32
+ shoulda-context (~> 1.0.1)
33
+ shoulda-matchers (~> 1.4.1)
34
+ shoulda-context (1.0.1)
35
+ shoulda-matchers (1.4.1)
36
+ activesupport (>= 3.0.0)
37
+ systemu (2.5.2)
38
+ uuid (2.3.6)
39
+ macaddr (~> 1.0)
40
+
41
+ PLATFORMS
42
+ java
43
+
44
+ DEPENDENCIES
45
+ debugger (~> 1.1.1)
46
+ mocha
47
+ nokogiri
48
+ rake
49
+ ruby-debug (~> 0.10.4)
50
+ ruby-saml-bm!
51
+ shoulda
data/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2010 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,126 @@
1
+ # Ruby SAML [![Build Status](https://secure.travis-ci.org/onelogin/ruby-saml-bm.png)](http://travis-ci.org/onelogin/ruby-saml-bm)
2
+
3
+ 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.
4
+
5
+ SAML authorization is a two step process and you are expected to implement support for both.
6
+
7
+ ## The initialization phase
8
+
9
+ 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):
10
+
11
+ ```ruby
12
+ def init
13
+ request = Onelogin::Saml::Authrequest.new
14
+ redirect_to(request.create(saml_settings))
15
+ end
16
+ ```
17
+
18
+ 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):
19
+
20
+ ```ruby
21
+ def consume
22
+ response = Onelogin::Saml::Response.new(params[:SAMLResponse])
23
+ response.settings = saml_settings
24
+
25
+ if response.is_valid? && user = current_account.users.find_by_email(response.name_id)
26
+ authorize_success(user)
27
+ else
28
+ authorize_failure(user)
29
+ end
30
+ end
31
+ ```
32
+
33
+ In the above there are a few assumptions in place, one being that the response.name_id 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:
34
+
35
+ ```ruby
36
+ def saml_settings
37
+ settings = Onelogin::Saml::Settings.new
38
+
39
+ settings.assertion_consumer_service_url = "http://#{request.host}/saml/finalize"
40
+ settings.issuer = request.host
41
+ settings.idp_sso_target_url = "https://app.onelogin.com/saml/signon/#{OneLoginAppId}"
42
+ settings.idp_cert_fingerprint = OneLoginAppCertFingerPrint
43
+ settings.name_identifier_format = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
44
+ # Optional for most SAML IdPs
45
+ settings.authn_context = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
46
+
47
+ settings
48
+ end
49
+ ```
50
+
51
+ 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:
52
+
53
+ ```ruby
54
+ # This controller expects you to use the URLs /saml/init and /saml/consume in your OneLogin application.
55
+ class SamlController < ApplicationController
56
+ def init
57
+ request = Onelogin::Saml::Authrequest.new
58
+ redirect_to(request.create(saml_settings))
59
+ end
60
+
61
+ def consume
62
+ response = Onelogin::Saml::Response.new(params[:SAMLResponse])
63
+ response.settings = saml_settings
64
+
65
+ if response.is_valid? && user = current_account.users.find_by_email(response.name_id)
66
+ authorize_success(user)
67
+ else
68
+ authorize_failure(user)
69
+ end
70
+ end
71
+
72
+ private
73
+
74
+ def saml_settings
75
+ settings = Onelogin::Saml::Settings.new
76
+
77
+ settings.assertion_consumer_service_url = "http://#{request.host}/saml/consume"
78
+ settings.issuer = request.host
79
+ settings.idp_sso_target_url = "https://app.onelogin.com/saml/signon/#{OneLoginAppId}"
80
+ settings.idp_cert_fingerprint = OneLoginAppCertFingerPrint
81
+ settings.name_identifier_format = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
82
+ # Optional for most SAML IdPs
83
+ settings.authn_context = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
84
+
85
+ settings
86
+ end
87
+ end
88
+ ```
89
+
90
+ If are using saml:AttributeStatement to transfare metadata, like the user name, you can access all the attributes through response.attributes. It
91
+ contains all the saml:AttributeStatement with its 'Name' as a indifferent key and the one saml:AttributeValue as value.
92
+
93
+ response = Onelogin::Saml::Response.new(params[:SAMLResponse])
94
+ response.settings = saml_settings
95
+
96
+ response.attributes[:username]
97
+
98
+ ## Service Provider Metadata
99
+
100
+ To form a trusted pair relationship with the IdP, the SP (you) need to provide metadata XML
101
+ to the IdP for various good reasons. (Caching, certificate lookups, relying party permissions, etc)
102
+
103
+ The class Onelogin::Saml::Metdata takes care of this by reading the Settings and returning XML. All
104
+ you have to do is add a controller to return the data, then give this URL to the IdP administrator.
105
+ The metdata will be polled by the IdP every few minutes, so updating your settings should propagate
106
+ to the IdP settings.
107
+
108
+ ```ruby
109
+ class SamlController < ApplicationController
110
+ # ... the rest of your controller definitions ...
111
+ def metadata
112
+ settings = Account.get_saml_settings
113
+ meta = Onelogin::Saml::Metadata.new
114
+ render :xml => meta.generate(settings)
115
+ end
116
+ end
117
+ ```
118
+
119
+ ## Note on Patches/Pull Requests
120
+
121
+ * Fork the project.
122
+ * Make your feature addition or bug fix.
123
+ * Add tests for it. This is important so I don't break it in a
124
+ future version unintentionally.
125
+ * Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
126
+ * Send me a pull request. Bonus points for topic branches.
data/Rakefile ADDED
@@ -0,0 +1,41 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ #not being used yet.
5
+ require 'rake/testtask'
6
+ Rake::TestTask.new(:test) do |test|
7
+ test.libs << 'lib' << 'test'
8
+ test.pattern = 'test/**/*_test.rb'
9
+ test.verbose = true
10
+ end
11
+
12
+ begin
13
+ require 'rcov/rcovtask'
14
+ Rcov::RcovTask.new do |test|
15
+ test.libs << 'test'
16
+ test.pattern = 'test/**/*_test.rb'
17
+ test.verbose = true
18
+ end
19
+ rescue LoadError
20
+ task :rcov do
21
+ abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
22
+ end
23
+ end
24
+
25
+ task :test
26
+
27
+ task :default => :test
28
+
29
+ # require 'rake/rdoctask'
30
+ # Rake::RDocTask.new do |rdoc|
31
+ # if File.exist?('VERSION')
32
+ # version = File.read('VERSION')
33
+ # else
34
+ # version = ""
35
+ # end
36
+
37
+ # rdoc.rdoc_dir = 'rdoc'
38
+ # rdoc.title = "ruby-saml-bm #{version}"
39
+ # rdoc.rdoc_files.include('README*')
40
+ # rdoc.rdoc_files.include('lib/**/*.rb')
41
+ #end
@@ -0,0 +1,79 @@
1
+ require "base64"
2
+ require "uuid"
3
+ require "zlib"
4
+ require "cgi"
5
+ require "rexml/document"
6
+ require "rexml/xpath"
7
+
8
+ module Onelogin
9
+ module Saml
10
+ include REXML
11
+ class Authrequest
12
+ def create(settings, params = {})
13
+ request_doc = create_authentication_xml_doc(settings)
14
+
15
+ request = ""
16
+ request_doc.write(request)
17
+
18
+ Logging.debug "Created AuthnRequest: #{request}"
19
+
20
+ deflated_request = Zlib::Deflate.deflate(request, 9)[2..-5]
21
+ base64_request = Base64.encode64(deflated_request)
22
+ encoded_request = CGI.escape(base64_request)
23
+ params_prefix = (settings.idp_sso_target_url =~ /\?/) ? '&' : '?'
24
+ request_params = "#{params_prefix}SAMLRequest=#{encoded_request}"
25
+
26
+ params.each_pair do |key, value|
27
+ request_params << "&#{key}=#{CGI.escape(value.to_s)}"
28
+ end
29
+
30
+ settings.idp_sso_target_url + request_params
31
+ end
32
+
33
+ def create_authentication_xml_doc(settings)
34
+ uuid = "_" + UUID.new.generate
35
+ time = Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S")
36
+ # Create AuthnRequest root element using REXML
37
+ request_doc = REXML::Document.new
38
+
39
+ root = request_doc.add_element "samlp:AuthnRequest", { "xmlns:samlp" => "urn:oasis:names:tc:SAML:2.0:protocol" }
40
+ root.attributes['ID'] = uuid
41
+ root.attributes['IssueInstant'] = time
42
+ root.attributes['Version'] = "2.0"
43
+
44
+ # Conditionally defined elements based on settings
45
+ if settings.assertion_consumer_service_url != nil
46
+ root.attributes["AssertionConsumerServiceURL"] = settings.assertion_consumer_service_url
47
+ end
48
+ if settings.issuer != nil
49
+ issuer = root.add_element "saml:Issuer", { "xmlns:saml" => "urn:oasis:names:tc:SAML:2.0:assertion" }
50
+ issuer.text = settings.issuer
51
+ end
52
+ if settings.name_identifier_format != nil
53
+ root.add_element "samlp:NameIDPolicy", {
54
+ "xmlns:samlp" => "urn:oasis:names:tc:SAML:2.0:protocol",
55
+ # Might want to make AllowCreate a setting?
56
+ "AllowCreate" => "true",
57
+ "Format" => settings.name_identifier_format
58
+ }
59
+ end
60
+
61
+ # BUG fix here -- if an authn_context is defined, add the tags with an "exact"
62
+ # match required for authentication to succeed. If this is not defined,
63
+ # the IdP will choose default rules for authentication. (Shibboleth IdP)
64
+ if settings.authn_context != nil
65
+ requested_context = root.add_element "samlp:RequestedAuthnContext", {
66
+ "xmlns:samlp" => "urn:oasis:names:tc:SAML:2.0:protocol",
67
+ "Comparison" => "exact",
68
+ }
69
+ class_ref = requested_context.add_element "saml:AuthnContextClassRef", {
70
+ "xmlns:saml" => "urn:oasis:names:tc:SAML:2.0:assertion",
71
+ }
72
+ class_ref.text = settings.authn_context
73
+ end
74
+ request_doc
75
+ end
76
+
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,26 @@
1
+ # Simplistic log class when we're running in Rails
2
+ module Onelogin
3
+ module Saml
4
+ class Logging
5
+ def self.debug(message)
6
+ return if !!ENV["ruby-saml-bm/testing"]
7
+
8
+ if defined? Rails
9
+ Rails.logger.debug message
10
+ else
11
+ puts message
12
+ end
13
+ end
14
+
15
+ def self.info(message)
16
+ return if !!ENV["ruby-saml-bm/testing"]
17
+
18
+ if defined? Rails
19
+ Rails.logger.info message
20
+ else
21
+ puts message
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,80 @@
1
+ require "base64"
2
+ require "uuid"
3
+ require "zlib"
4
+ require "cgi"
5
+
6
+ module Onelogin
7
+ module Saml
8
+ include REXML
9
+ class Logoutrequest
10
+
11
+ attr_reader :uuid # Can be obtained if neccessary
12
+
13
+ def initialize
14
+ @uuid = "_" + UUID.new.generate
15
+ end
16
+
17
+ def create(settings, params={})
18
+ request_doc = create_unauth_xml_doc(settings, params)
19
+ request = ""
20
+ request_doc.write(request)
21
+
22
+ deflated_request = Zlib::Deflate.deflate(request, 9)[2..-5]
23
+ base64_request = Base64.encode64(deflated_request)
24
+ encoded_request = CGI.escape(base64_request)
25
+
26
+ params_prefix = (settings.idp_slo_target_url =~ /\?/) ? '&' : '?'
27
+ request_params = "#{params_prefix}SAMLRequest=#{encoded_request}"
28
+
29
+ params.each_pair do |key, value|
30
+ request_params << "&#{key}=#{CGI.escape(value.to_s)}"
31
+ end
32
+
33
+ @logout_url = settings.idp_slo_target_url + request_params
34
+ end
35
+
36
+ def create_unauth_xml_doc(settings, params)
37
+
38
+ time = Time.new().strftime("%Y-%m-%dT%H:%M:%SZ")
39
+
40
+ request_doc = REXML::Document.new
41
+ root = request_doc.add_element "samlp:LogoutRequest", { "xmlns:samlp" => "urn:oasis:names:tc:SAML:2.0:protocol" }
42
+ root.attributes['ID'] = @uuid
43
+ root.attributes['IssueInstant'] = time
44
+ root.attributes['Version'] = "2.0"
45
+
46
+ if settings.issuer
47
+ issuer = root.add_element "saml:Issuer", { "xmlns:saml" => "urn:oasis:names:tc:SAML:2.0:assertion" }
48
+ issuer.text = settings.issuer
49
+ end
50
+
51
+ if settings.name_identifier_value
52
+ name_id = root.add_element "saml:NameID", { "xmlns:saml" => "urn:oasis:names:tc:SAML:2.0:assertion" }
53
+ name_id.attributes['NameQualifier'] = settings.sp_name_qualifier if settings.sp_name_qualifier
54
+ name_id.attributes['Format'] = settings.name_identifier_format if settings.name_identifier_format
55
+ name_id.text = settings.name_identifier_value
56
+ end
57
+
58
+ if settings.sessionindex
59
+ sessionindex = root.add_element "samlp:SessionIndex", { "xmlns:samlp" => "urn:oasis:names:tc:SAML:2.0:protocol" }
60
+ sessionindex.text = settings.sessionindex
61
+ end
62
+
63
+ # BUG fix here -- if an authn_context is defined, add the tags with an "exact"
64
+ # match required for authentication to succeed. If this is not defined,
65
+ # the IdP will choose default rules for authentication. (Shibboleth IdP)
66
+ if settings.authn_context != nil
67
+ requested_context = root.add_element "samlp:RequestedAuthnContext", {
68
+ "xmlns:samlp" => "urn:oasis:names:tc:SAML:2.0:protocol",
69
+ "Comparison" => "exact",
70
+ }
71
+ class_ref = requested_context.add_element "saml:AuthnContextClassRef", {
72
+ "xmlns:saml" => "urn:oasis:names:tc:SAML:2.0:assertion",
73
+ }
74
+ class_ref.text = settings.authn_context
75
+ end
76
+ request_doc
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,47 @@
1
+ require "rexml/document"
2
+ require "rexml/xpath"
3
+ require "uri"
4
+
5
+ # Class to return SP metadata based on the settings requested.
6
+ # Return this XML in a controller, then give that URL to the the
7
+ # IdP administrator. The IdP will poll the URL and your settings
8
+ # will be updated automatically
9
+ module Onelogin
10
+ module Saml
11
+ include REXML
12
+ class Metadata
13
+ def generate(settings)
14
+ meta_doc = REXML::Document.new
15
+ root = meta_doc.add_element "md:EntityDescriptor", {
16
+ "xmlns:md" => "urn:oasis:names:tc:SAML:2.0:metadata"
17
+ }
18
+ sp_sso = root.add_element "md:SPSSODescriptor", {
19
+ "protocolSupportEnumeration" => "urn:oasis:names:tc:SAML:2.0:protocol"
20
+ }
21
+ if settings.issuer != nil
22
+ root.attributes["entityID"] = settings.issuer
23
+ end
24
+ if settings.name_identifier_format != nil
25
+ name_id = sp_sso.add_element "md:NameIDFormat"
26
+ name_id.text = settings.name_identifier_format
27
+ end
28
+ if settings.assertion_consumer_service_url != nil
29
+ sp_sso.add_element "md:AssertionConsumerService", {
30
+ # Add this as a setting to create different bindings?
31
+ "Binding" => "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
32
+ "Location" => settings.assertion_consumer_service_url
33
+ }
34
+ end
35
+ meta_doc << REXML::XMLDecl.new
36
+ ret = ""
37
+ # pretty print the XML so IdP administrators can easily see what the SP supports
38
+ meta_doc.write(ret, 1)
39
+
40
+ Logging.debug "Generated metadata:\n#{ret}"
41
+
42
+ return ret
43
+
44
+ end
45
+ end
46
+ end
47
+ end