ror-rubycas-server 1.0.a

Sign up to get free protection for your applications and to get access to all the features.
Files changed (79) hide show
  1. data/CHANGELOG +292 -0
  2. data/Gemfile +2 -0
  3. data/LICENSE +26 -0
  4. data/README.textile +129 -0
  5. data/Rakefile +1 -0
  6. data/bin/rubycas-server +16 -0
  7. data/lib/casserver.rb +11 -0
  8. data/lib/casserver/authenticators/active_directory_ldap.rb +19 -0
  9. data/lib/casserver/authenticators/authlogic_crypto_providers/aes256.rb +43 -0
  10. data/lib/casserver/authenticators/authlogic_crypto_providers/bcrypt.rb +92 -0
  11. data/lib/casserver/authenticators/authlogic_crypto_providers/md5.rb +34 -0
  12. data/lib/casserver/authenticators/authlogic_crypto_providers/sha1.rb +59 -0
  13. data/lib/casserver/authenticators/authlogic_crypto_providers/sha512.rb +50 -0
  14. data/lib/casserver/authenticators/base.rb +67 -0
  15. data/lib/casserver/authenticators/client_certificate.rb +47 -0
  16. data/lib/casserver/authenticators/google.rb +58 -0
  17. data/lib/casserver/authenticators/ldap.rb +147 -0
  18. data/lib/casserver/authenticators/ntlm.rb +88 -0
  19. data/lib/casserver/authenticators/open_id.rb +22 -0
  20. data/lib/casserver/authenticators/sql.rb +133 -0
  21. data/lib/casserver/authenticators/sql_authlogic.rb +93 -0
  22. data/lib/casserver/authenticators/sql_encrypted.rb +75 -0
  23. data/lib/casserver/authenticators/sql_md5.rb +19 -0
  24. data/lib/casserver/authenticators/sql_rest_auth.rb +85 -0
  25. data/lib/casserver/authenticators/test.rb +22 -0
  26. data/lib/casserver/cas.rb +315 -0
  27. data/lib/casserver/localization.rb +91 -0
  28. data/lib/casserver/model.rb +270 -0
  29. data/lib/casserver/options_hash.rb +44 -0
  30. data/lib/casserver/server.rb +706 -0
  31. data/lib/casserver/utils.rb +32 -0
  32. data/lib/casserver/views/_login_form.erb +42 -0
  33. data/lib/casserver/views/layout.erb +18 -0
  34. data/lib/casserver/views/login.erb +30 -0
  35. data/lib/casserver/views/proxy.builder +12 -0
  36. data/lib/casserver/views/proxy_validate.builder +25 -0
  37. data/lib/casserver/views/service_validate.builder +18 -0
  38. data/lib/casserver/views/validate.erb +2 -0
  39. data/po/de_DE/rubycas-server.po +127 -0
  40. data/po/es_ES/rubycas-server.po +123 -0
  41. data/po/fr_FR/rubycas-server.po +128 -0
  42. data/po/ja_JP/rubycas-server.po +126 -0
  43. data/po/pl_PL/rubycas-server.po +123 -0
  44. data/po/pt_BR/rubycas-server.po +123 -0
  45. data/po/ru_RU/rubycas-server.po +118 -0
  46. data/po/rubycas-server.pot +112 -0
  47. data/po/zh_CN/rubycas-server.po +113 -0
  48. data/po/zh_TW/rubycas-server.po +113 -0
  49. data/public/themes/cas.css +121 -0
  50. data/public/themes/notice.png +0 -0
  51. data/public/themes/ok.png +0 -0
  52. data/public/themes/simple/bg.png +0 -0
  53. data/public/themes/simple/favicon.png +0 -0
  54. data/public/themes/simple/login_box_bg.png +0 -0
  55. data/public/themes/simple/logo.png +0 -0
  56. data/public/themes/simple/theme.css +28 -0
  57. data/public/themes/urbacon/bg.png +0 -0
  58. data/public/themes/urbacon/login_box_bg.png +0 -0
  59. data/public/themes/urbacon/logo.png +0 -0
  60. data/public/themes/urbacon/theme.css +33 -0
  61. data/public/themes/warning.png +0 -0
  62. data/resources/init.d.sh +58 -0
  63. data/rubycas-server.gemspec +57 -0
  64. data/setup.rb +1585 -0
  65. data/spec/alt_config.yml +50 -0
  66. data/spec/authenticators/ldap_spec.rb +53 -0
  67. data/spec/casserver_spec.rb +141 -0
  68. data/spec/database.yml +5 -0
  69. data/spec/default_config.yml +73 -0
  70. data/spec/model_spec.rb +42 -0
  71. data/spec/options_hash_spec.rb +146 -0
  72. data/spec/spec.opts +4 -0
  73. data/spec/spec_helper.rb +90 -0
  74. data/spec/utils_spec.rb +53 -0
  75. data/tasks/bundler.rake +4 -0
  76. data/tasks/db/migrate.rake +12 -0
  77. data/tasks/localization.rake +13 -0
  78. data/tasks/spec.rake +10 -0
  79. metadata +356 -0
@@ -0,0 +1,93 @@
1
+ require 'casserver/authenticators/sql'
2
+
3
+ # These were pulled directly from Authlogic, and new ones can be added
4
+ # just by including new Crypto Providers
5
+ require File.dirname(__FILE__) + '/authlogic_crypto_providers/aes256'
6
+ require File.dirname(__FILE__) + '/authlogic_crypto_providers/bcrypt'
7
+ require File.dirname(__FILE__) + '/authlogic_crypto_providers/md5'
8
+ require File.dirname(__FILE__) + '/authlogic_crypto_providers/sha1'
9
+ require File.dirname(__FILE__) + '/authlogic_crypto_providers/sha512'
10
+
11
+ begin
12
+ require 'active_record'
13
+ rescue LoadError
14
+ require 'rubygems'
15
+ require 'active_record'
16
+ end
17
+
18
+ # This is a version of the SQL authenticator that works nicely with Authlogic.
19
+ # Passwords are encrypted the same way as it done in Authlogic.
20
+ # Before use you this, you MUST configure rest_auth_digest_streches and rest_auth_site_key in
21
+ # config.
22
+ #
23
+ # Using this authenticator requires restful authentication plugin on rails (client) side.
24
+ #
25
+ # * git://github.com/binarylogic/authlogic.git
26
+ #
27
+ # Usage:
28
+
29
+ # authenticator:
30
+ # class: CASServer::Authenticators::SQLAuthlogic
31
+ # database:
32
+ # adapter: mysql
33
+ # database: some_database_with_users_table
34
+ # user: root
35
+ # password:
36
+ # server: localhost
37
+ # user_table: user
38
+ # username_column: login
39
+ # password_column: crypted_password
40
+ # salt_column: password_salt
41
+ # encryptor: Sha1
42
+ # encryptor_options:
43
+ # digest_format: --SALT--PASSWORD--
44
+ # stretches: 1
45
+ #
46
+ class CASServer::Authenticators::SQLAuthlogic < CASServer::Authenticators::SQL
47
+
48
+ def validate(credentials)
49
+ read_standard_credentials(credentials)
50
+ raise_if_not_configured
51
+
52
+ user_model = self.class.user_model
53
+
54
+ username_column = @options[:username_column] || "login"
55
+ password_column = @options[:password_column] || "crypted_password"
56
+ salt_column = @options[:salt_column]
57
+
58
+ $LOG.debug "#{self.class}: [#{user_model}] " + "Connection pool size: #{user_model.connection_pool.instance_variable_get(:@checked_out).length}/#{user_model.connection_pool.instance_variable_get(:@connections).length}"
59
+ results = user_model.find(:all, :conditions => ["#{username_column} = ?", @username])
60
+ user_model.connection_pool.checkin(user_model.connection)
61
+
62
+ begin
63
+ encryptor = eval("Authlogic::CryptoProviders::" + @options[:encryptor] || "Sha512")
64
+ rescue
65
+ $LOG.warn("Could not initialize Authlogic crypto class for '#{@options[:encryptor]}'")
66
+ encryptor = Authlogic::CryptoProviders::Sha512
67
+ end
68
+
69
+ @options[:encryptor_options].each do |name, value|
70
+ encryptor.send("#{name}=", value) if encryptor.respond_to?("#{name}=")
71
+ end
72
+
73
+ if results.size > 0
74
+ $LOG.warn("Multiple matches found for user '#{@username}'") if results.size > 1
75
+ user = results.first
76
+ tokens = [@password, (not salt_column.nil?) && user.send(salt_column) || nil].compact
77
+ crypted = user.send(password_column)
78
+
79
+ unless @options[:extra_attributes].blank?
80
+ if results.size > 1
81
+ $LOG.warn("#{self.class}: Unable to extract extra_attributes because multiple matches were found for #{@username.inspect}")
82
+ else
83
+ extract_extra(user)
84
+ log_extra
85
+ end
86
+ end
87
+
88
+ return encryptor.matches?(crypted, tokens)
89
+ else
90
+ return false
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,75 @@
1
+ require 'casserver/authenticators/sql'
2
+
3
+ require 'digest/sha1'
4
+ require 'digest/sha2'
5
+ require 'crypt-isaac'
6
+
7
+ # This is a more secure version of the SQL authenticator. Passwords are encrypted
8
+ # rather than being stored in plain text.
9
+ #
10
+ # Based on code contributed by Ben Mabey.
11
+ #
12
+ # Using this authenticator requires some configuration on the client side. Please see
13
+ # http://code.google.com/p/rubycas-server/wiki/UsingTheSQLEncryptedAuthenticator
14
+ class CASServer::Authenticators::SQLEncrypted < CASServer::Authenticators::SQL
15
+ # Include this module into your application's user model.
16
+ #
17
+ # Your model must have an 'encrypted_password' column where the password will be stored,
18
+ # and an 'encryption_salt' column that will be populated with a random string before
19
+ # the user record is first created.
20
+ module EncryptedPassword
21
+ def self.included(mod)
22
+ raise "#{self} should be inclued in an ActiveRecord class!" unless mod.respond_to?(:before_save)
23
+ mod.before_save :generate_encryption_salt
24
+ end
25
+
26
+ def encrypt(str)
27
+ generate_encryption_salt unless encryption_salt
28
+ Digest::SHA256.hexdigest("#{encryption_salt}::#{str}")
29
+ end
30
+
31
+ def password=(password)
32
+ self[:encrypted_password] = encrypt(password)
33
+ end
34
+
35
+ def generate_encryption_salt
36
+ self.encryption_salt = Digest::SHA1.hexdigest(Crypt::ISAAC.new.rand(2**31).to_s) unless
37
+ encryption_salt
38
+ end
39
+ end
40
+
41
+ def self.setup(options)
42
+ super(options)
43
+ user_model.__send__(:include, EncryptedPassword)
44
+ end
45
+
46
+ def validate(credentials)
47
+ read_standard_credentials(credentials)
48
+ raise_if_not_configured
49
+
50
+ user_model = self.class.user_model
51
+
52
+ username_column = @options[:username_column] || "username"
53
+ encrypt_function = @options[:encrypt_function] || 'user.encrypted_password == Digest::SHA256.hexdigest("#{user.encryption_salt}::#{@password}")'
54
+
55
+ $LOG.debug "#{self.class}: [#{user_model}] " + "Connection pool size: #{user_model.connection_pool.instance_variable_get(:@checked_out).length}/#{user_model.connection_pool.instance_variable_get(:@connections).length}"
56
+ results = user_model.find(:all, :conditions => ["#{username_column} = ?", @username])
57
+ user_model.connection_pool.checkin(user_model.connection)
58
+
59
+ if results.size > 0
60
+ $LOG.warn("Multiple matches found for user '#{@username}'") if results.size > 1
61
+ user = results.first
62
+ unless @options[:extra_attributes].blank?
63
+ if results.size > 1
64
+ $LOG.warn("#{self.class}: Unable to extract extra_attributes because multiple matches were found for #{@username.inspect}")
65
+ else
66
+ extract_extra(user)
67
+ log_extra
68
+ end
69
+ end
70
+ return eval(encrypt_function)
71
+ else
72
+ return false
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,19 @@
1
+ require 'casserver/authenticators/sql'
2
+
3
+ require 'digest/md5'
4
+
5
+ # Essentially the same as the standard SQL authenticator, but this version
6
+ # assumes that your password is stored as an MD5 hash.
7
+ #
8
+ # This was contributed by malcomm for Drupal authentication. To work with
9
+ # Drupal, you should use 'name' for the :username_column config option, and
10
+ # 'pass' for the :password_column.
11
+ class CASServer::Authenticators::SQLMd5 < CASServer::Authenticators::SQL
12
+
13
+ protected
14
+ def read_standard_credentials(credentials)
15
+ super
16
+ @password = Digest::MD5.hexdigest(@password)
17
+ end
18
+
19
+ end
@@ -0,0 +1,85 @@
1
+ require 'casserver/authenticators/sql_encrypted'
2
+
3
+ require 'digest/sha1'
4
+
5
+ begin
6
+ require 'active_record'
7
+ rescue LoadError
8
+ require 'rubygems'
9
+ require 'active_record'
10
+ end
11
+
12
+ # This is a version of the SQL authenticator that works nicely with RestfulAuthentication.
13
+ # Passwords are encrypted the same way as it done in RestfulAuthentication.
14
+ # Before use you this, you MUST configure rest_auth_digest_streches and rest_auth_site_key in
15
+ # config.
16
+ #
17
+ # Using this authenticator requires restful authentication plugin on rails (client) side.
18
+ #
19
+ # * git://github.com/technoweenie/restful-authentication.git
20
+ #
21
+ class CASServer::Authenticators::SQLRestAuth < CASServer::Authenticators::SQLEncrypted
22
+
23
+ def validate(credentials)
24
+ read_standard_credentials(credentials)
25
+ raise_if_not_configured
26
+
27
+ user_model = self.class.user_model
28
+
29
+ username_column = @options[:username_column] || "email"
30
+
31
+ $LOG.debug "#{self.class}: [#{user_model}] " + "Connection pool size: #{user_model.connection_pool.instance_variable_get(:@checked_out).length}/#{user_model.connection_pool.instance_variable_get(:@connections).length}"
32
+ results = user_model.find(:all, :conditions => ["#{username_column} = ?", @username])
33
+ user_model.connection_pool.checkin(user_model.connection)
34
+
35
+ if results.size > 0
36
+ $LOG.warn("Multiple matches found for user '#{@username}'") if results.size > 1
37
+ user = results.first
38
+ if user.crypted_password == user.encrypt(@password)
39
+ unless @options[:extra_attributes].blank?
40
+ extract_extra(user)
41
+ log_extra
42
+ end
43
+ return true
44
+ else
45
+ return false
46
+ end
47
+ else
48
+ return false
49
+ end
50
+ end
51
+
52
+ def self.setup(options)
53
+ super(options)
54
+ user_model.__send__(:include, EncryptedPassword)
55
+ end
56
+
57
+ module EncryptedPassword
58
+
59
+ # XXX: this constants MUST be defined in config.
60
+ # For more details # look at restful-authentication docs.
61
+ #
62
+ REST_AUTH_DIGEST_STRETCHES = $CONF.rest_auth_digest_streches
63
+ REST_AUTH_SITE_KEY = $CONF.rest_auth_site_key
64
+
65
+ def self.included(mod)
66
+ raise "#{self} should be inclued in an ActiveRecord class!" unless mod.respond_to?(:before_save)
67
+ end
68
+
69
+ def encrypt(password)
70
+ password_digest(password, self.salt)
71
+ end
72
+
73
+ def secure_digest(*args)
74
+ Digest::SHA1.hexdigest(args.flatten.join('--'))
75
+ end
76
+
77
+ def password_digest(password, salt)
78
+ digest = REST_AUTH_SITE_KEY
79
+ REST_AUTH_DIGEST_STRETCHES.times do
80
+ digest = secure_digest(digest, salt, password, REST_AUTH_SITE_KEY)
81
+ end
82
+ digest
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,22 @@
1
+ # encoding: UTF-8
2
+ require 'casserver/authenticators/base'
3
+
4
+ # Dummy authenticator used for testing.
5
+ # Accepts any username as valid as long as the password is "testpassword"; otherwise authentication fails.
6
+ # Raises an AuthenticationError when username is "do_error" (this is useful to test the Exception
7
+ # handling functionality).
8
+ class CASServer::Authenticators::Test < CASServer::Authenticators::Base
9
+ def validate(credentials)
10
+ read_standard_credentials(credentials)
11
+
12
+ raise CASServer::AuthenticatorError, "Username is 'do_error'!" if @username == 'do_error'
13
+
14
+ @extra_attributes[:test_utf_string] = "Ютф"
15
+ @extra_attributes[:test_numeric] = 123.45
16
+ @extra_attributes[:test_serialized] = {:foo => 'bar', :alpha => [1,2,3]}
17
+
18
+ valid_password = options[:password] || "testpassword"
19
+
20
+ return @password == valid_password
21
+ end
22
+ end
@@ -0,0 +1,315 @@
1
+ require 'uri'
2
+ require 'net/https'
3
+
4
+ require 'casserver/model'
5
+
6
+ # Encapsulates CAS functionality. This module is meant to be included in
7
+ # the CASServer::Controllers module.
8
+ module CASServer::CAS
9
+
10
+ include CASServer::Model
11
+
12
+ def generate_login_ticket
13
+ # 3.5 (login ticket)
14
+ lt = LoginTicket.new
15
+ lt.ticket = "LT-" + CASServer::Utils.random_string
16
+
17
+ lt.client_hostname = @env['HTTP_X_FORWARDED_FOR'] || @env['REMOTE_HOST'] || @env['REMOTE_ADDR']
18
+ lt.save!
19
+ $LOG.debug("Generated login ticket '#{lt.ticket}' for client" +
20
+ " at '#{lt.client_hostname}'")
21
+ lt
22
+ end
23
+
24
+ # Creates a TicketGrantingTicket for the given username. This is done when the user logs in
25
+ # for the first time to establish their SSO session (after their credentials have been validated).
26
+ #
27
+ # The optional 'extra_attributes' parameter takes a hash of additional attributes
28
+ # that will be sent along with the username in the CAS response to subsequent
29
+ # validation requests from clients.
30
+ def generate_ticket_granting_ticket(username, extra_attributes = {})
31
+ # 3.6 (ticket granting cookie/ticket)
32
+ tgt = TicketGrantingTicket.new
33
+ tgt.ticket = "TGC-" + CASServer::Utils.random_string
34
+ tgt.username = username
35
+ tgt.extra_attributes = extra_attributes
36
+ tgt.client_hostname = @env['HTTP_X_FORWARDED_FOR'] || @env['REMOTE_HOST'] || @env['REMOTE_ADDR']
37
+ tgt.save!
38
+ $LOG.debug("Generated ticket granting ticket '#{tgt.ticket}' for user" +
39
+ " '#{tgt.username}' at '#{tgt.client_hostname}'" +
40
+ (extra_attributes.blank? ? "" : " with extra attributes #{extra_attributes.inspect}"))
41
+ tgt
42
+ end
43
+
44
+ def generate_service_ticket(service, username, tgt)
45
+ # 3.1 (service ticket)
46
+ st = ServiceTicket.new
47
+ st.ticket = "ST-" + CASServer::Utils.random_string
48
+ st.service = service
49
+ st.username = username
50
+ st.granted_by_tgt_id = tgt.id
51
+ st.client_hostname = @env['HTTP_X_FORWARDED_FOR'] || @env['REMOTE_HOST'] || @env['REMOTE_ADDR']
52
+ st.save!
53
+ $LOG.debug("Generated service ticket '#{st.ticket}' for service '#{st.service}'" +
54
+ " for user '#{st.username}' at '#{st.client_hostname}'")
55
+ st
56
+ end
57
+
58
+ def generate_proxy_ticket(target_service, pgt)
59
+ # 3.2 (proxy ticket)
60
+ pt = ProxyTicket.new
61
+ pt.ticket = "PT-" + CASServer::Utils.random_string
62
+ pt.service = target_service
63
+ pt.username = pgt.service_ticket.username
64
+ pt.granted_by_pgt_id = pgt.id
65
+ pt.granted_by_tgt_id = pgt.service_ticket.granted_by_tgt.id
66
+ pt.client_hostname = @env['HTTP_X_FORWARDED_FOR'] || @env['REMOTE_HOST'] || @env['REMOTE_ADDR']
67
+ pt.save!
68
+ $LOG.debug("Generated proxy ticket '#{pt.ticket}' for target service '#{pt.service}'" +
69
+ " for user '#{pt.username}' at '#{pt.client_hostname}' using proxy-granting" +
70
+ " ticket '#{pgt.ticket}'")
71
+ pt
72
+ end
73
+
74
+ def generate_proxy_granting_ticket(pgt_url, st)
75
+ uri = URI.parse(pgt_url)
76
+ https = Net::HTTP.new(uri.host,uri.port)
77
+ https.use_ssl = true
78
+
79
+ # Here's what's going on here:
80
+ #
81
+ # 1. We generate a ProxyGrantingTicket (but don't store it in the database just yet)
82
+ # 2. Deposit the PGT and it's associated IOU at the proxy callback URL.
83
+ # 3. If the proxy callback URL responds with HTTP code 200, store the PGT and return it;
84
+ # otherwise don't save it and return nothing.
85
+ #
86
+ https.start do |conn|
87
+ path = uri.path.empty? ? '/' : uri.path
88
+ path += '?' + uri.query unless (uri.query.nil? || uri.query.empty?)
89
+
90
+ pgt = ProxyGrantingTicket.new
91
+ pgt.ticket = "PGT-" + CASServer::Utils.random_string(60)
92
+ pgt.iou = "PGTIOU-" + CASServer::Utils.random_string(57)
93
+ pgt.service_ticket_id = st.id
94
+ pgt.client_hostname = @env['HTTP_X_FORWARDED_FOR'] || @env['REMOTE_HOST'] || @env['REMOTE_ADDR']
95
+
96
+ # FIXME: The CAS protocol spec says to use 'pgt' as the parameter, but in practice
97
+ # the JA-SIG and Yale server implementations use pgtId. We'll go with the
98
+ # in-practice standard.
99
+ path += (uri.query.nil? || uri.query.empty? ? '?' : '&') + "pgtId=#{pgt.ticket}&pgtIou=#{pgt.iou}"
100
+
101
+ response = conn.request_get(path)
102
+ # TODO: follow redirects... 2.5.4 says that redirects MAY be followed
103
+ # NOTE: The following response codes are valid according to the JA-SIG implementation even without following redirects
104
+
105
+ if %w(200 202 301 302 304).include?(response.code)
106
+ # 3.4 (proxy-granting ticket IOU)
107
+ pgt.save!
108
+ $LOG.debug "PGT generated for pgt_url '#{pgt_url}': #{pgt.inspect}"
109
+ pgt
110
+ else
111
+ $LOG.warn "PGT callback server responded with a bad result code '#{response.code}'. PGT will not be stored."
112
+ nil
113
+ end
114
+ end
115
+ end
116
+
117
+ def validate_login_ticket(ticket)
118
+ $LOG.debug("Validating login ticket '#{ticket}'")
119
+
120
+ success = false
121
+ if ticket.nil?
122
+ error = _("Your login request did not include a login ticket. There may be a problem with the authentication system.")
123
+ $LOG.warn "Missing login ticket."
124
+ elsif lt = LoginTicket.find_by_ticket(ticket)
125
+ if lt.consumed?
126
+ error = _("The login ticket you provided has already been used up. Please try logging in again.")
127
+ $LOG.warn "Login ticket '#{ticket}' previously used up"
128
+ elsif Time.now - lt.created_on < settings.config[:maximum_unused_login_ticket_lifetime]
129
+ $LOG.info "Login ticket '#{ticket}' successfully validated"
130
+ else
131
+ error = _("You took too long to enter your credentials. Please try again.")
132
+ $LOG.warn "Expired login ticket '#{ticket}'"
133
+ end
134
+ else
135
+ error = _("The login ticket you provided is invalid. There may be a problem with the authentication system.")
136
+ $LOG.warn "Invalid login ticket '#{ticket}'"
137
+ end
138
+
139
+ lt.consume! if lt
140
+
141
+ error
142
+ end
143
+
144
+ def validate_ticket_granting_ticket(ticket)
145
+ $LOG.debug("Validating ticket granting ticket '#{ticket}'")
146
+
147
+ if ticket.nil?
148
+ error = "No ticket granting ticket given."
149
+ $LOG.debug error
150
+ elsif tgt = TicketGrantingTicket.find_by_ticket(ticket)
151
+ if settings.config[:maximum_session_lifetime] && Time.now - tgt.created_on > settings.config[:maximum_session_lifetime]
152
+ tgt.destroy
153
+ error = "Your session has expired. Please log in again."
154
+ $LOG.info "Ticket granting ticket '#{ticket}' for user '#{tgt.username}' expired."
155
+ else
156
+ $LOG.info "Ticket granting ticket '#{ticket}' for user '#{tgt.username}' successfully validated."
157
+ end
158
+ else
159
+ error = "Invalid ticket granting ticket '#{ticket}' (no matching ticket found in the database)."
160
+ $LOG.warn(error)
161
+ end
162
+
163
+ [tgt, error]
164
+ end
165
+
166
+ def validate_service_ticket(service, ticket, allow_proxy_tickets = false)
167
+ $LOG.debug "Validating service/proxy ticket '#{ticket}' for service '#{service}'"
168
+
169
+ if service.nil? or ticket.nil?
170
+ error = Error.new(:INVALID_REQUEST, "Ticket or service parameter was missing in the request.")
171
+ $LOG.warn "#{error.code} - #{error.message}"
172
+ elsif st = ServiceTicket.find_by_ticket(ticket)
173
+ if st.consumed?
174
+ error = Error.new(:INVALID_TICKET, "Ticket '#{ticket}' has already been used up.")
175
+ $LOG.warn "#{error.code} - #{error.message}"
176
+ elsif st.kind_of?(CASServer::Model::ProxyTicket) && !allow_proxy_tickets
177
+ error = Error.new(:INVALID_TICKET, "Ticket '#{ticket}' is a proxy ticket, but only service tickets are allowed here.")
178
+ $LOG.warn "#{error.code} - #{error.message}"
179
+ elsif Time.now - st.created_on > settings.config[:maximum_unused_service_ticket_lifetime]
180
+ error = Error.new(:INVALID_TICKET, "Ticket '#{ticket}' has expired.")
181
+ $LOG.warn "Ticket '#{ticket}' has expired."
182
+ elsif !st.matches_service? service
183
+ error = Error.new(:INVALID_SERVICE, "The ticket '#{ticket}' belonging to user '#{st.username}' is valid,"+
184
+ " but the requested service '#{service}' does not match the service '#{st.service}' associated with this ticket.")
185
+ $LOG.warn "#{error.code} - #{error.message}"
186
+ else
187
+ $LOG.info("Ticket '#{ticket}' for service '#{service}' for user '#{st.username}' successfully validated.")
188
+ end
189
+ else
190
+ error = Error.new(:INVALID_TICKET, "Ticket '#{ticket}' not recognized.")
191
+ $LOG.warn("#{error.code} - #{error.message}")
192
+ end
193
+
194
+ if st
195
+ st.consume!
196
+ end
197
+
198
+
199
+ [st, error]
200
+ end
201
+
202
+ def validate_proxy_ticket(service, ticket)
203
+ pt, error = validate_service_ticket(service, ticket, true)
204
+
205
+ if pt.kind_of?(CASServer::Model::ProxyTicket) && !error
206
+ if not pt.granted_by_pgt
207
+ error = Error.new(:INTERNAL_ERROR, "Proxy ticket '#{pt}' belonging to user '#{pt.username}' is not associated with a proxy granting ticket.")
208
+ elsif not pt.granted_by_pgt.service_ticket
209
+ error = Error.new(:INTERNAL_ERROR, "Proxy granting ticket '#{pt.granted_by_pgt}'"+
210
+ " (associated with proxy ticket '#{pt}' and belonging to user '#{pt.username}' is not associated with a service ticket.")
211
+ end
212
+ end
213
+
214
+ [pt, error]
215
+ end
216
+
217
+ def validate_proxy_granting_ticket(ticket)
218
+ if ticket.nil?
219
+ error = Error.new(:INVALID_REQUEST, "pgt parameter was missing in the request.")
220
+ $LOG.warn("#{error.code} - #{error.message}")
221
+ elsif pgt = ProxyGrantingTicket.find_by_ticket(ticket)
222
+ if pgt.service_ticket
223
+ $LOG.info("Proxy granting ticket '#{ticket}' belonging to user '#{pgt.service_ticket.username}' successfully validated.")
224
+ else
225
+ error = Error.new(:INTERNAL_ERROR, "Proxy granting ticket '#{ticket}' is not associated with a service ticket.")
226
+ $LOG.error("#{error.code} - #{error.message}")
227
+ end
228
+ else
229
+ error = Error.new(:BAD_PGT, "Invalid proxy granting ticket '#{ticket}' (no matching ticket found in the database).")
230
+ $LOG.warn("#{error.code} - #{error.message}")
231
+ end
232
+
233
+ [pgt, error]
234
+ end
235
+
236
+ # Takes an existing ServiceTicket object (presumably pulled from the database)
237
+ # and sends a POST with logout information to the service that the ticket
238
+ # was generated for.
239
+ #
240
+ # This makes possible the "single sign-out" functionality added in CAS 3.1.
241
+ # See http://www.ja-sig.org/wiki/display/CASUM/Single+Sign+Out
242
+ def send_logout_notification_for_service_ticket(st)
243
+ uri = URI.parse(st.service)
244
+ uri.path = '/' if uri.path.empty?
245
+ time = Time.now
246
+ rand = CASServer::Utils.random_string
247
+
248
+ begin
249
+ response = Net::HTTP.post_form(uri, {'logoutRequest' => URI.escape(%{<samlp:LogoutRequest ID="#{rand}" Version="2.0" IssueInstant="#{time.rfc2822}">
250
+ <saml:NameID></saml:NameID>
251
+ <samlp:SessionIndex>#{st.ticket}</samlp:SessionIndex>
252
+ </samlp:LogoutRequest>})})
253
+ if response.kind_of? Net::HTTPSuccess
254
+ $LOG.info "Logout notification successfully posted to #{st.service.inspect}."
255
+ return true
256
+ else
257
+ $LOG.error "Service #{st.service.inspect} responed to logout notification with code '#{response.code}'!"
258
+ return false
259
+ end
260
+ rescue Exception => e
261
+ $LOG.error "Failed to send logout notification to service #{st.service.inspect} due to #{e}"
262
+ return false
263
+ end
264
+ end
265
+
266
+ def service_uri_with_ticket(service, st)
267
+ raise ArgumentError, "Second argument must be a ServiceTicket!" unless st.kind_of? CASServer::Model::ServiceTicket
268
+
269
+ # This will choke with a URI::InvalidURIError if service URI is not properly URI-escaped...
270
+ # This exception is handled further upstream (i.e. in the controller).
271
+ service_uri = URI.parse(service)
272
+
273
+ if service.include? "?"
274
+ if service_uri.query.empty?
275
+ query_separator = ""
276
+ else
277
+ query_separator = "&"
278
+ end
279
+ else
280
+ query_separator = "?"
281
+ end
282
+
283
+ service_with_ticket = service + query_separator + "ticket=" + st.ticket
284
+ service_with_ticket
285
+ end
286
+
287
+ # Strips CAS-related parameters from a service URL and normalizes it,
288
+ # removing trailing / and ?. Also converts any spaces to +.
289
+ #
290
+ # For example, "http://google.com?ticket=12345" will be returned as
291
+ # "http://google.com". Also, "http://google.com/" would be returned as
292
+ # "http://google.com".
293
+ #
294
+ # Note that only the first occurance of each CAS-related parameter is
295
+ # removed, so that "http://google.com?ticket=12345&ticket=abcd" would be
296
+ # returned as "http://google.com?ticket=abcd".
297
+ def clean_service_url(dirty_service)
298
+ return dirty_service if dirty_service.blank?
299
+ clean_service = dirty_service.dup
300
+ ['service', 'ticket', 'gateway', 'renew'].each do |p|
301
+ clean_service.sub!(Regexp.new("&?#{p}=[^&]*"), '')
302
+ end
303
+
304
+ clean_service.gsub!(/[\/\?&]$/, '') # remove trailing ?, /, or &
305
+ clean_service.gsub!('?&', '?')
306
+ clean_service.gsub!(' ', '+')
307
+
308
+ $LOG.debug("Cleaned dirty service URL #{dirty_service.inspect} to #{clean_service.inspect}") if
309
+ dirty_service != clean_service
310
+
311
+ return clean_service
312
+ end
313
+ module_function :clean_service_url
314
+
315
+ end