|
| 1 | +import os |
| 2 | +import ConfigParser |
| 3 | +import optparse |
| 4 | +import logging |
| 5 | +import shutil |
| 6 | +import urlparse |
| 7 | + |
| 8 | +from StringIO import StringIO |
| 9 | +from BaseHTTPServer import BaseHTTPRequestHandler |
| 10 | +from BaseHTTPServer import HTTPServer |
| 11 | + |
| 12 | +from onelogin.saml import AuthRequest, Response |
| 13 | + |
| 14 | +__version__ = '0.1' |
| 15 | + |
| 16 | +log = logging.getLogger(__name__) |
| 17 | + |
| 18 | +class SampleAppHTTPRequestHandler(BaseHTTPRequestHandler): |
| 19 | + server_version = 'SampleAppHTTPRequestHandler/%s' % __version__ |
| 20 | + |
| 21 | + def _serve_msg(self, code, msg): |
| 22 | + f = StringIO() |
| 23 | + f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">') |
| 24 | + f.write("<html>\n<body>\n%s</body>\n</html>\n" % msg) |
| 25 | + length = f.tell() |
| 26 | + f.seek(0) |
| 27 | + |
| 28 | + if code == 200: |
| 29 | + self.send_response(code) |
| 30 | + else: |
| 31 | + self.send_error(code, message=msg) |
| 32 | + |
| 33 | + self.send_header('Content-type', 'text/html') |
| 34 | + self.send_header('Content-Length', str(length)) |
| 35 | + self.end_headers() |
| 36 | + |
| 37 | + shutil.copyfileobj(f, self.wfile) |
| 38 | + |
| 39 | + def _bad_request(self): |
| 40 | + """Serve Bad Request (400).""" |
| 41 | + self._serve_msg(400, 'Bad Request') |
| 42 | + |
| 43 | + def log_message(self, format, *args): |
| 44 | + log.info(format % args) |
| 45 | + |
| 46 | + def do_HEAD(self): |
| 47 | + """Serve a HEAD request.""" |
| 48 | + self._bad_request() |
| 49 | + |
| 50 | + def do_DEL(self): |
| 51 | + """Serve a DEL request.""" |
| 52 | + self._bad_request() |
| 53 | + |
| 54 | + def do_GET(self): |
| 55 | + """Serve a GET request.""" |
| 56 | + if not self.path == '/': |
| 57 | + self._bad_request() |
| 58 | + return |
| 59 | + |
| 60 | + url = AuthRequest.create(**self.settings) |
| 61 | + self.send_response(301) |
| 62 | + self.send_header("Location", url) |
| 63 | + self.end_headers() |
| 64 | + |
| 65 | + def do_POST(self): |
| 66 | + """Serve a POST request.""" |
| 67 | + if not self.path == self.saml_post_path: |
| 68 | + self._bad_request() |
| 69 | + return |
| 70 | + |
| 71 | + length = int(self.headers['Content-Length']) |
| 72 | + data = self.rfile.read(length) |
| 73 | + query = urlparse.parse_qs(data) |
| 74 | + res = Response( |
| 75 | + query['SAMLResponse'].pop(), |
| 76 | + self.settings['idp_cert_fingerprint'], |
| 77 | + ) |
| 78 | + valid = res.is_valid() |
| 79 | + name_id = res.name_id |
| 80 | + if valid: |
| 81 | + msg = 'The identify of {name_id} has been verified'.format( |
| 82 | + name_id=name_id, |
| 83 | + ) |
| 84 | + self._serve_msg(200, msg) |
| 85 | + else: |
| 86 | + msg = '{name_id} is not authorized to use this resource'.format( |
| 87 | + name_id=name_id, |
| 88 | + ) |
| 89 | + self._serve_msg(401, msg) |
| 90 | + |
| 91 | +def main(config_file): |
| 92 | + logging.basicConfig( |
| 93 | + level=logging.INFO, |
| 94 | + format='%(asctime)s.%(msecs)03d example: %(levelname)s: %(message)s', |
| 95 | + datefmt='%Y-%m-%dT%H:%M:%S', |
| 96 | + ) |
| 97 | + |
| 98 | + config = ConfigParser.RawConfigParser() |
| 99 | + config_path = os.path.expanduser(config_file) |
| 100 | + config_path = os.path.abspath(config_path) |
| 101 | + with open(config_path) as f: |
| 102 | + config.readfp(f) |
| 103 | + |
| 104 | + host = config.get('app', 'host') |
| 105 | + port = config.get('app', 'port') |
| 106 | + port = int(port) |
| 107 | + |
| 108 | + settings = dict() |
| 109 | + settings['assertion_consumer_service_url'] = config.get( |
| 110 | + 'saml', |
| 111 | + 'assertion_consumer_service_url' |
| 112 | + ) |
| 113 | + settings['issuer'] = config.get( |
| 114 | + 'saml', |
| 115 | + 'issuer' |
| 116 | + ) |
| 117 | + settings['name_identifier_format'] = config.get( |
| 118 | + 'saml', |
| 119 | + 'name_identifier_format' |
| 120 | + ) |
| 121 | + settings['idp_sso_target_url'] = config.get( |
| 122 | + 'saml', |
| 123 | + 'idp_sso_target_url' |
| 124 | + ) |
| 125 | + settings['idp_cert_file'] = config.get( |
| 126 | + 'saml', |
| 127 | + 'idp_cert_file' |
| 128 | + ) |
| 129 | + settings['idp_cert_fingerprint'] = config.get( |
| 130 | + 'saml', |
| 131 | + 'idp_cert_fingerprint' |
| 132 | + ) |
| 133 | + |
| 134 | + cert_file = settings.pop('idp_cert_file', None) |
| 135 | + |
| 136 | + # idp_cert_file has priority over idp_cert_fingerprint |
| 137 | + if cert_file: |
| 138 | + cert_path = os.path.expanduser(cert_file) |
| 139 | + cert_path = os.path.abspath(cert_path) |
| 140 | + |
| 141 | + with open(cert_path) as f: |
| 142 | + settings['idp_cert_fingerprint'] = f.read() |
| 143 | + |
| 144 | + parts = urlparse.urlparse(settings['assertion_consumer_service_url']) |
| 145 | + SampleAppHTTPRequestHandler.protocol_version = 'HTTP/1.0' |
| 146 | + SampleAppHTTPRequestHandler.settings = settings |
| 147 | + SampleAppHTTPRequestHandler.saml_post_path = parts.path |
| 148 | + httpd = HTTPServer( |
| 149 | + (host, port), |
| 150 | + SampleAppHTTPRequestHandler, |
| 151 | + ) |
| 152 | + |
| 153 | + socket_name = httpd.socket.getsockname() |
| 154 | + |
| 155 | + log.info( |
| 156 | + 'Serving HTTP on {host} port {port} ...'.format( |
| 157 | + host=socket_name[0], |
| 158 | + port=socket_name[1], |
| 159 | + ) |
| 160 | + ) |
| 161 | + |
| 162 | + httpd.serve_forever() |
| 163 | + |
| 164 | +if __name__ == '__main__': |
| 165 | + parser = optparse.OptionParser( |
| 166 | + usage='%prog [OPTS]', |
| 167 | + ) |
| 168 | + parser.add_option( |
| 169 | + '--config-file', |
| 170 | + metavar='PATH', |
| 171 | + help='The configuration file containing the app and SAML settings', |
| 172 | + ) |
| 173 | + |
| 174 | + parser.set_defaults( |
| 175 | + config_file='example.cfg' |
| 176 | + ) |
| 177 | + |
| 178 | + options, args = parser.parse_args() |
| 179 | + if args: |
| 180 | + parser.error('Wrong number of arguments') |
| 181 | + |
| 182 | + main(options.config_file) |
0 commit comments