forked from salrashid123/googlapps-sso
-
Notifications
You must be signed in to change notification settings - Fork 0
/
saml_idp_gsuites.py
executable file
·367 lines (298 loc) · 11.8 KB
/
saml_idp_gsuites.py
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
#!/usr/bin/python
import base64
import cgi
import datetime
import getopt
import getpass
import httplib
import json
import logging
import md5
import os
import pprint
import random
import socket
import ssl
import sys
import time
import urllib
import urllib2
import uuid
import xml.dom.minidom
import zlib
from socket import gethostname
from urlparse import urlparse
from xml.sax.saxutils import escape
import libxml2
import xmlsec
from flask import (Flask, Response, abort, jsonify, redirect, render_template,
request, send_from_directory, session)
app = Flask(__name__, static_url_path='')
app.secret_key = 'notasecret'
debug_flag = False
saml_issuer = "authn.py"
key_file = ''
key_pwd = ''
cert_file = None
class SignatureError(Exception):
pass
def getrandom_samlID():
return random.choice('abcdefghijklmnopqrstuvwxyz') + hex(random.getrandbits(160))[2:-1]
def _generate_response(now, later, username, login_req_id, recipient, audience):
resp_rand_id = getrandom_samlID()
rand_id_assert = getrandom_samlID()
sigtmpl = ''
key_info = ''
sigtmpl = ('<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">'
'<ds:SignedInfo>'
'<ds:CanonicalizationMethod '
'Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />'
'<ds:SignatureMethod '
'Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />'
'<ds:Reference URI="#%s">'
'<ds:Transforms>'
'<ds:Transform Algorithm='
'"http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>'
'</ds:Transforms>'
'<ds:DigestMethod Algorithm='
'"http://www.w3.org/2000/09/xmldsig#sha1" />'
'<ds:DigestValue></ds:DigestValue>'
'</ds:Reference>'
'</ds:SignedInfo>'
'<ds:SignatureValue/>'
'<ds:KeyInfo>'
'<ds:X509Data>'
'<ds:X509Certificate></ds:X509Certificate>'
'</ds:X509Data>'
'</ds:KeyInfo>'
'</ds:Signature>') % (resp_rand_id)
resp = ('<samlp:Response '
'xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" '
'xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" '
'ID="%s" InResponseTo="%s" Version="2.0" IssueInstant="%s" Destination="%s">'
'<saml:Issuer>%s</saml:Issuer>'
'%s'
'<samlp:Status>'
'<samlp:StatusCode '
'Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>'
'</samlp:Status>'
'<saml:Assertion '
'Version="2.0" ID="%s" IssueInstant="%s">'
'<saml:Issuer>%s</saml:Issuer>'
'<saml:Subject>'
'<saml:NameID>%s</saml:NameID>'
'<saml:SubjectConfirmation '
'Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">'
'<saml:SubjectConfirmationData '
'InResponseTo="%s" Recipient="%s" NotOnOrAfter="%s"/>'
'</saml:SubjectConfirmation>'
'</saml:Subject>'
'<saml:Conditions NotBefore="%s" NotOnOrAfter="%s">'
'<saml:AudienceRestriction>'
'<saml:Audience>%s</saml:Audience>'
'</saml:AudienceRestriction>'
'</saml:Conditions>'
'<saml:AuthnStatement AuthnInstant="%s" SessionIndex="%s">'
'<saml:AuthnContext>'
'<saml:AuthnContextClassRef>'
'urn:oasis:names:tc:SAML:2.0:ac:classes:Password'
'</saml:AuthnContextClassRef>'
'</saml:AuthnContext>'
'</saml:AuthnStatement>'
'</saml:Assertion>'
'</samlp:Response>') % (resp_rand_id, login_req_id, now, recipient,
saml_issuer, sigtmpl, rand_id_assert, now,
saml_issuer, username,
login_req_id, recipient, later,
now, later, audience,
now, rand_id_assert)
resp = '<!DOCTYPE samlp:Response [<!ATTLIST samlp:Response ID ID #IMPLIED>]>' + resp
resp = _signXML(resp)
return resp
def _signXML(xml):
dsigctx = None
doc = None
try:
# initialization
libxml2.initParser()
libxml2.substituteEntitiesDefault(1)
if xmlsec.init() < 0:
raise SignatureError('xmlsec init failed')
if xmlsec.checkVersion() != 1:
raise SignatureError('incompatible xmlsec library version %s' %
str(xmlsec.checkVersion()))
if xmlsec.cryptoAppInit(None) < 0:
raise SignatureError('crypto initialization failed')
if xmlsec.cryptoInit() < 0:
raise SignatureError('xmlsec-crypto initialization failed')
# load the input
doc = libxml2.parseDoc(xml)
if not doc or not doc.getRootElement():
raise SignatureError('error parsing input xml')
node = xmlsec.findNode(doc.getRootElement(), xmlsec.NodeSignature,
xmlsec.DSigNs)
if not node:
raise SignatureError("couldn't find root node")
dsigctx = xmlsec.DSigCtx()
key = xmlsec.cryptoAppKeyLoad(key_file, xmlsec.KeyDataFormatPem,
key_pwd, None, None)
if not key:
raise SignatureError(
'failed to load the private key %s' % key_file)
dsigctx.signKey = key
if key.setName(key_file) < 0:
raise SignatureError('failed to set key name')
if xmlsec.cryptoAppKeyCertLoad(key, cert_file, xmlsec.KeyDataFormatPem) < 0:
print "Error: failed to load pem certificate \"%s\"" % cert_file
return cleanup(doc, dsigctx)
# sign
if dsigctx.sign(node) < 0:
raise SignatureError('signing failed')
signed_xml = doc.serialize()
finally:
if dsigctx:
dsigctx.destroy()
if doc:
doc.freeDoc()
xmlsec.cryptoShutdown()
xmlsec.shutdown()
libxml2.cleanupParser()
return signed_xml
def cleanup(doc=None, dsig_ctx=None, res=-1):
if dsig_ctx is not None:
dsig_ctx.destroy()
if doc is not None:
doc.freeDoc()
return res
def log(msg):
print ('[%s] %s') % (datetime.datetime.now(), msg)
def decode_base64_and_inflate(b64string):
decoded_data = base64.b64decode(b64string)
return zlib.decompress(decoded_data, -15)
def deflate_and_base64_encode(string_val):
zlibbed_str = zlib.compress(string_val)
compressed_string = zlibbed_str[2:-4]
return base64.b64encode(compressed_string)
@app.route('/public/<path:path>')
def send_file(path):
return send_from_directory('public', path)
@app.route('/')
def index():
logged_in_user = ''
if ('user' in session):
logged_in_user = session['user']
return render_template('login.html', footer_username=logged_in_user)
@app.route('/_ah/health')
def health():
return('ok')
@app.route('/login')
def login():
RelayState = request.args.get('RelayState')
SAMLRequest = request.args.get('SAMLRequest')
if (RelayState is not None):
session['RelayState'] = RelayState
log(' RelayState' + str(RelayState))
if (SAMLRequest is not None):
session['SAMLRequest'] = SAMLRequest
log('SAMLRequest' + str(SAMLRequest))
# TODO: validate the saml request for namespace, format
if ('user' in session and RelayState != None and SAMLRequest != None):
return _postResoponse(session['user'])
return render_template('login.html')
def _postResoponse(username):
RelayState = session['RelayState']
SAMLRequest = session['SAMLRequest']
if debug_flag:
log('SAMLRequest ' + str(SAMLRequest))
decoded_saml = decode_base64_and_inflate(SAMLRequest)
xmldoc = xml.dom.minidom.parseString(decoded_saml)
saml_oissuer = None
req_id = None
acs_url = None
samlpnode = xmldoc.getElementsByTagName('samlp:AuthnRequest')
for node in samlpnode:
if node.nodeName == 'samlp:AuthnRequest':
if samlpnode[0].hasAttribute('ID'):
req_id = samlpnode[0].attributes['ID'].value
samliss = node.getElementsByTagName('saml:Issuer')
for n_issuer in samliss:
cnode = n_issuer.childNodes[0]
if cnode.nodeType == node.TEXT_NODE:
saml_oissuer = cnode.nodeValue
if samlpnode[0].hasAttribute('AssertionConsumerServiceURL'):
acs_url = samlpnode[0].attributes['AssertionConsumerServiceURL'].value
else:
log('NO AssertionConsumerServiceURL sent in saml request')
return render_template('login.html', error_string="Error: No AssertionConsumerServiceURL provided in SAMLRequest")
if debug_flag:
log('login Parsed AssertionConsumerServiceURL: %s' % (acs_url))
if not req_id:
log('Error: could not parse request SAML request ID')
return render_template('login.html', error_string="Error: could not parse request SAML request ID")
if acs_url:
redirect_location = acs_url
if debug_flag:
log('Redirecting to: %s' % (redirect_location))
log('----------- LOGIN END -----------')
now = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
five_sec_from_now = time.strftime(
'%Y-%m-%dT%H:%M:%SZ', time.gmtime(time.time()+30))
samlresp = _generate_response(now, five_sec_from_now, session['user'],
req_id, acs_url,
saml_oissuer)
log(xml.dom.minidom.parseString(samlresp).toprettyxml())
samlresp = samlresp.replace("""<!DOCTYPE samlp:Response [<!ATTLIST samlp:Response ID ID #IMPLIED>]>""", "")
return render_template('response.html', redirect_location=redirect_location, relay_state=RelayState,
saml_response=base64.encodestring(samlresp),
decoded_saml=xml.dom.minidom.parseString(samlresp).toprettyxml())
@app.route('/authenticate', methods=["POST"])
def autheticate():
username = request.form.get('username')
password = request.form.get('password')
if 'SAMLRequest' not in session:
session['user'] = username
return render_template('portal.html', footer_username=session['user'])
# AUTO LOG THE USER IN
# TODO: validate via ldap, etc
session['user'] = username
return _postResoponse(username)
@app.route('/logout')
def logout():
session.clear()
return render_template('logout.html')
@app.route('/passwd')
def password():
return render_template('login.html', error_string="Error: Change password not implemented")
def usage():
print ('\nUsage: saml_idp.py --debug '
'--port=<port> '
'--saml_issuer=<issuer> '
'--key_file=<private_key_file> '
'--cert_file=<certificate_file>\n')
if __name__ == '__main__':
try:
opts, args = getopt.getopt(sys.argv[1:], None,
["debug", "port=",
"saml_issuer=", "cert_file=",
"key_file="])
except getopt.GetoptError:
usage()
sys.exit(1)
for opt, arg in opts:
if opt == "--debug":
debug_flag = True
if opt == "--saml_issuer":
saml_issuer = arg
if opt == "--port":
port = int(arg)
if opt == "--key_file":
key_file = arg
if opt == "--cert_file":
cert_file = arg
if not key_file or not cert_file:
print('No private key specified to use for POST binding.')
usage()
sys.exit(1)
context = ('server.crt', 'server.key')
app.run(host='0.0.0.0', port=28080, debug=True,
threaded=True, ssl_context=context)