godfat-rubycas-server 0.8.0.20090918

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