1 #!/usr/bin/env python 2 3 """ 4 OpenID redirection classes, sending unauthenticated users to the OpenID 5 initiation page. 6 7 Copyright (C) 2004, 2005, 2006, 2007 Paul Boddie <paul@boddie.org.uk> 8 9 This library is free software; you can redistribute it and/or 10 modify it under the terms of the GNU Lesser General Public 11 License as published by the Free Software Foundation; either 12 version 2.1 of the License, or (at your option) any later version. 13 14 This library is distributed in the hope that it will be useful, 15 but WITHOUT ANY WARRANTY; without even the implied warranty of 16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 Lesser General Public License for more details. 18 19 You should have received a copy of the GNU Lesser General Public 20 License along with this library; if not, write to the Free Software 21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA 22 """ 23 24 from WebStack.Resources.LoginRedirect import LoginRedirectResource 25 from WebStack.Helpers.Auth import Verifier, check_openid_signature 26 import WebStack.Generic 27 import datetime 28 import urllib 29 30 class OpenIDRedirectResource(LoginRedirectResource): 31 32 "A resource redirecting to an OpenID initiation page." 33 34 openid_ns = "http://specs.openid.net/auth/2.0" 35 36 def respond(self, trans): 37 38 "Respond using the given transaction 'trans'." 39 40 fields = trans.get_fields(self.path_encoding) 41 42 # If requested, attempt to verify OpenID assertions. 43 # http://openid.net/specs/openid-authentication-2_0-12.html#rfc.section.11 44 45 if fields.get("openid.mode", [None])[0] == "id_res": 46 47 # The additional condition could be used to insist on OpenID 2.0 48 # conformance: 49 # fields.get("openid.ns", [None])[0] == self.openid_ns 50 51 if self.authenticator.authenticate(trans, verify=1): 52 trans.redirect(fields["openid.return_to"][0]) 53 54 # Otherwise, handle the usual parameters and request details. 55 56 LoginRedirectResource.respond(self, trans) 57 58 class OpenIDRedirectAuthenticator(Verifier): 59 60 """ 61 An authenticator which verifies the credentials provided in a special login 62 cookie, accepting OpenID assertions if necessary. 63 """ 64 65 encoding = "utf-8" 66 openid_ns = "http://specs.openid.net/auth/2.0" 67 replay_limit = datetime.timedelta(0, 10) # 10s 68 69 def __init__(self, secret_key, app_url, associations=None, replay_limit=None, 70 cookie_name=None, urlencoding=None): 71 72 """ 73 Initialise the authenticator with a 'secret_key', 'app_url' and optional 74 'associations', 'replay_limit', 'cookie_name' and 'urlencoding'. 75 """ 76 77 Verifier.__init__(self, secret_key, cookie_name) 78 79 self.app_url = app_url 80 self.associations = associations or {} 81 self.replay_limit = replay_limit or self.replay_limit 82 self.urlencoding = urlencoding or self.encoding 83 84 def authenticate(self, trans, verify=0): 85 86 """ 87 Authenticate the originator of 'trans', updating the object if 88 successful and returning a true value if successful, or a false value 89 otherwise. 90 91 If the optional 'verify' parameter is specified as a true value, perform 92 verification on any 93 """ 94 95 # If requested, attempt to verify OpenID assertions. 96 97 if verify: 98 fields = trans.get_fields(self.urlencoding) 99 100 # NOTE: Could expose all errors. 101 102 try: 103 # Test the details of the assertion. 104 105 if self.test_url(fields) and \ 106 self.test_signature(fields) and \ 107 self.test_replay(fields): 108 109 self.set_token(trans, fields["openid.identity"][0]) 110 return 1 111 112 # Incomplete assertion. 113 114 except (KeyError, ValueError): 115 raise 116 117 # Assertion failed or was incomplete. 118 119 return 0 120 121 # Otherwise, try to authenticate with an application cookie. 122 123 else: 124 valid = Verifier.authenticate(self, trans) 125 126 # Update the transaction with the user details. 127 128 if valid: 129 username, token = self.get_username_and_token(trans) 130 trans.set_user(username) 131 return valid 132 133 def test_url(self, fields): 134 135 """ 136 See: 137 http://openid.net/specs/openid-authentication-2_0-12.html#rfc.section.11.1 138 """ 139 140 # NOTE: Currently, this is not strict enough. 141 142 return fields["openid.return_to"][0].startswith(self.app_url) 143 144 def test_signature(self, fields): 145 146 """ 147 See: 148 http://openid.net/specs/openid-authentication-2_0-12.html#rfc.section.11.4 149 http://openid.net/specs/openid-authentication-2_0-12.html#rfc.section.6 150 """ 151 152 handle = fields.get("openid.assoc_handle", [None])[0] 153 154 # With an association handle, look up the appropriate secret key and 155 # verify the signed items. 156 157 if handle is not None: 158 159 # Where an association exists, use the known secret key. 160 161 if self.associations.has_key(handle): 162 return check_openid_signature(fields, self.associations[handle]) 163 164 # Without an association, request verification of the signed items 165 # from the OpenID provider. 166 167 else: 168 return self.test_signature_direct(fields) 169 170 # Without a handle, no signature verification can occur. 171 172 return 0 173 174 def test_signature_direct(self, fields): 175 176 """ 177 See: 178 http://openid.net/specs/openid-authentication-2_0-12.html#rfc.section.11.4.2 179 """ 180 181 # Make a POST request using the "openid." fields. 182 183 d = {} 184 for name, values in fields.items(): 185 if name.startswith("openid.") and name != "openid.mode": 186 d[name] = values[0] 187 d["openid.mode"] = "check_authentication" 188 data = urllib.urlencode(d) 189 190 # Send a POST request to the OpenID provider, reading the response and 191 # testing for certain fields and values. 192 193 f = urllib.urlopen(fields["openid.op_endpoint"][0], data) 194 try: 195 items = [] 196 for line in f.readlines(): 197 if line[-1] == "\n": 198 line = line[:-1] 199 parts = line.split(":") 200 items.append((parts[0], ":".join(parts[1:]))) 201 fields = dict(items) 202 return fields["ns"] == self.openid_ns and fields["is_valid"] == "true" 203 finally: 204 f.close() 205 206 def test_replay(self, fields): 207 208 """ 209 See: 210 http://openid.net/specs/openid-authentication-2_0-12.html#rfc.section.11.3 211 """ 212 213 timestamp = fields["openid.response_nonce"][0] 214 # YYYY-MM-DDTHH:MM:SSZ... 215 year, month, day, hour, minute, second, unique = \ 216 int(timestamp[0:4]), int(timestamp[5:7]), int(timestamp[8:10]), \ 217 int(timestamp[11:13]), int(timestamp[14:16]), int(timestamp[17:19]), \ 218 timestamp[20:] 219 dt = datetime.datetime(year, month, day, hour, minute, second) 220 return -self.replay_limit < (datetime.datetime.utcnow() - dt) < self.replay_limit 221 222 def set_token(self, trans, username): 223 224 "Set an authentication token in 'trans' with the given 'username'." 225 226 Verifier.set_token(self, trans, username) 227 228 # Update the transaction with the user details. 229 230 trans.set_user(username) 231 232 # vim: tabstop=4 expandtab shiftwidth=4