-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathserver.py
More file actions
275 lines (225 loc) · 9.65 KB
/
server.py
File metadata and controls
275 lines (225 loc) · 9.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/usr/bin/env python
import argparse
import errno
import json
import mimetypes
import os
from functools import partial
from functools import wraps
from urllib import parse as urlparse
import cherrypy
import yaml
from cherrypy import wsgiserver
from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter
from jinja2 import select_autoescape
from jinja2.environment import Environment
from jinja2.loaders import FileSystemLoader
from provider.authn import make_cls_from_name
from oic import rndstr
from oic.oic.provider import AuthorizationEndpoint
from oic.oic.provider import EndSessionEndpoint
from oic.oic.provider import Provider
from oic.oic.provider import RegistrationEndpoint
from oic.oic.provider import TokenEndpoint
from oic.oic.provider import UserinfoEndpoint
from oic.utils.authn.authn_context import AuthnBroker
from oic.utils.authn.client import verify_client
from oic.utils.authz import AuthzHandling
from oic.utils.http_util import BadRequest
from oic.utils.http_util import NotFound
from oic.utils.http_util import Response
from oic.utils.http_util import SeeOther
from oic.utils.http_util import get_or_post
from oic.utils.http_util import get_post
from oic.utils.keyio import keyjar_init
from oic.utils.sdb import create_session_db
from oic.utils.userinfo import UserInfo
from oic.utils.webfinger import OIC_ISSUER
from oic.utils.webfinger import WebFinger
try:
from cherrypy.wsgiserver.wsgiserver3 import WSGIPathInfoDispatcher
except ImportError:
from cherrypy.wsgiserver.wsgiserver2 import WSGIPathInfoDispatcher
def VerifierMiddleware(verifier):
"""Common wrapper for the authentication modules.
* Parses the request before passing it on to the authentication module.
* Sets 'pyoidc' cookie if authentication succeeds.
* Redirects the user to complete the authentication.
* Allows the user to retry authentication if it fails.
:param verifier: authentication module
"""
@wraps(verifier.verify)
def wrapper(environ, start_response):
data = get_post(environ)
kwargs = dict(urlparse.parse_qsl(data))
kwargs["state"] = json.loads(urlparse.unquote(kwargs["state"]))
val, completed = verifier.verify(**kwargs)
if not completed:
return val(environ, start_response)
if val:
set_cookie, cookie_value = verifier.create_cookie(val, "auth")
cookie_value += "; path=/"
url = "{base_url}?{query_string}".format(
base_url="/authorization",
query_string=urlparse.urlparse(environ.get("HTTP_REFERER")).query)
response = SeeOther(url, headers=[(set_cookie, cookie_value)])
return response(environ, start_response)
else: # Unsuccessful authentication
url = "{base_url}?{query_string}".format(
base_url="/authorization",
query_string=urlparse.urlparse(environ.get("HTTP_REFERER")).query)
response = SeeOther(url, headers=[(set_cookie, cookie_value)])
return response(environ, start_response)
response = SeeOther(url)
return response(environ, start_response)
return wrapper
def pyoidcMiddleware(func):
"""Common wrapper for the underlying pyoidc library functions.
Reads GET params and POST data before passing it on the library and
converts the response from oic.utils.http_util to wsgi.
:param func: underlying library function
"""
def wrapper(environ, start_response):
data = get_or_post(environ)
cookies = environ.get("HTTP_COOKIE", "")
if(environ.get("REQUEST_URI", "") == "/token"):
# This is correct at least for our case which is the authorization code flow.
resp = func(request=data, cookie=cookies, authn=environ.get("HTTP_AUTHORIZATION", ""))
else:
resp = func(request=data, cookie=cookies)
return resp(environ, start_response)
return wrapper
def resp2flask(resp):
"""Convert an oic.utils.http_util instance to Flask."""
if isinstance(resp, SeeOther):
code = int(resp.status.split()[0])
raise cherrypy.HTTPRedirect(resp.message, code)
return resp.message, resp.status, resp.headers
"""
Creates an AuthnBroker with the authentication methods set in settings.yaml.
:returns an AuthnBroker and the routing.
"""
def setup_authentication_methods(authn_config, template_env):
"""Add all authentication methods specified in the configuration."""
routing = {}
ac = AuthnBroker()
for authn_method in authn_config:
# Create instance of the appropiate auth class.
cls = make_cls_from_name(authn_method["class"])
instance = cls(template_env=template_env, **authn_method["kwargs"])
# Adds the auth method name to the broker.
ac.add(authn_method["acr"], instance)
routing[instance.url_endpoint] = VerifierMiddleware(instance)
return ac, routing
def setup_endpoints(provider):
"""Setup the OpenID Connect Provider endpoints."""
app_routing = {}
# Each provider.***** is a pointer to a function
endpoints = [
AuthorizationEndpoint(
pyoidcMiddleware(provider.authorization_endpoint)),
TokenEndpoint(
pyoidcMiddleware(provider.token_endpoint)),
UserinfoEndpoint(
pyoidcMiddleware(provider.userinfo_endpoint)),
RegistrationEndpoint(
pyoidcMiddleware(provider.registration_endpoint)),
EndSessionEndpoint(
pyoidcMiddleware(provider.endsession_endpoint))
]
provider.endp = endpoints
for ep in endpoints:
app_routing["/{}".format(ep.etype)] = ep
return app_routing
def _webfinger(provider, request, **kwargs):
"""Handle webfinger requests."""
params = urlparse.parse_qs(request)
if params["rel"][0] == OIC_ISSUER:
wf = WebFinger()
return Response(wf.response(params["resource"][0], provider.baseurl),
headers=[("Content-Type", "application/jrd+json")])
else:
return BadRequest("Incorrect webfinger.")
def make_static_handler(static_dir):
def static(environ, start_response):
path = environ['PATH_INFO']
full_path = os.path.join(static_dir, os.path.normpath(path).lstrip("/"))
if os.path.exists(full_path):
with open(full_path, 'rb') as f:
content = f.read()
content_type, encoding = mimetypes.guess_type(full_path)
headers = [('Content-Type', content_type)]
start_response("200 OK", headers)
return [content]
else:
response = NotFound(
"File '{}' not found.".format(environ['PATH_INFO']))
return response(environ, start_response)
return static
def main():
parser = argparse.ArgumentParser(description='Example OIDC Provider.')
parser.add_argument("-p", "--port", default=80, type=int)
parser.add_argument("-b", "--base", default="https://localhost", type=str)
parser.add_argument("-d", "--debug", action="store_true")
parser.add_argument("settings")
args = parser.parse_args()
# Load configuration
with open(args.settings, "r") as f:
settings = yaml.safe_load(f)
issuer = args.base.rstrip("/")
template_dirs = settings["server"].get("template_dirs", "templates")
jinja_env = Environment(loader=FileSystemLoader(template_dirs),
autoescape=select_autoescape(['html']))
authn_broker, auth_routing = setup_authentication_methods(settings["authn"],
jinja_env)
# Setup userinfo
userinfo_conf = settings["userinfo"]
cls = make_cls_from_name(userinfo_conf["class"])
i = cls(**userinfo_conf["kwargs"])
userinfo = UserInfo(i)
client_db = {}
session_db = create_session_db(issuer,
secret=rndstr(32), password=rndstr(32))
# verify_client is a pointer to that function which is used in the token endpoint.
provider = Provider(issuer, session_db, client_db, authn_broker,
userinfo, AuthzHandling(), verify_client, None)
provider.baseurl = issuer
provider.symkey = rndstr(16)
# Setup keys
path = os.path.join(os.path.dirname(__file__), "static")
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise e
pass
jwks = keyjar_init(provider, settings["provider"]["keys"])
name = "jwks.json"
with open(os.path.join(path, name), "w") as f:
f.write(json.dumps(jwks))
#TODO: I take this out and it still works, what was this for?
#provider.jwks_uri.append(
# "{}/static/{}".format(provider.baseurl, name))
# Mount the WSGI callable object (app) on the root directory
app_routing = setup_endpoints(provider)
app_routing["/.well-known/openid-configuration"] = pyoidcMiddleware(
provider.providerinfo_endpoint)
app_routing["/.well-known/webfinger"] = pyoidcMiddleware(
partial(_webfinger, provider))
routing = dict(list(auth_routing.items()) + list(app_routing.items()))
routing["/static"] = make_static_handler(path)
dispatcher = WSGIPathInfoDispatcher(routing)
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', args.port), dispatcher) # nosec
# Setup SSL
if provider.baseurl.startswith("https://"):
server.ssl_adapter = BuiltinSSLAdapter(
settings["server"]["cert"], settings["server"]["key"],
settings["server"]["cert_chain"])
# Start the CherryPy WSGI web server
try:
print("Server started: {}".format(issuer))
server.start()
except KeyboardInterrupt:
server.stop()
if __name__ == "__main__":
main()