forked from italia/spid-testenv2
/
spid-testenv.py
1178 lines (1084 loc) · 42.6 KB
/
spid-testenv.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import argparse
import collections
import json
import logging
import lxml.etree as etree
import os
import os.path
import random
import string
from datetime import datetime
from hashlib import sha1, sha512
from logging.handlers import RotatingFileHandler
import saml2.xmldsig as ds
import yaml
from flask import Flask, Response, abort, escape, redirect, render_template_string, request, session, url_for, \
render_template
from passlib.hash import sha512_crypt
from saml2 import (BINDING_HTTP_POST, BINDING_HTTP_REDIRECT, BINDING_URI,
NAMESPACE)
from saml2.assertion import Assertion
from saml2.authn_context import AuthnBroker, authn_context_class_ref
from saml2.config import Config as Saml2Config
from saml2.metadata import create_metadata_string
from saml2.saml import NAME_FORMAT_BASIC, NAMEID_FORMAT_TRANSIENT, NAMEID_FORMAT_ENTITY
from saml2.server import Server
from saml2.sigver import verify_redirect_signature
from saml2.s_utils import OtherError
try:
FileNotFoundError
except NameError:
#py2
FileNotFoundError = IOError
try:
from saml2.sigver import get_xmlsec_binary
except ImportError:
get_xmlsec_binary = None
if get_xmlsec_binary:
xmlsec_path = get_xmlsec_binary(["/opt/local/bin"])
else:
xmlsec_path = '/usr/bin/xmlsec1'
SIGN_ALG = ds.SIG_RSA_SHA1
DIGEST_ALG = ds.DIGEST_SHA1
COMPARISONS = ['exact', 'minimum', 'better', 'maximum']
SPID_LEVELS = [
'https://www.spid.gov.it/SpidL1',
'https://www.spid.gov.it/SpidL2',
'https://www.spid.gov.it/SpidL3'
]
error_table = '''
<html>
<head>
</head>
<body>
<table border=1>
<thead>
<tr>
<th>Errore</th>
<th>Dettagli</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{msg}}</td>
<td>{{extra}}</td>
</tr>
</tbody>
</table>
</body>
</html>
'''
spid_error_table = '''
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="message">
{% for line in lines %}
<pre class="xml-line">{{line}}</pre>
{% endfor %}
</div>
<table class="spid-error" border=1>
<thead>
<tr>
<th>Elemento</th>
<th>Dettagli errore</th>
</tr>
</thead>
<tbody>
{% for err in errors %}
<tr>
<td class="spid-error__elem" id="{{err.1}}">{{err.1}}</td>
<td>
<ul>
{% for name, msgs in err.2.items() %}
<li>{{name}}
<ul>
{% for type, msg in msgs.items() %}
<li>{{msg|safe}}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function(){
$.each($('.spid-error__elem'), function(){
var id = $(this).attr('id');
var line = $('.xml-line:contains("<' + id + '")');
var tag = line[0];
$(tag).css('background-color', 'red');
});
});
</script>
</body>
</html>
'''
FORM_LOGIN = '''
<form name="login" method="post" action="{{action}}">
<input type="hidden" name="request_key" value="{{request_key}}" />
<input type="hidden" name="relay_state" value="{{relay_state}}" />
<span>Username</span> <input type="text" name="username" /><br>
<span>Password</span> <input type="password" name="password" /><br>
{{extra_challenge|safe}}
<input type="submit"/>
</form>
'''
FORM_ADD_USER = '''
<form name="add_user" method="post" action="{{action}}">
<b>Credentials</b><br>
<span>Username</span> <input type="text" name="username" /><br>
<span>Password</span> <input type="password" name="password" /><br>
<span>Service provider id</span> <input type="text" name="service_provider" /><br>
<br>
<b>Attributi primari</b>
<br>
{% for attribute in primary_attributes %}
<span>{{attribute}}</span> <input type="text" name="{{attribute}}" /><br>
{% endfor %}
<br>
<b>Attributi secondari</b>
<br>
{% for attribute in secondary_attributes %}
<span>{{attribute}} </span><input type="text" name="{{attribute}}" /><br>
{% endfor %}
<br>
<input type="submit"/>
</form>
'''
CONFIRM_PAGE = '''
<html>
<head>
</head>
<body>
<div id="message">
{% for line in lines %}
<pre class="xml-line">{{line}}</pre>
{% endfor %}
</div>
Vuoi trasmettere i seguenti attributi?
<table border=1>
<thead>
<tr>
<th>attributo</th>
</tr>
</thead>
<tbody>
{% for attr in attrs %}
<tr>
<td>{{attr}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<form name="make_response" method="post" action="{{action}}">
<input type="hidden" name="request_key" value="{{request_key}}" />
<input type="submit"/>
</form>
</body>
</html>
'''
def check_utc_date(date):
try:
datetime.strptime(date, '%Y-%m-%dT%H:%M:%SZ')
except ValueError:
return False
return True
check_utc_date.error_msg = 'la data non è in formato UTC'
def prettify_xml(msg):
msg = etree.tostring(etree.XML(msg), pretty_print=True, encoding='utf-8')
return msg.decode()
class Observer(object):
def __init__(self, *args, **kwargs):
self._pool = collections.OrderedDict()
def attach(self, obj):
self._pool[obj._name] = obj
for _child in obj._children:
self.attach(_child)
def evaluate(self):
_errors = []
for elem, obj in self._pool.items():
if obj._errors:
_errors.append([elem, obj._tag, obj._errors])
return _errors
class Attr(object):
"""
Define an attribute for a SAML2 element
"""
MANDATORY_ERROR = 'L\'attributo è obbligatorio'
NO_WANT_ERROR = 'L\'attributo non è richiesto'
DEFAULT_VALUE_ERROR = '{} è diverso dal valore di riferimento {}'
DEFAULT_LIST_VALUE_ERROR = '{} non corrisponde a nessuno dei valori contenuti in {}'
def __init__(self, name, absent=False, required=True, default=None, func=None, *args, **kwargs):
"""
:param name: attribute name
:param required: flag to indicate if the attribute is mandatory (True by default)
:param default: default value (or list of values, to be compared with the provided value to the 'validate' method)
:param func: optional additional function to perform a validation on value passed to 'validated' method
"""
self._name = name
self._absent = absent
self._required = required
self._errors = {}
self._default = default
self._func = func
def validate(self, value=None):
"""
:param value: attribute value
"""
if self._absent and value is not None:
self._errors['no_want_error'] = self.NO_WANT_ERROR
else:
if self._required and value is None:
self._errors['required_error'] = self.MANDATORY_ERROR
if self._default is not None:
if isinstance(self._default, list) and value not in self._default:
self._errors['value_error'] = self.DEFAULT_LIST_VALUE_ERROR.format(value, self._default)
elif isinstance(self._default, str) and self._default != value:
self._errors['value_error'] = self.DEFAULT_VALUE_ERROR.format(value, self._default)
if self._func is not None and value is not None:
if not self._func(value):
self._errors['validation_error'] = self._func.error_msg
return {
'value': value if not self._errors else None,
'errors': self._errors
}
@property
def real_name(self):
if self._name == 'id':
return 'ID'
else:
parsed_elements = []
for el in self._name.split('_'):
_new_element = el[0].upper() + el[1:]
parsed_elements.append(_new_element)
return ''.join(parsed_elements)
class Elem(object):
"""
Define a SAML2 element
"""
MANDATORY_ERROR = 'L\'elemento è obbligatorio'
NO_WANT_ERROR = 'L\'elemento non è richiesto'
def __init__(self, name, tag, absent=False, required=True, attributes=[], children=[], example='', *args, **kwargs):
"""
:param name: element name
:param tag: element 'namespace:tag_name'
:param required: flag to indicate if the element is mandatory (True by default)
:param attributes: list of Attr objects (element attributes)
:param children: list of Elem objects (nested elements)
:param example: string to explain how the missing element need to be implemented
"""
self._name = name
self._required = required
self._absent = absent
self._attributes = attributes
self._children = children
self._errors = {}
self._tag = tag
self._example = example
def validate(self, data):
"""
:param data: (nested) object returned by pysaml2
"""
res = { 'attrs': {}, 'children': {}, 'errors': {} }
if self._absent and data is not None:
res['errors']['no_want_error'] = self.NO_WANT_ERROR
self._errors.update(res['errors'])
else:
if self._required and data is None:
# check if the element is required, if not provide and example
_error_msg = self.MANDATORY_ERROR
_example = '<br>Esempio:<br>'
lines = self._example.splitlines()
for line in lines:
_example = '{}<pre>{}</pre>'.format(_example, escape(line))
_error_msg = '{} {}'.format(_error_msg, _example)
res['errors']['required_error'] = _error_msg
self._errors.update(res['errors'])
if data:
if isinstance(data, list):
# TODO: handle list elements in a clean way
data = data[0]
for attribute in self._attributes:
_validated_attributes = attribute.validate(getattr(data, attribute._name))
res['attrs'][attribute.real_name] = _validated_attributes
if _validated_attributes['errors']:
self._errors.update({attribute.real_name: _validated_attributes['errors']})
for child in self._children:
res['children'][child._name] = child.validate(getattr(data, child._name))
return res
class SpidParser(object):
"""
Parser for spid messages
"""
def __init__(self, *args, **kwargs):
self.schema = None
def get_schema(self, action, binding):
"""
:param binding:
"""
_schema = None
if action == 'login':
required_signature = False
if binding == BINDING_HTTP_POST:
required_signature = True
elif binding == BINDING_HTTP_REDIRECT:
required_signature = False
_schema = Elem(
name='auth_request',
tag='samlp:AuthnRequest',
attributes=[
Attr('id'),
Attr('version', default='2.0'),
Attr('issue_instant', func=check_utc_date),
Attr('destination'),
Attr('force_authn', required=False),
Attr('attribute_consuming_service_index', required=False),
Attr('assertion_consumer_service_url', required=False),
Attr('protocol_binding', default=BINDING_HTTP_POST, required=False)
],
children=[
Elem(
'subject',
tag='saml:Subject',
required=False,
attributes=[
Attr('format', default=NAMEID_FORMAT_ENTITY),
Attr('name_qualifier')
]
),
Elem(
'issuer',
tag='saml:Issuer',
example='''
<saml:Issuer
NameQualifier="http://spid.serviceprovider.it"
Format="{}">
spid-sp
</saml:Issuer>
'''.format(NAMEID_FORMAT_ENTITY),
attributes=[
Attr('format', default=NAMEID_FORMAT_ENTITY),
Attr('name_qualifier')
],
),
Elem(
'name_id_policy',
tag='samlp:NameIDPolicy',
attributes=[
Attr('allow_create', absent=True, required=False),
Attr('format', default=NAMEID_FORMAT_TRANSIENT)
]
),
Elem(
'conditions',
tag='saml:Conditions',
required=False,
attributes=[
Attr('not_before', func=check_utc_date),
Attr('not_on_or_after', func=check_utc_date)
]
),
Elem(
'requested_authn_context',
tag='saml:AuthnContext',
attributes=[
Attr('comparison', default=COMPARISONS),
],
children=[
Elem(
'authn_context_class_ref',
tag='saml:AuthnContextClassRef',
attributes=[
Attr('text', default=SPID_LEVELS)
]
)
]
),
Elem(
'signature',
tag='ds:Signature',
required=required_signature,
),
Elem(
'scoping',
tag='saml2p:Scoping',
required=False,
attributes=[
Attr('proxy_count', default=[0])
]
),
]
)
elif action == 'logout':
_schema = Elem(
name='logout_request',
tag='samlp:LogoutRequest',
attributes=[
Attr('id'),
Attr('version', default='2.0'),
Attr('issue_instant', func=check_utc_date),
Attr('destination'),
],
children=[
Elem(
'issuer',
tag='saml:Issuer',
example='''
<saml:Issuer
NameQualifier="http://spid.serviceprovider.it"
Format="{}">
spid-sp
</saml:Issuer>
'''.format(NAMEID_FORMAT_ENTITY),
attributes=[
Attr('format', default=NAMEID_FORMAT_ENTITY),
Attr('name_qualifier')
],
),
Elem(
'name_id',
tag='saml:NameID',
attributes=[
Attr('name_qualifier'),
Attr('format', default=NAMEID_FORMAT_TRANSIENT)
]
),
Elem(
'session_index',
tag='samlp:SessionIndex',
),
]
)
return _schema
def parse(self, obj, action, binding, schema=None):
"""
:param obj: pysaml2 object
:param binding:
:param schema: custom schema (None by default)
"""
_schema = self.get_schema(action, binding) if schema is None else schema
self.observer = Observer()
self.observer.attach(_schema)
validated = _schema.validate(obj)
errors = self.observer.evaluate()
return validated, errors
class BadConfiguration(Exception):
pass
class AbstractUserManager(object):
"""
Base User manager class to handling user objects
"""
def get(self, uid, pwd, sp_id):
raise NotImplementedError
def add(self, uid, pwd, sp_id, extra={}):
raise NotImplementedError
class JsonUserManager(AbstractUserManager):
"""
User manager class to handling json user objects
"""
FILE_NAME = 'users.json'
def _load(self):
try:
with open(self.FILE_NAME, 'r') as fp:
self.users = json.loads(fp.read())
except FileNotFoundError:
self.users = {}
self._save()
def _save(self):
with open(self.FILE_NAME, 'w') as fp:
json.dump(self.users, fp, indent=4)
def __init__(self, *args, **kwargs):
self._load()
def get(self, uid, pwd, sp_id):
for user, _attrs in self.users.items():
if pwd == _attrs['pwd'] and _attrs['sp'] == sp_id:
return user, self.users[user]
return None, None
def add(self, uid, pwd, sp_id, extra={}):
if uid not in self.users:
self.users[uid] = {
'pwd': pwd,
'sp': sp_id,
'attrs': extra
}
self._save()
class IdpServer(object):
ticket = {}
responses = {}
challenges = {}
_binding_mapping = {
'http-redirect': BINDING_HTTP_REDIRECT,
'http-post': BINDING_HTTP_POST
}
_endpoint_types = ['single_sign_on_service', 'single_logout_service']
_spid_levels = SPID_LEVELS
_spid_attributes = {
'primary': {
'spidCode' : 'xs:string',
'name': 'xs:string',
'familyName': 'xs:string',
'placeOfBirth': 'xs:string',
'countryOfBirth': 'xs:string',
'dateOfBirth': 'xs:date',
'gender': 'xs:string',
'companyName': 'xs:string',
'registeredOffice': 'xs:string',
'fiscalNumber': 'xs:string',
'ivaCode': 'xs:string',
'idCard': 'xs:string',
},
'secondary': {
'mobilePhone': 'xs:string',
'email': 'xs:string',
'address': 'xs:string',
'expirationDate': 'xs:date',
'digitalAddress': 'xs:string' # PEC
}
}
CHALLENGES_TIMEOUT = 30 # seconds
SAML_VERSION = '2.0'
def __init__(self, app, config, *args, **kwargs):
"""
:param app: Flask instance
:param config: dictionary containing the configuration
:param args:
:param kwargs:
"""
# bind Flask app
self.app = app
self.user_manager = JsonUserManager()
# setup
self._config = config
self.app.secret_key = 'sosecret'
handler = RotatingFileHandler('spid.log', maxBytes=500000, backupCount=1)
self.app.logger.addHandler(handler)
self._prepare_server()
self.spid_parser = SpidParser()
@property
def _mode(self):
return 'https' if self._config.get('https', False) else 'http'
def _idp_config(self):
"""
Process pysaml2 configuration
"""
key_file_path = self._config.get('key_file')
cert_file_path = self._config.get('cert_file')
metadata = self._config.get('metadata')
metadata = metadata if metadata else []
if metadata:
for typ in ['local', 'remote']:
if metadata.get(typ) is None:
metadata[typ] = []
existing_key = os.path.isfile(key_file_path) if key_file_path else None
existing_cert = os.path.isfile(cert_file_path) if cert_file_path else None
if not existing_key:
raise BadConfiguration('Chiave privata dell\'IdP di test non trovata: {} non trovato'.format(key_file_path))
if not existing_cert:
raise BadConfiguration('Certificato dell\'IdP di test non trovato: {} non trovato'.format(cert_file_path))
self.entity_id = self._config.get('hostname')
if not self.entity_id:
self.entity_id = self._config.get('host')
self.entity_id = '{}://{}'.format(self._mode, self.entity_id)
port = self._config.get('port')
if port:
self.entity_id = '{}:{}'.format(self.entity_id, port)
idp_conf = {
"entityid": self.entity_id,
"description": "Spid Test IdP",
"service": {
"idp": {
"name": "Spid Testenv",
"endpoints": {
"single_sign_on_service": [
],
"single_logout_service": [
],
},
"policy": {
"default": {
"name_form": NAME_FORMAT_BASIC,
},
},
"name_id_format": [
NAMEID_FORMAT_TRANSIENT,
]
},
},
"debug": 1,
"key_file": self._config.get('key_file'),
"cert_file": self._config.get('cert_file'),
"metadata": metadata,
"logger": {
"rotating": {
"filename": "idp.log",
"maxBytes": 500000,
"backupCount": 1,
},
"loglevel": "debug",
}
}
# setup services url
for _service_type in self._endpoint_types:
endpoint = self._config['endpoints'][_service_type]
idp_conf['service']['idp']['endpoints'][_service_type].append(
('{}{}'.format(self.entity_id, endpoint), BINDING_HTTP_REDIRECT)
)
idp_conf['service']['idp']['endpoints'][_service_type].append(
('{}{}'.format(self.entity_id, endpoint), BINDING_HTTP_POST)
)
return idp_conf
def _setup_app_routes(self):
"""
Setup Flask routes
"""
# Setup SSO and SLO endpoints
endpoints = self._config.get('endpoints')
if endpoints:
for ep_type in self._endpoint_types:
_url = endpoints.get(ep_type)
if _url:
if not _url.startswith('/'):
raise BadConfiguration('Errore nella configurazione delle url, i path devono essere relativi ed iniziare con "/" (slash) - url {}'.format(_url)
)
for _binding in self._binding_mapping.keys():
self.app.add_url_rule(_url, '{}_{}'.format(ep_type, _binding), getattr(self, ep_type), methods=['GET',])
self.app.add_url_rule('/', 'index', self.index, methods=['GET'])
self.app.add_url_rule('/login', 'login', self.login, methods=['POST', 'GET',])
# Endpoint for user add action
self.app.add_url_rule('/add-user', 'add_user', self.add_user, methods=['GET', 'POST',])
self.app.add_url_rule('/continue-response', 'continue_response', self.continue_response, methods=['POST',])
self.app.add_url_rule('/metadata', 'metadata', self.metadata, methods=['POST', 'GET'])
def _prepare_server(self):
"""
Setup server
"""
self.idp_config = Saml2Config()
self.BASE = '{}://{}:{}'.format(self._mode, self._config.get('host'), self._config.get('port'))
if 'entityid' not in self._config:
# as fallback for entityid use host:port string
self._config['entityid'] = self.BASE
self.idp_config.load(cnf=self._idp_config())
self.server = Server(config=self.idp_config)
self._setup_app_routes()
# setup custom methods in order to
# prepare the login form and verify the challenge (optional)
# for every spid level (1-2-3)
self.authn_broker = AuthnBroker()
for index, _level in enumerate(self._spid_levels):
self.authn_broker.add(
authn_context_class_ref(_level),
getattr(self, '_verify_spid_{}'.format(index + 1))
)
def _verify_spid_1(self, verify=False, **kwargs):
self.app.logger.debug('spid level 1 - verifica ({})'.format(verify))
return self._verify_spid(1, verify, **kwargs)
def _verify_spid_2(self, verify=False, **kwargs):
self.app.logger.debug('spid level 2 - verifica ({})'.format(verify))
return self._verify_spid(2, verify, **kwargs)
def _verify_spid_3(self, verify=False, **kwargs):
self.app.logger.debug('spid level 3 - verifica ({})'.format(verify))
return self._verify_spid(3, verify, **kwargs)
def _verify_spid(self, level=1, verify=False, **kwargs):
"""
:param level: integer, SPID level
:param verify: boolean, if True verify spid extra challenge (otp etc.), if False prepare the challenge
:param kwargs: dictionary, extra arguments
"""
if verify:
# Verify the challenge
if level == 2:
# spid level 2
otp = kwargs.get('data').get('otp')
key = kwargs.get('key')
if key and key not in self.challenges or not otp:
return False
total_seconds = (datetime.now() - self.challenges[key][1]).total_seconds()
# Check that opt value is equal and not expired
if self.challenges[key][0] != otp or total_seconds > self.CHALLENGES_TIMEOUT:
del self.challenges[key]
return False
return True
else:
# Prepare the challenge
if level == 2:
# spid level 2
# very simple otp implementation, while opt is a random 6 digits string
# with a lifetime setup in the server instance
key = kwargs.get('key')
otp = ''.join(random.choice(string.digits) for _ in range(6))
self.challenges[key] = [otp, datetime.now()]
extra_challenge = '<span>Otp ({})</span><input type="text" name="otp" />'.format(otp)
else:
extra_challenge = ''
return extra_challenge
def unpack_args(self, elems):
"""
Unpack arguments from request
"""
return dict([(k, v) for k, v in elems.items()])
def _raise_error(self, msg, extra=None):
"""
Raise some error using 'abort' function from Flask
:param msg: string for error type
:param extra: optional string for error details
"""
abort(
Response(
render_template(
"error.html",
**{'msg': msg, 'extra': extra or ""}
),
200
)
)
def _check_spid_restrictions(self, msg, action, binding):
parsed_msg, errors = self.spid_parser.parse(msg.message, action, binding)
self.app.logger.debug('parsed authn_request: {}'.format(parsed_msg))
return parsed_msg, errors
def _store_request(self, authnreq):
"""
Store authnrequest in a dictionary
:param authnreq: authentication request string
"""
self.app.logger.debug('store_request: {}'.format(authnreq))
key = sha1(authnreq.xmlstr).hexdigest()
# store the AuthnRequest
self.ticket[key] = authnreq
return key
def _handle_errors(self, errors, xmlstr):
_escaped_xml = escape(prettify_xml(xmlstr.decode()))
rendered_error_response = render_template_string(
spid_error_table,
**{
'lines': _escaped_xml.splitlines(),
'errors': errors
}
)
return rendered_error_response
def single_sign_on_service(self):
"""
Process Http-Redirect or Http-POST request
:param request: Flask request object
"""
self.app.logger.info("Http-Redirect")
# Unpack parameters
saml_msg = self.unpack_args(request.args)
try:
_key = session['request_key']
req_info = self.ticket[_key]
except KeyError as e:
try:
binding = self._get_binding('single_sign_on_service', request)
# Parse AuthnRequest
req_info = self.server.parse_authn_request(
saml_msg["SAMLRequest"],
binding
)
authn_req = req_info.message
_, errors = self._check_spid_restrictions(req_info, 'login', binding)
except KeyError as err:
self.app.logger.debug(str(err))
self._raise_error('Parametro SAMLRequest assente.')
except OtherError as err:
self.app.logger.debug(str(err))
self._raise_error('Destinazione messaggio errata.')
if errors:
return self._handle_errors(errors, req_info.xmlstr)
if not req_info:
self._raise_error('Processo di parsing del messaggio fallito.')
self.app.logger.debug('AuthnRequest: {}'.format(authn_req))
# Check if it is signed
if "SigAlg" in saml_msg and "Signature" in saml_msg:
# Signed request
self.app.logger.debug('Messaggio SAML firmato.')
issuer_name = authn_req.issuer.text
try:
_certs = self.server.metadata.certs(
issuer_name,
"any",
"signing"
)
except KeyError:
self._raise_error('entity ID {} non registrato, impossibile ricavare un certificato valido.'.format(issuer_name))
verified_ok = False
for cert in _certs:
self.app.logger.debug(
'security backend: {}'.format(self.server.sec.sec_backend.__class__.__name__)
)
# Check signature
if verify_redirect_signature(saml_msg, self.server.sec.sec_backend,
cert):
verified_ok = True
break
if not verified_ok:
self._raise_error('Verifica della firma del messaggio fallita.')
else:
self._raise_error('Messaggio SAML non firmato.')
# Perform login
key = self._store_request(req_info)
relay_state = saml_msg.get('RelayState', '')
session['request_key'] = key
session['relay_state'] = relay_state
return redirect(url_for('login'))
def _get_binding(self, endpoint_type, request):
try:
endpoint = request.endpoint
binding = endpoint.split('{}_'.format(endpoint_type))[1]
return self._binding_mapping.get(binding)
except IndexError:
pass
@property
def _spid_main_fields(self):
"""
Returns a list of spid main attributes
"""
return self._spid_attributes['primary'].keys()
@property
def _spid_secondary_fields(self):
"""
Returns a list of spid secondary attributes
"""
return self._spid_attributes['secondary'].keys()
def add_user(self):
"""
Add user endpoint
"""
spid_main_fields = self._spid_main_fields
spid_secondary_fields = self._spid_secondary_fields
rendered_form = render_template(
"add_user.html",
**{
'action': '/add-user',
'primary_attributes': spid_main_fields,
'secondary_attributes': spid_secondary_fields
}
)
if request.method == 'GET':
return rendered_form, 200
elif request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
sp = request.form.get('service_provider')
if not username or not password or not sp:
abort(400)
extra = {}
for spid_field in spid_main_fields:
spid_value = request.form.get(spid_field)
if spid_value:
extra[spid_field] = spid_value
for spid_field in spid_secondary_fields:
spid_value = request.form.get(spid_field)
if spid_value:
extra[spid_field] = spid_value
self.user_manager.add(username, password, sp, extra)
return 'Added a new user', 200
def index(self):
rendered_form = render_template(
"home.html",
**{
'sp_list': [{"name": sp, "spId": sp} for sp in self.server.metadata.service_providers()],
}
)
return rendered_form, 200
def login(self):
"""
Login endpoint (verify user credentials)
"""
key = session['request_key'] if 'request_key' in session else None
relay_state = session['relay_state'] if 'relay_state' in session else ''
self.app.logger.debug('Request key: {}'.format(key))
if key and key in self.ticket:
authn_request = self.ticket[key]
sp_id = authn_request.message.issuer.text
destination = None
if authn_request.message.attribute_consuming_service_index is not None:
acss = self.server.metadata.assertion_consumer_service(sp_id, authn_request.message.protocol_binding)
for acs in acss:
if acs.get('index') == authn_request.message.attribute_consuming_service_index:
destination = acs.get('location')
break
self.app.logger.debug('AssertionConsumingServiceIndex Location: {}'.format(destination))
if destination is None:
destination = authn_request.message.assertion_consumer_service_url
self.app.logger.debug('AssertionConsumerServiceUrl: {}'.format(destination))
if destination is None:
self._raise_error(
'Impossibile ricavare l\'url di risposta',
'Verificare la presenza e la correttezza dell\'AssertionConsumerServiceIndex, o in alternativa della coppia di attributi AssertionConsumerServiceURL e ProtocolBinding'
)