#!/usr/bin/env python # -*- coding: iso8859-1 -*- # # Copyright (C) 2003, 2004 Edgewall Software # Copyright (C) 2003, 2004 Jonas Borgström # # Trac is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Trac is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # Author: Jonas Borgström # # Todo: # - External auth using mod_proxy / squid. import os import re import sys import md5 import time import shutil import getopt import locale import urllib import urllib2 import mimetypes import SocketServer import BaseHTTPServer import svn.core import trac.core import trac.util from trac.Href import Href from trac import auth, Wiki, siteconfig from trac.Environment import Environment class DigestAuth: """A simple HTTP DigestAuth implementation (rfc2617)""" MAX_NONCES = 100 def __init__(self, htdigest, realm): self.active_nonces = [] self.hash = {} self.realm = realm self.load_htdigest(htdigest, realm) def load_htdigest(self, filename, realm): """ Load account information from apache style htdigest files, only users from the specified realm are used """ fd = open(filename, 'r') for line in fd.readlines(): u, r, a1 = line.strip().split(':') if r == realm: self.hash[u] = a1 if self.hash == {}: print >> sys.stderr, "Warning: found no users in realm:", realm def parse_auth_header(self, authorization): values = {} for value in urllib2.parse_http_list(authorization): n, v = value.split('=', 1) if v[0] == '"' and v[-1] == '"': values[n] = v[1:-1] else: values[n] = v return values def send_auth_request(self, req, stale='false'): """ Send a digest challange to the browser. Record used nonces to avoid replay attacks. """ nonce = trac.util.hex_entropy() self.active_nonces.append(nonce) if len(self.active_nonces) > DigestAuth.MAX_NONCES: self.active_nonces = self.active_nonces[-DigestAuth.MAX_NONCES:] req.send_response(401) req.send_header('WWW-Authenticate', 'Digest realm="%s", nonce="%s", qop="auth", stale="%s"' % (self.realm, nonce, stale)) req.end_headers() def do_auth(self, req): if not 'Authorization' in req.headers or \ req.headers['Authorization'][:6] != 'Digest': self.send_auth_request(req) return None auth = self.parse_auth_header(req.headers['Authorization'][7:]) required_keys = ['username', 'realm', 'nonce', 'uri', 'response', 'nc', 'cnonce'] # Invalid response? for key in required_keys: if not auth.has_key(key): self.send_auth_request(req) return None # Unknown user? if not self.hash.has_key(auth['username']): self.send_auth_request(req) return None kd = lambda x: md5.md5(':'.join(x)).hexdigest() a1 = self.hash[auth['username']] a2 = kd([req.command, auth['uri']]) # Is the response correct? correct = kd([a1, auth['nonce'], auth['nc'], auth['cnonce'], auth['qop'], a2]) if auth['response'] != correct: self.send_auth_request(req) return None # Is the nonce active, if not ask the client to use a new one if not auth['nonce'] in self.active_nonces: self.send_auth_request(req, stale='true') return None self.active_nonces.remove(auth['nonce']) return auth['username'] class TracHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass class TracHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler, trac.core.Request): url_re = re.compile('/(?P[^/\?]+)' '(?P/?[^\?]*)?' '(?:\?(?P.*))?') server_version = 'tracd/' + trac.__version__ env = None def read(self, len): return self.rfile.read(len) def write(self, data): self.wfile.write(data) def init_request(self): trac.core.Request.init_request(self) self.remote_addr = str(self.client_address[0]) self.hdf.setValue('HTTP.Host', self.server.http_host) if self.headers.has_key('Cookie'): self.incookie.load(self.headers['Cookie']) def parse_path(self, path): m = self.url_re.findall(self.path) if not m: raise trac.util.TracError('Unknown URI') self.project_name, self.path_info, self.query_string = m[0] if not self.server.projects.has_key(self.project_name): raise trac.util.TracError('Unknown Project') self.env = self.server.projects[self.project_name] self.log = self.env.log self.cgi_location = '/' + self.project_name def log_message(self, format, *args): if self.env: self.log.debug(format%args) def do_project_index(self): self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.write('Available Projects') self.write('

Available Projects

    ') for project in self.server.projects.keys(): self.write('
  • %s
  • ' % (project, project)) self.write('
') def do_htdocs_req(self, path): """This function serves request for static img/css files""" path = urllib.unquote(path) # Make sure the path doesn't contain any dangerous ".."-parts. path = '/'.join(filter(lambda x: x not in ['..', ''], path.split('/'))) filename = os.path.join(siteconfig.__default_htdocs_dir__, os.path.normcase(path)) try: f = open(filename, 'rb') except IOError: self.send_error(404, path) return self.send_response(200) mtype, enc = mimetypes.guess_type(filename) stat = os.fstat(f.fileno()) content_length = stat[6] last_modified = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stat[8])) self.send_header('Content-Type', mtype) self.send_header('Conten-Length', str(content_length)) self.send_header('Last-Modified', last_modified) self.end_headers() shutil.copyfileobj(f, self.wfile) def do_POST(self): self.do_trac_req() def do_HEAD(self): self.do_GET() def do_GET(self): if self.path[0:13] == '/': self.do_project_index() elif self.path[0:13] == '/trac_common/': self.do_htdocs_req(self.path[13:]) else: self.do_trac_req() def do_trac_req(self): try: self.parse_path(self.path) except: self.send_error(404, 'Unknown request') return try: self.do_real_trac_req() except Exception, e: trac.core.send_pretty_error(e, self.env, self) def do_real_trac_req(self): start = time.time() self.init_request() db = self.env.get_db_cnx() self.remote_user = None if self.path_info == '/login': self.remote_user = self.env.auth.do_auth(self) if not self.remote_user: return Wiki.populate_page_dict(db, self.env) authenticator = auth.Authenticator(db, self) http_referer = self.headers.get('Referer', None) if self.path_info == '/logout': authenticator.logout() try: self.redirect (http_referer or self.env.href.wiki()) except trac.core.RedirectException: pass return if self.remote_user and authenticator.authname == 'anonymous': authenticator.login(self) if self.path_info == '/login': try: self.redirect (http_referer or self.env.href.wiki()) except trac.core.RedirectException: pass return self.authname = authenticator.authname # Parse arguments args = trac.core.parse_args(self.command, self.path_info, self.query_string, self.rfile, None, self.headers) trac.core.add_args_to_hdf(args, self.hdf) try: pool = None # Load the selected module module = trac.core.module_factory(args, self.env, db, self) pool = module.pool module.run() finally: if pool: svn.core.svn_pool_destroy(pool) self.log.debug('Total request time: %f s', time.time() - start) def usage(): print 'usage: %s [options] [database] ...' % sys.argv[0] print '\nOptions:\n' print '-a --auth [project],[htdigest_file],[realm]' print '-p --port [port]\t\tPort number to use (default: 80)' print '-b --hostname [hostname]\tIP to bind to (default: \'\')' print sys.exit(1) def main(): locale.setlocale(locale.LC_ALL, '') port = 80 hostname = '' auths = {} projects = {} try: opts, args = getopt.getopt(sys.argv[1:], "a:p:b:", ["auth=", "port=", "hostname="]) except getopt.GetoptError: usage() for o, a in opts: if o in ("-a", "--auth"): info = a.split(',', 3) if len(info) != 3: usage() p, h, r = info auths[p] = DigestAuth(h, r) if o in ("-p", "--port"): port = int(a) elif o in ("-b", "--hostname"): hostname = a if not args: usage() server_address = (hostname, port) httpd = TracHTTPServer(server_address, TracHTTPRequestHandler) if httpd.server_port == 80: httpd.http_host = httpd.server_name else: httpd.http_host = '%s:%d' % (httpd.server_name, httpd.server_port) for path in args: project = os.path.split(path)[1] if not project: project = os.path.split(path)[0] # We assume the database filenames follow the following # naming convention: /some/path/project.whatever auth = auths.get(project, None) env = Environment(path) # Upgrade the database schema if needed env.upgrade(backup=1) env.href = Href('/' + project) env.abs_href = Href('http://%s/%s' % (httpd.http_host, project)) projects[project] = env projects[project].set_config('trac', 'htdocs_location', '/trac_common/') projects[project].auth = auth httpd.projects = projects httpd.serve_forever() if __name__ == '__main__': main()