-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgrid_openid.py
More file actions
executable file
·1792 lines (1591 loc) · 71.4 KB
/
grid_openid.py
File metadata and controls
executable file
·1792 lines (1591 loc) · 71.4 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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# --- BEGIN_HEADER ---
#
# grid_openid - openid server authenticating users against user database
# Copyright (C) 2003-2026 The MiG Project by the Science HPC Center at UCPH
#
# This file is part of MiG.
#
# MiG 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.
#
# MiG 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
#
# -- END_HEADER ---
#
#
# This code is a heavily modified version of the server example from the
# python-openid package
# https://pypi.python.org/pypi/python-openid/
#
# = Original copyright notice follows =
# Python OpenID - OpenID consumer and server library
# Copyright (C) 2005-2008 Janrain, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions
# and limitations under the License.
# = End of original copyright notice =
"""OpenID server to let users authenticate with username and password from
our local user DB.
Requires OpenID module (https://github.com/openid/python-openid).
"""
from __future__ import print_function
from __future__ import absolute_import
# NOTE: we use additional try/except wrapping here to prevent autopep8 mess up
try:
from future import standard_library
standard_library.install_aliases()
from past.builtins import basestring
import http.cookies
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
except Exception as exc:
print("ERROR: failed to init py 2/3 compatibility")
exit(1)
import base64
import cgitb
import os
import re
import socket
import sys
import time
import types
try:
import openid
except ImportError:
print("ERROR: the python openid module is required for this daemon")
sys.exit(1)
try:
from openid.consumer import discover
from openid.extensions import sreg
from openid.server import server
from openid.store.filestore import FileOpenIDStore
except ImportError:
print("ERROR: one or more python openid modules missing")
sys.exit(1)
try:
from mig.shared.accountstate import check_account_accessible
from mig.shared.base import client_id_dir, cert_field_map, force_utf8, \
force_native_str
from mig.shared.conf import get_configuration_object
from mig.shared.griddaemons.openid import default_max_user_hits, \
default_user_abuse_hits, default_proto_abuse_hits, \
default_username_validator, refresh_user_creds, update_login_map, \
login_map_lookup, hit_rate_limit, expire_rate_limit, \
validate_auth_attempt
from mig.shared.htmlgen import openid_page_template
from mig.shared.logger import daemon_logger, register_hangup_handler
from mig.shared.pwcrypto import make_simple_hash
from mig.shared.safeinput import valid_distinguished_name, valid_password, \
valid_path, valid_ascii, valid_job_id, valid_base_url, valid_url, \
valid_complex_url, html_escape, InputException
from mig.shared.tlsserver import hardened_ssl_context
from mig.shared.url import urlparse, urlencode, check_local_site_url, \
parse_qsl
from mig.shared.useradm import get_openid_user_dn, check_password_scramble, \
check_hash
from mig.shared.userdb import default_db_path
from mig.shared.validstring import possible_user_id
except Exception as exc:
print("ERROR: migrid modules could not be loaded: %s" % exc)
sys.exit(1)
configuration, logger = None, None
# Update with extra fields
cert_field_map.update({'role': 'ROLE', 'timezone': 'TZ', 'nickname': 'NICK',
'fullname': 'CN', 'o': 'O', 'ou': 'OU'})
cert_field_names = list(cert_field_map)
cert_field_values = list(cert_field_map.values())
cert_field_aliases = {}
# NOTE: response may contain password on the form
# (<Symbol Bare namespace>, 'password'): 'S3cr3tP4ssw0rd'
pw_pattern = "\(<Symbol Bare namespace>, 'password'\): '(.+)'"
pw_regexp = re.compile(pw_pattern)
def quoteattr(val):
"""Escape string for safe printing"""
esc = html_escape(val, 1)
return '"%s"' % (esc,)
def valid_mode_name(arg):
"""Make sure only valid mode names are allowed"""
valid_job_id(arg)
def valid_cert_dir(arg):
"""Make sure only valid cert dir names are allowed"""
valid_distinguished_name(arg, extra_chars='+_')
def valid_cert_fields(arg):
"""Make sure only valid cert field names are allowed"""
valid_job_id(arg, extra_chars=',')
if [i for i in arg.split(',') if not i in cert_field_names]:
invalid_argument(arg)
def valid_identity_url(arg):
"""Make sure only valid url followed by cert dir names are allowed"""
valid_distinguished_name(arg, extra_chars=':+_')
def valid_session_hash(arg):
"""Make sure only valid session hashes are allowed"""
valid_password(arg, extra_chars='=', max_length=512)
def invalid_argument(arg):
"""Always raise exception to mark argument invalid"""
raise ValueError("Unexpected query variable: %s" % quoteattr(arg))
def strip_password(configuration, obj):
"""Always filter out password entries from obj, which might be a string or
a query dictionary.
"""
_logger = configuration.logger
if isinstance(obj, basestring):
pw_match = pw_regexp.search(obj)
if pw_match:
msg_pw = pw_match.group(1)
filtered = obj.replace(msg_pw, '*' * len(msg_pw))
_logger.debug("filtered string for password: %s" % filtered)
else:
filtered = obj
elif isinstance(obj, dict):
filtered = obj.copy()
if 'password' in obj:
filtered['password'] = '*' * len(obj['password'])
_logger.debug("filtered dict for password: %s" % filtered)
else:
_logger.error(
"not filtering unexpected obj in strip_password: %s" % obj)
return obj
return filtered
def filter_why_pw(configuration, why):
"""Helper to wrap strip_password around exceptions"""
_logger = configuration.logger
if isinstance(why, server.EncodingError):
text = why.response.encodeToKVForm()
return strip_password(configuration, text)
elif isinstance(why, server.ProtocolError):
text = why.message
return strip_password(configuration, text)
else:
# IMPORTANT: do NOT log or show raw why as it may contain credentials
# NOTE: we should not get here, but return generic safe msg if we do.
why_type = type(why)
_logger.warning("can't filter unknown 'why' (%s) - show generic err" %
why_type)
return 'Unexpected %s to filter for safe log and output.' % why_type
def lookup_full_user(username):
"""Look up the full user identity for username consisting of e.g. just an
email address.
The method to extract the full identity depends on the back end database.
If username matches either the openid link, the full ID or the dir version
from it, a tuple with the expanded username and the full user dictionary
is returned.
On no match a tuple with the unchanged username and an empty dictionary
is returned.
"""
# print "DEBUG: lookup full user for %s" % username
login_url = os.path.join(configuration.user_mig_oid_provider, username)
distinguished_name = get_openid_user_dn(configuration, login_url)
# print "DEBUG: compare against %s" % full_id
entries = login_map_lookup(configuration.daemon_conf, username)
for entry in entries:
if entry and entry.user_dict:
url_friendly = client_id_dir(distinguished_name)
return (url_friendly, entry.user_dict)
return (username, {})
def lookup_full_identity(username):
"""Look up the full identity for username consisting of e.g. just an email
address.
The method to extract the full identity depends on the back end database
and the format of the ID can be overriden here as well.
If username matches either the full ID or the configured alias field from
it, the full ID is returned on a URL-friendly form. On no match the
original username is returned in unchanged form.
"""
# print "DEBUG: lookup full ID for %s" % username
return lookup_full_user(username)[0]
class OpenIDHTTPServer(HTTPServer):
"""
http(s) server that contains a reference to an OpenID Server and
knows its base URL.
Extended to fork on requests to avoid one slow or broken login stalling
the rest.
"""
min_expire_delay = 120
last_expire = time.time()
# NOTE: We do not enable hash and scramble cache here since it is hardly
# any gain and it potentially introduces a race
hash_cache, scramble_cache = None, None
def __init__(self, *args, **kwargs):
HTTPServer.__init__(self, *args, **kwargs)
fqdn = self.server_name
port = self.server_port
# Masquerading if needed
if configuration.daemon_conf['show_address']:
fqdn = configuration.daemon_conf['show_address']
if configuration.daemon_conf['show_port']:
port = configuration.daemon_conf['show_port']
if configuration.daemon_conf['nossl']:
proto = 'http'
proto_port = 80
else:
proto = 'https'
proto_port = 443
if port != proto_port:
self.base_url = '%s://%s:%s/' % (proto, fqdn, port)
else:
self.base_url = '%s://%s/' % (proto, fqdn)
# We serve from sub dir to ease targeted proxying
self.server_base = 'openid'
self.base_url += "%s/" % self.server_base
self.openid = None
self.approved = {}
self.lastCheckIDRequest = {}
# Add our own SReg fields to list of valid fields from sreg 1.1 spec
for (key, val) in cert_field_map.items():
if not key in sreg.data_fields:
sreg.data_fields[key] = key.replace('_', ' ').title()
# print "DEBUG: sreg fields: %s" % sreg.data_fields
for name in cert_field_names:
cert_field_aliases[name] = []
for target in [i for i in cert_field_names if name != i]:
if cert_field_map[name] == cert_field_map[target]:
cert_field_aliases[name].append(target)
# print "DEBUG: cert field aliases: %s" % cert_field_aliases
def expire_volatile(self):
"""Expire old entries in the volatile helper dictionaries"""
if self.last_expire + self.min_expire_delay < time.time():
self.last_expire = time.time()
expire_rate_limit(configuration, "openid",
expire_delay=self.min_expire_delay)
if self.hash_cache:
self.hash_cache.clear()
if self.scramble_cache:
self.scramble_cache.clear()
logger.debug("Expired old rate limits and scramble cache")
def setOpenIDServer(self, oidserver):
"""Override openid attribute"""
self.openid = oidserver
class ThreadedOpenIDHTTPServer(ThreadingMixIn, OpenIDHTTPServer):
"""Multi-threaded version of the OpenIDHTTPServer"""
pass
class ServerHandler(BaseHTTPRequestHandler):
"""Override BaseHTTPRequestHandler to handle OpenID protocol"""
# Input validation helper which must hold validators for all valid query
# string variables. Any other variables must trigger a client error.
validators = {
'username': valid_cert_dir,
'login_as': valid_cert_dir,
'identifier': valid_cert_dir,
'user': valid_cert_dir,
'password': valid_password,
'yes': valid_ascii,
'no': valid_ascii,
'err': valid_ascii,
'remember': valid_ascii,
'cancel': valid_ascii,
'submit': valid_distinguished_name,
'logout': valid_ascii,
'success_to': valid_url,
'fail_to': valid_url,
'return_to': valid_complex_url,
'openid.assoc_handle': valid_password,
'openid.assoc_type': valid_password,
'openid.dh_consumer_public': valid_session_hash,
'openid.dh_gen': valid_password,
'openid.dh_modulus': valid_session_hash,
'openid.session_type': valid_mode_name,
'openid.claimed_id': valid_identity_url,
'openid.identity': valid_identity_url,
'openid.mode': valid_mode_name,
'openid.ns': valid_base_url,
'openid.realm': valid_base_url,
'openid.success_to': valid_url,
'openid.return_to': valid_complex_url,
'openid.trust_root': valid_base_url,
'openid.ns.sreg': valid_base_url,
'openid.sreg.required': valid_cert_fields,
'openid.sreg.optional': valid_ascii,
'openid.sreg.policy_url': valid_base_url,
}
def __init__(self, *args, **kwargs):
if configuration.daemon_conf['session_ttl'] > 0:
self.session_ttl = configuration.daemon_conf['session_ttl']
else:
self.session_ttl = 48 * 3600
self.clearUser()
# NOTE: drop idle clients after N seconds to clean stale connections.
# Does NOT include clients that connect and do nothing at all :-(
self.timeout = 120
self.retry_url = ''
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
def __retry_url_from_cookie(self):
"""Extract retry_url from cookie and validate"""
retry_url = None
try:
cookies = self.headers.get('Cookie')
cookie = http.cookies.SimpleCookie(cookies)
cookie_dict = dict((k, v.value) for k, v in cookie.items())
retry_url_enc = cookie_dict.get('retry_url_enc', '')
logger.debug("found retry_url_enc: %s" % retry_url_enc)
if retry_url_enc:
# NOTE: b64decode takes str and returns bytes
retry_url = force_native_str(base64.b64decode(retry_url_enc))
else:
retry_url = ''
logger.debug("decoded retry_url: %s" % retry_url)
if retry_url and retry_url.startswith("http"):
raise InputException("invalid retry_url: %s" % retry_url)
elif retry_url:
valid_url(retry_url)
except http.cookies.CookieError as err:
retry_url = None
logger.error("found invalid cookie: %s" % err)
except InputException as exc:
retry_url = None
logger.error("found invalid cookie content: %s" % exc)
return retry_url
def __format_retry_url_for_cookie(self):
"""Format retry_url to fit in cookie"""
if self.retry_url is None:
retry_url = ''
else:
retry_url = self.retry_url
logger.debug("encoding retry_url: %s" % retry_url)
try:
valid_url(retry_url)
except InputException as exc:
retry_url = ''
logger.error("found invalid retry_url: %s" % exc)
# NOTE: b64encode takes bytes and returns bytes
enc = force_native_str(base64.b64encode(force_utf8(retry_url)))
logger.debug("encoded retry_url: %s" % enc)
return 'retry_url_enc=%s;secure;httponly' % enc
def clearUser(self):
"""Reset all saved user variables"""
self.user = None
self.user_dn = None
self.user_dn_dir = None
self.password = None
self.login_expire = None
def do_GET(self):
"""Handle all HTTP GET requests"""
# Make sure key is always available for exception handler
key = 'UNSET'
try:
# NOTE: force native string even if socketserver provides bytes
self.parsed_uri = urlparse(force_native_str(self.path))
self.query = {}
for (key, val) in parse_qsl(self.parsed_uri[4]):
# print("DEBUG: checking input arg %s: '%s'" % (key, val))
validate_helper = self.validators.get(key, invalid_argument)
# Let validation errors pass to general exception handler below
validate_helper(val)
self.query[key] = val
self.setUser()
# print "DEBUG: checking path '%s'" % self.parsed_uri[2]
valid_path(self.parsed_uri[2])
# Resolve retry url, strip password and err
retry_query = {key: val for (key, val) in self.query.items()
if not key in ['password', 'err']}
self.retry_url = "%s?%s" \
% (self.parsed_uri[2], urlencode(retry_query))
path = self.parsed_uri[2]
# Strip server_base before testing location
path = path.replace("%s/" % self.server.server_base, '', 1)
if path == '/':
self.showMainPage()
elif path.startswith('/ping'):
self.showPingPage()
elif path == '/openidserver':
self.serverEndPoint(self.query)
elif path == '/login':
self.showLoginPage('/%s/' % self.server.server_base,
'/%s/' % self.server.server_base,
query=self.query)
elif path == '/loginsubmit':
self.doLogin()
elif path == '/logout':
self.doLogout()
elif path.startswith('/id/'):
self.showIdPage(path)
elif path.startswith('/yadis/'):
self.showYadis(path[7:])
elif path == '/serveryadis':
self.showServerYadis()
else:
self.send_response(404)
self.end_headers()
except (KeyboardInterrupt, SystemExit):
raise
except InputException as err:
logger.error("Invalid %r input: %s" % (key, err))
logger.debug("*** Begin Trace ***\n%s\n*** End trace ***" %
cgitb.text(sys.exc_info(), context=10))
err_msg = """<p class='leftpad'>
Invalid '%s' input: %s
</p>
<p>
<a href='javascript:history.back(-1);'>Back</a>
</p>""" % (key, err)
self.showErrorPage(err_msg)
except Exception as exc:
error_ref = time.time()
logger.error("do_GET with ref %d crashed: %s" % (error_ref, exc))
# Do not disclose internal details
filtered_exc = cgitb.text(sys.exc_info(), context=10)
# IMPORTANT: do NOT ever print or log raw password
pw = self.password or ''
filtered_exc = filtered_exc.replace(pw, '*' * len(pw))
logger.debug("Traceback %s: %s" % (error_ref, filtered_exc))
err_msg = """<p class='leftpad'>
Internal error while handling your request - please contact the site support
%s if this persistently happens and include the error reference %d.
</p>
<p>
<a href='javascript:history.back(-1);'>Back</a>
</p>""" % (configuration.support_email, error_ref)
self.showErrorPage(err_msg, error_code=500)
def do_POST(self):
"""Handle all HTTP POST requests"""
try:
# NOTE: force native string even if socketserver provides bytes
self.parsed_uri = urlparse(force_native_str(self.path))
content_length = int(self.headers['Content-Length'])
# NOTE: force native string even if socketserver provides bytes
post_data = force_native_str(self.rfile.read(content_length))
self.query = {}
for (key, val) in parse_qsl(post_data):
# print "DEBUG: checking post input arg %s: '%s'" % (key, val)
validate_helper = self.validators.get(key, invalid_argument)
# Let validation errors pass to general exception handler below
validate_helper(val)
self.query[key] = val
self.setUser()
# print "DEBUG: checking path '%s'" % self.parsed_uri[2]
valid_path(self.parsed_uri[2])
path = self.parsed_uri[2]
# Strip server_base before testing location
path = path.replace("%s/" % self.server.server_base, '', 1)
if path == '/openidserver':
self.serverEndPoint(self.query)
elif path == '/allow':
self.handleAllow(self.query)
elif path == '/loginsubmit':
self.doLogin()
elif path == '/logout':
self.doLogout()
else:
self.send_response(404)
self.end_headers()
except (KeyboardInterrupt, SystemExit):
raise
except InputException as err:
logger.error("Invalid %r input: %s" % (key, err))
logger.debug("*** Begin Trace ***\n%s\n*** End trace ***" %
cgitb.text(sys.exc_info(), context=10))
err_msg = """<p class='leftpad'>
Invalid '%s' input: %s
</p>
<p>
<a href='javascript:history.back(-1);'>Back</a>
</p>""" % (key, err)
self.showErrorPage(err_msg)
except Exception as exc:
error_ref = time.time()
logger.error("do_POST with ref %d crashed: %s" % (error_ref, exc))
# Do not disclose internal details
filtered_exc = cgitb.text(sys.exc_info(), context=10)
# IMPORTANT: do NOT ever print or log raw password
pw = self.password
filtered_exc = filtered_exc.replace(pw, '*' * len(pw))
logger.debug("Traceback %s: %s" % (error_ref, filtered_exc))
self.send_response(500)
self.send_header('Content-type', 'text/html')
self.end_headers()
err_msg = """<p class='leftpad'>
Internal error while handling your request - please contact the site support
%s if this persistently happens and include the error reference %d.
</p>
<p>
<a href='javascript:history.back(-1);'>Back</a>
</p>""" % (configuration.support_email, error_ref)
# NOTE: socket write expects byte strings
self.wfile.write(force_utf8(err_msg))
def handleAllow(self, query):
"""Handle requests to allow authentication:
Must verify user is already logged in or validate username/password
pair against user DB.
"""
# Use client address directly but with optional local proxy override
hashed_secret = None
exceeded_rate_limit = False
invalid_username = False
invalid_user = False
account_accessible = False
valid_password = False
daemon_conf = configuration.daemon_conf
max_user_hits = daemon_conf['auth_limits']['max_user_hits']
user_abuse_hits = daemon_conf['auth_limits']['user_abuse_hits']
proto_abuse_hits = daemon_conf['auth_limits']['proto_abuse_hits']
max_secret_hits = daemon_conf['auth_limits']['max_secret_hits']
client_ip = self.headers.get('X-Forwarded-For', self.client_address[0])
if client_ip == self.client_address[0]:
tcp_port = self.client_address[1]
else:
tcp_port = 0
request = self.server.lastCheckIDRequest.get(self.user)
# NOTE: last request may be None here e.g. on back after illegal char!
if not request:
try:
request = self.server.openid.decodeRequest(query)
except server.ProtocolError as why:
# IMPORTANT: NEVER log or show raw why or query with password!
safe_query = strip_password(configuration, query)
safe_why = filter_why_pw(configuration, why)
logger.error("handleAllow got broken request %s: %s" %
(safe_query, safe_why))
# IMPORTANT: do NOT use displayResponse here! It would a.o.
# uncritically forward user any unverified return_to
# value in query.
self.showErrorPage('''<h2>Error in Communication</h2>
You may have discovered a bug in the %s OpenID 2.0 service. Please report it
to the site admins if you keep getting here. If you arrived here using the
browser "back" button, however, that is expected since it results in
inconsistent session state.
<h3>Error details:</h3>
<pre>%s</pre>
''' % (configuration.short_title, html_escape(safe_why)))
return
logger.debug("handleAllow with last request %s from user %s" %
(request, self.user))
# print "DEBUG: full query %s" % query
# Old IE 8 does not send contents of submit buttons thus only the
# fields login_as and password are set with the allow requests. We
# manually add a yes here if so to avoid the else case.
if not 'yes' in query and not 'no' in query:
query['yes'] = 'yes'
if 'yes' in query:
if 'login_as' in query:
self.user = self.query['login_as']
# print "handleAllow set user %s" % self.user
elif 'identifier' in query:
self.user = self.query['identifier']
elif self.user is None:
# Later handling refuses None as user
logger.error("no user in query")
self.user = ""
if request.idSelect():
# Do any ID expansion to a specified format
if daemon_conf['expandusername']:
user_id = lookup_full_identity(query.get('identifier', ''))
else:
user_id = query.get('identifier', '')
identity = self.server.base_url + 'id/' + user_id
else:
identity = request.identity
logger.debug("handleAllow with identity %s" % identity)
if hit_rate_limit(configuration, "openid",
client_ip, self.user,
max_user_hits=max_user_hits):
exceeded_rate_limit = True
elif not default_username_validator(configuration, self.user):
invalid_username = True
else:
if 'password' in self.query:
logger.debug("setting password")
self.password = self.query['password']
# NOTE: base64 encode expects byte strings
hashed_secret = make_simple_hash(
base64.b64encode(force_utf8(self.password)))
else:
logger.debug("no password in query")
self.password = None
account_accessible = check_account_accessible(
configuration, self.user, 'openid')
# NOTE: returns None for invalid user, and boolean otherwise
accepted = self.checkLogin(self.user, self.password, client_ip)
if accepted is None:
invalid_user = True
elif accepted:
valid_password = True
# Update rate limits and write to auth log
(authorized, _) = validate_auth_attempt(
configuration,
'openid',
'password',
self.user,
client_ip,
tcp_port,
secret=hashed_secret,
invalid_username=invalid_username,
invalid_user=invalid_user,
account_accessible=account_accessible,
skip_twofa_check=True,
authtype_enabled=True,
valid_auth=valid_password,
exceeded_rate_limit=exceeded_rate_limit,
user_abuse_hits=user_abuse_hits,
proto_abuse_hits=proto_abuse_hits,
max_secret_hits=max_secret_hits,
)
if authorized:
logger.debug("handleAllow validated login %s" % identity)
trust_root = request.trust_root
if self.query.get('remember', 'no') == 'yes':
self.server.approved[(identity, trust_root)] = 'always'
self.login_expire = int(time.time() + self.session_ttl)
logger.info("handleAllow approving login %s" % identity)
response = self.approved(request, identity)
else:
logger.warning("handleAllow rejected login %s" % identity)
# logger.debug("full query: %s" % self.query)
# logger.debug("full headers: %s" % self.headers)
fail_user, fail_pw = self.user, self.password
self.clearUser()
# Login failed - return to refering page to let user try again
retry_url = self.__retry_url_from_cookie()
if retry_url:
# Add error message to display
if retry_url.find('?') == -1:
retry_url += '?'
else:
retry_url += '&'
retry_url += 'err=loginfail'
else:
retry_url = self.server.base_url
self.redirect(retry_url)
return
elif 'no' in query:
response = request.answer(False)
else:
assert False, 'strange allow post. %r' % (query,)
self.displayResponse(response)
def setUser(self):
"""Read any saved user value from cookie"""
cookies = self.headers.get('Cookie')
# print "found cookies: %s" % cookies
if cookies:
morsel = http.cookies.BaseCookie(cookies).get('user')
# Added morsel value check here since IE sends empty string from
# cookie after initial user=;expire is sent. Others leave it out.
if morsel and morsel.value != '':
self.user = morsel.value
expire = int(time.time() + self.session_ttl)
morsel = http.cookies.BaseCookie(cookies).get('session_expire')
if morsel and morsel.value != '':
# print "found user session_expire value: %s" % morsel.value
if morsel.value.isdigit() and int(morsel.value) <= expire:
# print "using saved session expire: %s" % morsel.value
expire = int(morsel.value)
else:
logger.warning("invalid session_expire %s" % morsel.value)
self.login_expire = expire
def isAuthorized(self, identity_url, trust_root):
"""Check if user is authorized"""
if self.user is None:
return False
if identity_url != self.server.base_url + 'id/' + self.user:
return False
key = (identity_url, trust_root)
return self.server.approved.get(key) is not None
def serverEndPoint(self, query):
"""End-point handler"""
try:
request = self.server.openid.decodeRequest(query)
# Pass any errors from previous login attempts on for display
request.error = query.get('err', '')
except server.ProtocolError as why:
# IMPORTANT: NEVER log or show raw why or query with password!
safe_query = strip_password(configuration, query)
safe_why = filter_why_pw(configuration, why)
logger.error("serverEndPoint got broken request %s: %s" %
(safe_query, safe_why))
# IMPORTANT: do NOT use displayResponse here! It would a.o.
# uncritically forward user any unverified return_to
# value in query.
self.showErrorPage('''<h2>Error in Communication</h2>
You may have discovered a bug in the %s OpenID 2.0 service. Please report it
to the site admins if you keep getting here. If you arrived here using the
browser "back" button, however, that is expected since it results in
inconsistent session state.
<h3>Error details:</h3>
<pre>%s</pre>
''' % (configuration.short_title, html_escape(safe_why)))
return
if request is None:
# Display text indicating that this is an endpoint.
self.showAboutPage()
return
if request.mode in ["checkid_immediate", "checkid_setup"]:
self.handleCheckIDRequest(request)
else:
response = self.server.openid.handleRequest(request)
self.displayResponse(response)
def addSRegResponse(self, request, response):
"""SReg extended attributes handler"""
if not self.user:
return
sreg_req = sreg.SRegRequest.fromOpenIDRequest(request)
(username, user) = lookup_full_user(self.user)
if not user:
logger.warning("addSRegResponse user lookup failed!")
return
sreg_data = {}
for field in cert_field_names:
# Skip fields already set by alias
if field in sreg_data:
continue
# Backends choke on empty fields
found = user.get(field, None)
if found:
val = found
else:
val = 'NA'
# Add both the field and any alias values for now if found
sreg_data[field] = val
if found:
for alias in cert_field_aliases[field]:
sreg_data[alias] = val
# print "DEBUG: addSRegResponse added data:\n%s\n%s\n%s" % \
# (sreg_data, sreg_req.required, request)
sreg_resp = sreg.SRegResponse.extractResponse(sreg_req, sreg_data)
# print "DEBUG: addSRegResponse send response:\n%s" % sreg_resp.data
response.addExtension(sreg_resp)
def approved(self, request, identifier=None):
"""Accept helper"""
response = request.answer(True, identity=identifier)
self.addSRegResponse(request, response)
return response
def rejected(self, request, identifier=None):
"""Reject helper"""
response = request.answer(False, identity=identifier)
return response
def handleCheckIDRequest(self, request):
"""Check ID handler"""
logger.debug("handleCheckIDRequest with req %s" % request)
is_authorized = self.isAuthorized(request.identity, request.trust_root)
if is_authorized:
response = self.approved(request)
self.displayResponse(response)
elif request.immediate:
response = request.answer(False)
self.displayResponse(response)
else:
# print "DEBUG: adding user request to last dict: %s : %s" \
# % (self.user, request)
self.server.lastCheckIDRequest[self.user] = request
self.showDecidePage(request)
def displayResponse(self, response):
"""Response helper"""
try:
webresponse = self.server.openid.encodeResponse(response)
except server.EncodingError as why:
# IMPORTANT: NEVER log or show raw why or query with password!
safe_why = filter_why_pw(configuration, why)
logger.error("displayResponse failed encode: %s" % safe_why)
self.showErrorPage('''<h2>Error in Communication</h2>
You may have discovered a bug in the %s OpenID 2.0 service. Please report it
to the site admins if you keep getting here. If you arrived here using the
browser "back" button, however, that is expected since it results in
inconsistent session state.
<h3>Error details:</h3>
<pre>%s</pre>
''' % (configuration.short_title, html_escape(safe_why)))
return
self.send_response(webresponse.code)
for header, value in webresponse.headers.items():
self.send_header(header, value)
self.writeUserHeader()
self.end_headers()
if webresponse.body:
# NOTE: socket write expects byte strings
self.wfile.write(force_utf8(webresponse.body))
def checkLogin(self, username, password, addr):
"""Check username and password stored in MiG user DB.
Returns True on valid username+password, False on password mismatch and
None if no such user was found or username is invalid.
"""
# Only need to update users here
changed_users = []
if possible_user_id(configuration, username):
daemon_conf, changed_users = refresh_user_creds(configuration,
'openid',
username)
else:
logger.warning("Invalid username %s from %s" % (username, addr))
return None
update_login_map(daemon_conf, changed_users, [], [])
strict_policy = True
# Support password legacy policy during log in for transition periods
allow_legacy = True
# username may be None here
login_url = os.path.join(configuration.user_mig_oid_provider,
username or '')
distinguished_name = get_openid_user_dn(configuration, login_url)
entries = login_map_lookup(daemon_conf, username)
for entry in entries:
allowed = entry.password
if allowed is None or not password:
continue
# NOTE: We always enforce password policy here to refuse weak
# legacy passwords.
# NOTE: we prefer password hash but with fall back to scrambled
is_hashed = allowed.startswith('PBKDF2$')
if is_hashed and check_hash(configuration, 'openid', username,
password, allowed,
self.server.hash_cache, strict_policy,
allow_legacy):
logger.info("Accepted password hash login for %s from %s" %
(username, addr))
self.user_dn = distinguished_name
self.user_dn_dir = client_id_dir(distinguished_name)
self.login_expire = int(time.time() + self.session_ttl)
return True
elif not is_hashed and check_password_scramble(
configuration, 'openid', username, password, allowed,
configuration.site_password_salt,
self.server.scramble_cache, strict_policy, allow_legacy):
logger.info("Accepted password login for %s from %s" %
(username, addr))
self.user_dn = distinguished_name
self.user_dn_dir = client_id_dir(distinguished_name)
self.login_expire = int(time.time() + self.session_ttl)
return True
else:
logger.warning("Failed password check for user %s" % username)
if not entries:
logger.warning("No such user %s from %s" % (username, addr))
return None
else:
logger.error("Failed password login for %s from %s" %
(username, addr))
return False
def doLogin(self):
"""Login handler"""
hashed_secret = None
exceeded_rate_limit = False
invalid_username = False
invalid_user = False
account_accessible = False
valid_password = False