PageRenderTime 45ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/portal.policy/Paste-1.7.4-py2.4.egg/paste/auth/auth_tkt.py

https://bitbucket.org/eaviles/gobierno
Python | 380 lines | 318 code | 7 blank | 55 comment | 6 complexity | 2ef0313c499cb56bf0497f8a52646732 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0
  1. # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
  2. # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
  3. ##########################################################################
  4. #
  5. # Copyright (c) 2005 Imaginary Landscape LLC and Contributors.
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining
  8. # a copy of this software and associated documentation files (the
  9. # "Software"), to deal in the Software without restriction, including
  10. # without limitation the rights to use, copy, modify, merge, publish,
  11. # distribute, sublicense, and/or sell copies of the Software, and to
  12. # permit persons to whom the Software is furnished to do so, subject to
  13. # the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be
  16. # included in all copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  19. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. ##########################################################################
  26. """
  27. Implementation of cookie signing as done in `mod_auth_tkt
  28. <http://www.openfusion.com.au/labs/mod_auth_tkt/>`_.
  29. mod_auth_tkt is an Apache module that looks for these signed cookies
  30. and sets ``REMOTE_USER``, ``REMOTE_USER_TOKENS`` (a comma-separated
  31. list of groups) and ``REMOTE_USER_DATA`` (arbitrary string data).
  32. This module is an alternative to the ``paste.auth.cookie`` module;
  33. it's primary benefit is compatibility with mod_auth_tkt, which in turn
  34. makes it possible to use the same authentication process with
  35. non-Python code run under Apache.
  36. """
  37. import time as time_mod
  38. try:
  39. from hashlib import md5
  40. except ImportError:
  41. from md5 import md5
  42. import Cookie
  43. from paste import request
  44. class AuthTicket(object):
  45. """
  46. This class represents an authentication token. You must pass in
  47. the shared secret, the userid, and the IP address. Optionally you
  48. can include tokens (a list of strings, representing role names),
  49. 'user_data', which is arbitrary data available for your own use in
  50. later scripts. Lastly, you can override the cookie name and
  51. timestamp.
  52. Once you provide all the arguments, use .cookie_value() to
  53. generate the appropriate authentication ticket. .cookie()
  54. generates a Cookie object, the str() of which is the complete
  55. cookie header to be sent.
  56. CGI usage::
  57. token = auth_tkt.AuthTick('sharedsecret', 'username',
  58. os.environ['REMOTE_ADDR'], tokens=['admin'])
  59. print 'Status: 200 OK'
  60. print 'Content-type: text/html'
  61. print token.cookie()
  62. print
  63. ... redirect HTML ...
  64. Webware usage::
  65. token = auth_tkt.AuthTick('sharedsecret', 'username',
  66. self.request().environ()['REMOTE_ADDR'], tokens=['admin'])
  67. self.response().setCookie('auth_tkt', token.cookie_value())
  68. Be careful not to do an HTTP redirect after login; use meta
  69. refresh or Javascript -- some browsers have bugs where cookies
  70. aren't saved when set on a redirect.
  71. """
  72. def __init__(self, secret, userid, ip, tokens=(), user_data='',
  73. time=None, cookie_name='auth_tkt',
  74. secure=False):
  75. self.secret = secret
  76. self.userid = userid
  77. self.ip = ip
  78. self.tokens = ','.join(tokens)
  79. self.user_data = user_data
  80. if time is None:
  81. self.time = time_mod.time()
  82. else:
  83. self.time = time
  84. self.cookie_name = cookie_name
  85. self.secure = secure
  86. def digest(self):
  87. return calculate_digest(
  88. self.ip, self.time, self.secret, self.userid, self.tokens,
  89. self.user_data)
  90. def cookie_value(self):
  91. v = '%s%08x%s!' % (self.digest(), int(self.time), self.userid)
  92. if self.tokens:
  93. v += self.tokens + '!'
  94. v += self.user_data
  95. return v
  96. def cookie(self):
  97. c = Cookie.SimpleCookie()
  98. c[self.cookie_name] = self.cookie_value().encode('base64').strip().replace('\n', '')
  99. c[self.cookie_name]['path'] = '/'
  100. if self.secure:
  101. c[self.cookie_name]['secure'] = 'true'
  102. return c
  103. class BadTicket(Exception):
  104. """
  105. Exception raised when a ticket can't be parsed. If we get
  106. far enough to determine what the expected digest should have
  107. been, expected is set. This should not be shown by default,
  108. but can be useful for debugging.
  109. """
  110. def __init__(self, msg, expected=None):
  111. self.expected = expected
  112. Exception.__init__(self, msg)
  113. def parse_ticket(secret, ticket, ip):
  114. """
  115. Parse the ticket, returning (timestamp, userid, tokens, user_data).
  116. If the ticket cannot be parsed, ``BadTicket`` will be raised with
  117. an explanation.
  118. """
  119. ticket = ticket.strip('"')
  120. digest = ticket[:32]
  121. try:
  122. timestamp = int(ticket[32:40], 16)
  123. except ValueError, e:
  124. raise BadTicket('Timestamp is not a hex integer: %s' % e)
  125. try:
  126. userid, data = ticket[40:].split('!', 1)
  127. except ValueError:
  128. raise BadTicket('userid is not followed by !')
  129. if '!' in data:
  130. tokens, user_data = data.split('!', 1)
  131. else:
  132. # @@: Is this the right order?
  133. tokens = ''
  134. user_data = data
  135. expected = calculate_digest(ip, timestamp, secret,
  136. userid, tokens, user_data)
  137. if expected != digest:
  138. raise BadTicket('Digest signature is not correct',
  139. expected=(expected, digest))
  140. tokens = tokens.split(',')
  141. return (timestamp, userid, tokens, user_data)
  142. def calculate_digest(ip, timestamp, secret, userid, tokens, user_data):
  143. secret = maybe_encode(secret)
  144. userid = maybe_encode(userid)
  145. tokens = maybe_encode(tokens)
  146. user_data = maybe_encode(user_data)
  147. digest0 = md5(
  148. encode_ip_timestamp(ip, timestamp) + secret + userid + '\0'
  149. + tokens + '\0' + user_data).hexdigest()
  150. digest = md5(digest0 + secret).hexdigest()
  151. return digest
  152. def encode_ip_timestamp(ip, timestamp):
  153. ip_chars = ''.join(map(chr, map(int, ip.split('.'))))
  154. t = int(timestamp)
  155. ts = ((t & 0xff000000) >> 24,
  156. (t & 0xff0000) >> 16,
  157. (t & 0xff00) >> 8,
  158. t & 0xff)
  159. ts_chars = ''.join(map(chr, ts))
  160. return ip_chars + ts_chars
  161. def maybe_encode(s, encoding='utf8'):
  162. if isinstance(s, unicode):
  163. s = s.encode(encoding)
  164. return s
  165. class AuthTKTMiddleware(object):
  166. """
  167. Middleware that checks for signed cookies that match what
  168. `mod_auth_tkt <http://www.openfusion.com.au/labs/mod_auth_tkt/>`_
  169. looks for (if you have mod_auth_tkt installed, you don't need this
  170. middleware, since Apache will set the environmental variables for
  171. you).
  172. Arguments:
  173. ``secret``:
  174. A secret that should be shared by any instances of this application.
  175. If this app is served from more than one machine, they should all
  176. have the same secret.
  177. ``cookie_name``:
  178. The name of the cookie to read and write from. Default ``auth_tkt``.
  179. ``secure``:
  180. If the cookie should be set as 'secure' (only sent over SSL) and if
  181. the login must be over SSL. (Defaults to False)
  182. ``httponly``:
  183. If the cookie should be marked as HttpOnly, which means that it's
  184. not accessible to JavaScript. (Defaults to False)
  185. ``include_ip``:
  186. If the cookie should include the user's IP address. If so, then
  187. if they change IPs their cookie will be invalid.
  188. ``logout_path``:
  189. The path under this middleware that should signify a logout. The
  190. page will be shown as usual, but the user will also be logged out
  191. when they visit this page.
  192. If used with mod_auth_tkt, then these settings (except logout_path) should
  193. match the analogous Apache configuration settings.
  194. This also adds two functions to the request:
  195. ``environ['paste.auth_tkt.set_user'](userid, tokens='', user_data='')``
  196. This sets a cookie that logs the user in. ``tokens`` is a
  197. string (comma-separated groups) or a list of strings.
  198. ``user_data`` is a string for your own use.
  199. ``environ['paste.auth_tkt.logout_user']()``
  200. Logs out the user.
  201. """
  202. def __init__(self, app, secret, cookie_name='auth_tkt', secure=False,
  203. include_ip=True, logout_path=None, httponly=False,
  204. no_domain_cookie=True, current_domain_cookie=True,
  205. wildcard_cookie=True):
  206. self.app = app
  207. self.secret = secret
  208. self.cookie_name = cookie_name
  209. self.secure = secure
  210. self.httponly = httponly
  211. self.include_ip = include_ip
  212. self.logout_path = logout_path
  213. self.no_domain_cookie = no_domain_cookie
  214. self.current_domain_cookie = current_domain_cookie
  215. self.wildcard_cookie = wildcard_cookie
  216. def __call__(self, environ, start_response):
  217. cookies = request.get_cookies(environ)
  218. if cookies.has_key(self.cookie_name):
  219. cookie_value = cookies[self.cookie_name].value
  220. else:
  221. cookie_value = ''
  222. if cookie_value:
  223. if self.include_ip:
  224. remote_addr = environ['REMOTE_ADDR']
  225. else:
  226. # mod_auth_tkt uses this dummy value when IP is not
  227. # checked:
  228. remote_addr = '0.0.0.0'
  229. # @@: This should handle bad signatures better:
  230. # Also, timeouts should cause cookie refresh
  231. try:
  232. timestamp, userid, tokens, user_data = parse_ticket(
  233. self.secret, cookie_value, remote_addr)
  234. tokens = ','.join(tokens)
  235. environ['REMOTE_USER'] = userid
  236. if environ.get('REMOTE_USER_TOKENS'):
  237. # We want to add tokens/roles to what's there:
  238. tokens = environ['REMOTE_USER_TOKENS'] + ',' + tokens
  239. environ['REMOTE_USER_TOKENS'] = tokens
  240. environ['REMOTE_USER_DATA'] = user_data
  241. environ['AUTH_TYPE'] = 'cookie'
  242. except BadTicket:
  243. # bad credentials, just ignore without logging the user
  244. # in or anything
  245. pass
  246. set_cookies = []
  247. def set_user(userid, tokens='', user_data=''):
  248. set_cookies.extend(self.set_user_cookie(
  249. environ, userid, tokens, user_data))
  250. def logout_user():
  251. set_cookies.extend(self.logout_user_cookie(environ))
  252. environ['paste.auth_tkt.set_user'] = set_user
  253. environ['paste.auth_tkt.logout_user'] = logout_user
  254. if self.logout_path and environ.get('PATH_INFO') == self.logout_path:
  255. logout_user()
  256. def cookie_setting_start_response(status, headers, exc_info=None):
  257. headers.extend(set_cookies)
  258. return start_response(status, headers, exc_info)
  259. return self.app(environ, cookie_setting_start_response)
  260. def set_user_cookie(self, environ, userid, tokens, user_data):
  261. if not isinstance(tokens, basestring):
  262. tokens = ','.join(tokens)
  263. if self.include_ip:
  264. remote_addr = environ['REMOTE_ADDR']
  265. else:
  266. remote_addr = '0.0.0.0'
  267. ticket = AuthTicket(
  268. self.secret,
  269. userid,
  270. remote_addr,
  271. tokens=tokens,
  272. user_data=user_data,
  273. cookie_name=self.cookie_name,
  274. secure=self.secure)
  275. # @@: Should we set REMOTE_USER etc in the current
  276. # environment right now as well?
  277. cur_domain = environ.get('HTTP_HOST', environ.get('SERVER_NAME'))
  278. wild_domain = '.' + cur_domain
  279. cookie_options = ""
  280. if self.secure:
  281. cookie_options += "; secure"
  282. if self.httponly:
  283. cookie_options += "; HttpOnly"
  284. cookies = []
  285. if self.no_domain_cookie:
  286. cookies.append(('Set-Cookie', '%s=%s; Path=/%s' % (
  287. self.cookie_name, ticket.cookie_value(), cookie_options)))
  288. if self.current_domain_cookie:
  289. cookies.append(('Set-Cookie', '%s=%s; Path=/; Domain=%s%s' % (
  290. self.cookie_name, ticket.cookie_value(), cur_domain,
  291. cookie_options)))
  292. if self.wildcard_cookie:
  293. cookies.append(('Set-Cookie', '%s=%s; Path=/; Domain=%s%s' % (
  294. self.cookie_name, ticket.cookie_value(), wild_domain,
  295. cookie_options)))
  296. return cookies
  297. def logout_user_cookie(self, environ):
  298. cur_domain = environ.get('HTTP_HOST', environ.get('SERVER_NAME'))
  299. wild_domain = '.' + cur_domain
  300. expires = 'Sat, 01-Jan-2000 12:00:00 GMT'
  301. cookies = [
  302. ('Set-Cookie', '%s=""; Expires="%s"; Path=/' % (self.cookie_name, expires)),
  303. ('Set-Cookie', '%s=""; Expires="%s"; Path=/; Domain=%s' %
  304. (self.cookie_name, expires, cur_domain)),
  305. ('Set-Cookie', '%s=""; Expires="%s"; Path=/; Domain=%s' %
  306. (self.cookie_name, expires, wild_domain)),
  307. ]
  308. return cookies
  309. def make_auth_tkt_middleware(
  310. app,
  311. global_conf,
  312. secret=None,
  313. cookie_name='auth_tkt',
  314. secure=False,
  315. include_ip=True,
  316. logout_path=None):
  317. """
  318. Creates the `AuthTKTMiddleware
  319. <class-paste.auth.auth_tkt.AuthTKTMiddleware.html>`_.
  320. ``secret`` is requird, but can be set globally or locally.
  321. """
  322. from paste.deploy.converters import asbool
  323. secure = asbool(secure)
  324. include_ip = asbool(include_ip)
  325. if secret is None:
  326. secret = global_conf.get('secret')
  327. if not secret:
  328. raise ValueError(
  329. "You must provide a 'secret' (in global or local configuration)")
  330. return AuthTKTMiddleware(
  331. app, secret, cookie_name, secure, include_ip, logout_path or None)