/
system.py
1997 lines (1502 loc) · 63.2 KB
/
system.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Colony Framework
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Colony Framework.
#
# Hive Colony Framework is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foundation, either version 2.0 of the License, or (at your option) any
# later version.
#
# Hive Colony Framework 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
# Apache License for more details.
#
# You should have received a copy of the Apache License along with
# Hive Colony Framework. If not, see <http://www.apache.org/licenses/>.
__author__ = "João Magalhães <joamag@hive.pt>"
""" The author(s) of the module """
__version__ = "1.0.0"
""" The version of the module """
__revision__ = "$LastChangedRevision$"
""" The revision number of the module """
__date__ = "$LastChangedDate$"
""" The last change date of the module """
__copyright__ = "Copyright (c) 2008-2020 Hive Solutions Lda."
""" The copyright for the module """
__license__ = "Apache License, Version 2.0"
""" The license for the module """
import hmac
import base64
import hashlib
import datetime
import colony
from . import parser
from . import exceptions
DEFAULT_CHARSET = "utf-8"
""" The default charset """
DEFAULT_EXPIRES_IN = "3600"
""" The default expires in """
DEFAULT_SIGNED_NAMES = (
"op_endpoint",
"return_to",
"response_nonce",
"assoc_handle",
"claimed_id",
"identity"
)
""" The default signed names """
DEFAULT_SIGNED_ITEMS = (
"provider_url",
"return_to",
"response_nonce",
"association_handle",
"claimed_id",
"identity"
)
""" The default signed items """
TRUE_VALUE = "true"
""" The true value """
FALSE_VALUE = "false"
""" The false value """
GET_METHOD_VALUE = "GET"
""" The get method value """
POST_METHOD_VALUE = "POST"
""" The post method value """
CONTENT_TYPE_CHARSET_VALUE = "content_type_charset"
""" The content type charset value """
HTTP_URI_VALUE = "http://"
""" The HTTP URI value """
HTTPS_URI_VALUE = "https://"
""" The HTTPS URI value """
XRI_URI_VALUE = "xri://="
""" The XRI URI value """
XRI_INITIALIZER_VALUE = "="
""" The XRI initializer value """
OPENID_NAMESPACE_VALUE = "http://specs.openid.net/auth/2.0"
""" The OpenID namespace value """
OPENID_SREG_1_1_EXTENSION_NAMESPACE_VALUE = "http://openid.net/extensions/sreg/1.1"
""" The OpenID SREG 1.1 extension namespace value """
OPENID_AX_1_0_EXTENSION_NAMESPACE_VALUE = "http://openid.net/srv/ax/1.0"
""" The OpenID ax 1.0 extension namespace value """
ASSOCIATE_MODE_VALUE = "associate"
""" The associate mode value """
CHECKID_SETUP_VALUE = "checkid_setup"
""" The checkid setup value """
CHECKID_IMMEDIATE_VALUE = "checkid_immediate"
""" The checkid immediate value """
ID_RES_VALUE = "id_res"
""" The id res value """
HMAC_SHA1_VALUE = "HMAC-SHA1"
""" The HMAC SHA1 value """
HMAC_SHA256_VALUE = "HMAC-SHA256"
""" The HMAC SHA256 value """
DH_SHA1_VALUE = "DH-SHA1"
""" The DH SHA1 value """
DH_SHA256_VALUE = "DH-SHA256"
""" The DH SHA256 value """
NO_ENCRYPTION_VALUE = "no-encryption"
""" The no encryption value """
XRDS_LOCATION_VALUE = "X-XRDS-Location"
""" The XRDS location value """
XRDS_LOCATION_LOWER_VALUE = "x-xrds-location"
""" The XRDS location lower value """
DEFAULT_OPENID_ASSOCIATE_TYPE = HMAC_SHA256_VALUE
""" The default OpenID associate type """
DEFAULT_OPENID_SESSION_TYPE = "no-encryption"
""" The default OpenID session type """
NONCE_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZUNIQUE"
""" The nonce time format """
MAXIMUM_NONCE_VALUES_LIST_SIZE = 1000
""" The maximum nonce values list size """
HMAC_HASH_MODULES_MAP = {
HMAC_SHA1_VALUE : hashlib.sha1,
HMAC_SHA256_VALUE : hashlib.sha256,
DH_SHA1_VALUE : hashlib.sha1,
DH_SHA256_VALUE : hashlib.sha1
}
""" The map associating the HMAC values with the hashlib
hash function modules """
DIFFIE_HELLMAN_ASSOCIATION_TYPES = (
DH_SHA1_VALUE,
DH_SHA256_VALUE
)
""" The diffie hellman association types """
DEFAULT_PRIME_VALUE = colony.legacy.LONG(155172898181473697471232257763715539915724801966915404479707795314057629378541917580651227423698188993727816152646631438561595825688188889951272158842675419950341258706556549803580104870537681476726513255747040765857479291291572334510643245094715007229621094194349783925984760375594985848253359305585439638443)
""" The default prime value to be used in Diffie Hellman """
DEFAULT_BASE_VALUE = 2
""" The default base value to be used in diffie hellman """
class APIOpenid(colony.System):
"""
The API OpenID class.
"""
nonce_values_map = {}
""" The map associating the provider URL with the nonce values """
def __init__(self, plugin):
colony.System.__init__(self, plugin)
self.nonce_values_map = {}
def create_server(self, api_attributes, open_server = True):
"""
Creates a server, with the given API attributes.
:type api_attributes: Dictionary
:param api_attributes: The API attributes to be used.
:type open_server: bool
:param open_server: If the server should be opened.
:rtype: OpenidServer
:return: The created server.
"""
# retrieves the Diffie Hellman plugin
diffie_hellman_plugin = self.plugin.diffie_hellman_plugin
# retrieves the random plugin
random_plugin = self.plugin.random_plugin
# retrieves the OpenID structure (if available) and uses it
# to create the "new" OpenID server
openid_structure = api_attributes.get("openid_structure", None)
openid_server = OpenidServer(
self.plugin,
diffie_hellman_plugin,
random_plugin,
self,
openid_structure
)
# in case the server is meant to be open
# opens the server
open_server and openid_server.open()
# returns the OpenID server
return openid_server
def create_client(self, api_attributes, open_client = True):
"""
Creates a client, with the given API attributes.
:type api_attributes: Dictionary
:param api_attributes: The API attributes to be used.
:type open_client: bool
:param open_client: If the client should be opened.
:rtype: OpenidClient
:return: The created client.
"""
# retrieves the client HTTP plugin
client_http_plugin = self.plugin.client_http_plugin
# retrieves the API Yadis plugin
api_yadis_plugin = self.plugin.api_yadis_plugin
# retrieves the OpenID structure (if available)
openid_structure = api_attributes.get("openid_structure", None)
# creates a new client with the given options, opens
# it in case it's required and returns the generated
# client to the caller method
openid_client = OpenidClient(self.plugin, client_http_plugin, api_yadis_plugin, self, openid_structure)
open_client and openid_client.open()
return openid_client
def _verify_nonce(self, nonce_value, provider_url):
"""
Verifies if the nonce value does not exists in the current
nonce values database. The validation is made in accordance
with the OpenID specification.
:type nonce_value: String
:param nonce_value: The nonce value to be verified.
:type provider_url: String
:param provider_url: The provider URL to be used in
the verification.
:rtype: bool
:return: The result of the verification.
"""
# in case the provider URL does not exists in the
# global nonce values map
if not provider_url in self.nonce_values_map:
return True
# retrieves the nonce values map
nonce_values_map = self.nonce_values_map[provider_url][2]
# in case the nonce value exists in the
# nonce values map (collision)
if nonce_value in nonce_values_map:
# returns false
return False
# returns true
return True
def _update_nonce(self, nonce_value, provider_url):
"""
Updates the nonce database by adding the nonce value
to it, using the provider URL.
:type nonce_value: String
:param nonce_value: The nonce value to be added.
:type provider_url: String
:param provider_url: The provider URL to be used in
the addition.
"""
# in case the provider URL is not defined
# in the nonce values map
if not provider_url in self.nonce_values_map:
# sets the nonce values map
self.nonce_values_map[provider_url] = {}
# sets the nonce values list and map
self.nonce_values_map[provider_url][1] = []
self.nonce_values_map[provider_url][2] = {}
# retrieves the nonce values list and map
nonce_values_list = self.nonce_values_map[provider_url][1]
nonce_values_map = self.nonce_values_map[provider_url][2]
# retrieves the nonce values list length
nonce_values_list_length = len(nonce_values_list)
# in case the list is full (it's a circular list)
# the list needs to be kept at the same size (last item is removed)
if nonce_values_list_length == MAXIMUM_NONCE_VALUES_LIST_SIZE:
# retrieves the last element from the
# nonce values list (the oldest)
last_element = nonce_values_list[-1]
# removes the last element from the nonce values map
del nonce_values_map[last_element]
# pops the last element from the nonce values list
nonce_values_list.pop()
# inserts the item at the beginning of the list
# and sets the item in the map
nonce_values_list.insert(0, nonce_value)
nonce_values_map[nonce_value] = True
def _btwoc(self, long_value):
"""
Given some kind of integer (generally a long), this function
returns the big-endian two's complement as a binary string.
:type value: int
:param value: The value to be converted.
:rtype: String
:return: The big-endian two's complement as a binary string.
"""
# encodes the long value into string value
long_value_encoded = colony.encode_two_complement_string(long_value)
# converts the long value to a list value
list_value = list(long_value_encoded)
# reverses the list
list_value.reverse()
# joins the list to retrieve the result
result = "".join(list_value)
# returns the result
return result
def _mklong(self, btwoc):
"""
Given a big-endian two's complement string, return the
long int it represents.
:type btwoc: String
:param btwoc: A big-endian two's complement string
:rtype: int
:return: The decoded int value.
"""
# converts the string value to string
list_value = list(btwoc)
# reverses the string value
list_value.reverse()
# joins the list value to retrieve the string value
string_value = "".join(list_value)
# decodes the string value into long
result = colony.decode_two_complement_string(string_value)
# returns the result
return result
class OpenidServer(object):
"""
The class that represents an OpenID server connection.
"""
api_openid_plugin = None
""" The API OpenID plugin """
diffie_hellman_plugin = None
""" The Diffie Hellman plugin """
random_plugin = None
""" The random plugin """
api_openid = None
""" The API OpenID """
openid_structure = None
""" The OpenID structure """
diffie_hellman = None
""" the Diffie Hellman management structure """
def __init__(
self,
api_openid_plugin = None,
diffie_hellman_plugin = None,
random_plugin = None,
api_openid = None,
openid_structure = None,
diffie_hellman = None
):
"""
Constructor of the class.
:type api_openid_plugin: APIOpenidPlugin
:param api_openid_plugin: The API OpenID plugin.
:type diffie_hellman_plugin: DiffieHellmanPlugin
:param diffie_hellman_plugin: The Diffie Hellman plugin.
:type random_plugin: RandomPlugin
:param random_plugin: The random plugin.
:type api_openid: ServiceOpenid
:param api_openid: The API OpenID.
:type openid_structure: OpenidStructure
:param openid_structure: The OpenID structure.
:type diffie_hellman: DiffieHellman
:param diffie_hellman: The Diffie Hellman management structure.
"""
self.api_openid_plugin = api_openid_plugin
self.diffie_hellman_plugin = diffie_hellman_plugin
self.random_plugin = random_plugin
self.api_openid = api_openid
self.openid_structure = openid_structure
self.diffie_hellman = diffie_hellman
def open(self):
"""
Opens the OpenID server.
"""
pass
def close(self):
"""
Closes the OpenID server.
"""
pass
def generate_openid_structure(
self,
provider_url = None,
association_type = HMAC_SHA256_VALUE,
session_type = NO_ENCRYPTION_VALUE,
prime_value = None,
base_value = None,
consumer_public = None,
set_structure = True
):
# creates a new OpenID structure
openid_structure = OpenidStructure(
provider_url,
association_type = association_type,
session_type = session_type
)
# in case the structure is meant to be set
# sets the OpenID structure
if set_structure: self.set_openid_structure(openid_structure)
# decodes the Diffie Hellman values in case they exist
prime_value = prime_value and self.api_openid._mklong(base64.b64decode(prime_value)) or None
base_value = base_value and self.api_openid._mklong(base64.b64decode(base_value)) or None
consumer_public = consumer_public and self.api_openid._mklong(base64.b64decode(consumer_public)) or None
# sets the default Diffie Hellman values
prime_value = prime_value or DEFAULT_PRIME_VALUE
base_value = base_value or DEFAULT_BASE_VALUE
# creates the parameters to send to be used in the Diffie Hellman
# structure creation
parameters = dict(
prime_value = prime_value,
base_value = base_value
)
# creates the Diffie Hellman management structure with the prime
# and base values given
self.diffie_hellman = self.diffie_hellman_plugin.create_structure(parameters)
# sets the a value in the Diffie Hellman structure
self.diffie_hellman.set_A_value(consumer_public)
# returns the OpenID structure
return openid_structure
def openid_associate(self):
"""
Requests an association (associate mode) according to the
OpenID specification.
:rtype: OpenidStructure
:return: The current OpenID structure.
"""
# generates an association handle
association_handle = self._generate_handle()
# retrieves the MAC key type to be used
mac_key_type = self._get_mac_key_type()
# generates the MAC key
mac_key = self._generate_mac_key(mac_key_type)
# sets the association handle in the OpenID structure
self.openid_structure.association_handle = association_handle
# sets the expires in in the OpenID structure
self.openid_structure.expires_in = DEFAULT_EXPIRES_IN
# sets the MAC key in the OpenID structure
self.openid_structure.mac_key = mac_key
# in case the current session type is of type diffie hellman
if self.openid_structure.session_type in DIFFIE_HELLMAN_ASSOCIATION_TYPES:
# generates a private key for the diffie hellman "b" value
private_key = self._generate_private_key()
# sets the "b" value in the diffie hellman management structure
self.diffie_hellman.set_b_value(private_key)
# returns the OpenID structure
return self.openid_structure
def openid_request(self):
# generates an invalidate handle if necessary
invalidate_handle = self.openid_structure.invalidate_handle or self._generate_handle()
# retrieves the current date time
current_date_time = datetime.datetime.utcnow()
# converts the current date time to string
current_date_time_string = current_date_time.strftime(NONCE_TIME_FORMAT)
# generates a random handle
random_handle = self._generate_handle()
# creates the response nonce appending the current date time string
# to the random handle
response_nonce = current_date_time_string + random_handle
# sets the mode in the OpenID structure
self.openid_structure.mode = ID_RES_VALUE
# sets the invalidate handle in the OpenID structure
self.openid_structure.invalidate_handle = invalidate_handle
# sets the response nonce in the OpenID structure
self.openid_structure.response_nonce = response_nonce
# sets the signed in the OpenID structure
self.openid_structure.signed = ",".join(DEFAULT_SIGNED_NAMES)
# generates the signature
signature = self._generate_signature()
# sets the signature in the OpenID structure
self.openid_structure.signature = signature
def openid_check_authentication(self, return_openid_structure, strict = True):
"""
Verifies the given return OpenID structure (verification)
according to the OpenID specification.
:type return_openid_structure: OpenidStructure
:param return_openid_structure: The return OpenID structure
to be verified.
:type strict: bool
:param strict: Flag to control if the verification should be strict.
:rtype: OpenidStructure
:return: The current OpenID structure.
"""
# in case the verification is strict and any of the base information items mismatches
if strict and not (self.openid_structure.return_to == return_openid_structure.return_to and\
self.openid_structure.claimed_id == return_openid_structure.claimed_id and\
self.openid_structure.identity == return_openid_structure.identity and\
self.openid_structure.provider_url == return_openid_structure.provider_url and\
self.openid_structure.response_nonce == return_openid_structure.response_nonce and\
self.openid_structure.signed == return_openid_structure.signed and\
self.openid_structure.signature == return_openid_structure.signature and\
return_openid_structure.ns == OPENID_NAMESPACE_VALUE):
# raises a verification failed exception
raise exceptions.VerificationFailed("invalid discovered information")
# returns the OpenID structure
return self.openid_structure
def get_response_parameters(self):
# start the parameters map
parameters = {}
# sets the namespace
parameters["ns"] = self.openid_structure.ns
# sets the association handle
parameters["assoc_handle"] = self.openid_structure.association_handle
# sets the session type
parameters["session_type"] = self.openid_structure.session_type
# sets the association type
parameters["assoc_type"] = self.openid_structure.association_type
# sets the expires in
parameters["expires_in"] = self.openid_structure.expires_in
# in case the current session type is of type diffie hellman
if self.openid_structure.session_type in DIFFIE_HELLMAN_ASSOCIATION_TYPES:
# retrieves the MAC key type to be used
mac_key_type = self._get_mac_key_type()
# generates the "B" value
B_value = self.diffie_hellman.generate_B()
# calculates the shared key value
key_value = self.diffie_hellman.calculate_Kb()
# decodes the MAC key using Base64
decoded_mac_key = base64.b64decode(self.openid_structure.mac_key)
# retrieves the hash module from the HMAC hash modules map
hash_module = HMAC_HASH_MODULES_MAP.get(mac_key_type, None)
# encodes the key value in order to be used in the xor operation
encoded_key_value = hash_module(self.api_openid._btwoc(key_value)).digest()
# calculates the encoded MAC key value and retrieves the digest
encoded_mac_key = colony.xor_string_value(decoded_mac_key, encoded_key_value)
# encodes the encoded MAC key into Base64
encoded_mac_key = base64.b64encode(encoded_mac_key)
# sets the DH server public
parameters["dh_server_public"] = base64.b64encode(self.api_openid._btwoc(B_value))
# sets the encoded MAC key
parameters["enc_mac_key"] = encoded_mac_key
else:
# sets the MAC key
parameters["mac_key"] = self.openid_structure.mac_key
# returns the parameters
return parameters
def get_encoded_response_parameters(self):
# retrieves the response parameters
response_parameters = self.get_response_parameters()
# encodes the response parameters
encoded_response_parameters = self._encode_key_value(response_parameters)
# returns the encoded response parameters
return encoded_response_parameters
def get_check_authentication_parameters(self):
# start the parameters map
parameters = {}
# sets the namespace
parameters["ns"] = self.openid_structure.ns
# sets the is valid
parameters["is_valid"] = TRUE_VALUE
# sets the invalidate handle
parameters["invalidate_handle"] = self.openid_structure.association_handle
# returns the parameters
return parameters
def get_encoded_check_authentication_parameters(self):
# retrieves the check authentication parameters
check_authentication_parameters = self.get_check_authentication_parameters()
# encodes the check authentication parameters
encoded_check_authentication_parameters = self._encode_key_value(check_authentication_parameters)
# returns the encoded check authentication parameters
return encoded_check_authentication_parameters
def get_return_url(self):
# sets the retrieval URL
retrieval_url = self.openid_structure.return_to
# start the parameters map and sets the complete set of
# parameters associated with the return URL, these values
# are taken from the current structure instance
parameters = {}
parameters["openid.ns"] = self.openid_structure.ns
parameters["openid.mode"] = self.openid_structure.mode
parameters["openid.op_endpoint"] = self.openid_structure.provider_url
parameters["openid.claimed_id"] = self.openid_structure.claimed_id
parameters["openid.identity"] = self.openid_structure.identity
parameters["openid.return_to"] = self.openid_structure.return_to
parameters["openid.response_nonce"] = self.openid_structure.response_nonce
parameters["openid.invalidate_handle"] = self.openid_structure.invalidate_handle
parameters["openid.assoc_handle"] = self.openid_structure.association_handle
parameters["openid.signed"] = self.openid_structure.signed
parameters["openid.sig"] = self.openid_structure.signature
# creates the request (get) URL from the parameters and returns
# the value to the caller method
request_url = self._build_get_url(retrieval_url, parameters)
return request_url
def get_openid_structure(self):
"""
Retrieves the OpenID structure.
:rtype: OpenidStructure
:return: The OpenID structure.
"""
return self.openid_structure
def set_openid_structure(self, openid_structure):
"""
Sets the OpenID structure.
:type openid_structure: OpenidStructure
:param openid_structure: The OpenID structure.
"""
self.openid_structure = openid_structure
def _get_mac_key_type(self):
"""
Retrieves the type of hashing to be used in the
MAC key.
:rtype: String
:return: The type of hashing to be used in the MAC key.
"""
# in case the current session is of type no encryption
if self.openid_structure.session_type == NO_ENCRYPTION_VALUE:
# returns the current association type
return self.openid_structure.association_type
# in case the current session is of type DH SHA1
elif self.openid_structure.session_type == DH_SHA1_VALUE:
# returns the HMAC SHA1 value
return HMAC_SHA1_VALUE
# in case the current session is of type DH SHA256
elif self.openid_structure.session_type == DH_SHA256_VALUE:
# returns the HMAC sha256 value
return HMAC_SHA256_VALUE
def _generate_signature(self):
# sets the signature items list
signed_items_list = DEFAULT_SIGNED_ITEMS
# sets the signature names list
signed_names_list = DEFAULT_SIGNED_NAMES
# creates the string buffer for the message
message_string_buffer = colony.StringBuffer()
# starts the index counter
index = 0
# iterates over all the signed items
for signed_item_name in signed_items_list:
# retrieves the signed item value from the return OpenID structure
signed_item_value = getattr(self.openid_structure, signed_item_name)
# retrieves the signed item real name
signed_item_real_name = signed_names_list[index]
# adds the key value pair to the message string buffer
message_string_buffer.write(signed_item_real_name.encode(DEFAULT_CHARSET) + ":" + signed_item_value.encode(DEFAULT_CHARSET) + "\n")
# increments the index
index += 1
# retrieves the value from the message string buffer
message = message_string_buffer.get_value()
# decodes the signature MAC key from Base64
signature_mac_key = base64.b64decode(self.openid_structure.mac_key)
# retrieves the hash module from the HMAC hash modules map
hash_module = HMAC_HASH_MODULES_MAP.get(self.openid_structure.association_type, None)
# in case no hash module is set
if not hash_module:
# raises the invalid hash function exception
raise exceptions.InvalidHashFunction("the hash function is not available: " + self.openid_structure.association_type)
# calculates the signature value and retrieves the digest
signature = hmac.new(signature_mac_key, message, hash_module).digest()
# encodes the signature into Base64
signature = base64.b64encode(signature)
# returns the signature
return signature
def _generate_handle(self):
# generates a random SHA1
random_sha1 = self.random_plugin.generate_random_sha1()
# retrieves the random SHA1 value
random_sha1_value = random_sha1.digest()
# encodes the random SHA1 value into Base64
handle = base64.b64encode(random_sha1_value)
# returns the handle
return handle
def _generate_mac_key(self, mac_key_type = HMAC_SHA1_VALUE):
# in case the key type is SHA1
if mac_key_type == HMAC_SHA1_VALUE:
# generates a MAC key with the SHA1 random value
mac_key = self.random_plugin.generate_random_sha1()
# in case the key type is sha256
elif mac_key_type == HMAC_SHA256_VALUE:
# generates a MAC key with the sha256 random value
mac_key = self.random_plugin.generate_random_sha256()
# retrieves the MAC key value
mac_key_value = mac_key.digest()
# encodes the MAC key into Base64
mac_key_value_encoded = base64.b64encode(mac_key_value)
# returns the encoded MAC key value
return mac_key_value_encoded
def _generate_private_key(self):
"""
Generates a private key long number, based in the current
diffie hellman "p" value.
"""
# retrieves the diffie hellman "p" value
diffie_hellman_p_value = self.diffie_hellman.get_p_value()
# generates a "pure" random value
random_value = self.random_plugin.generate_random_value()
# normalizes the random value, creating the private key value
private_key_value = int(random_value * diffie_hellman_p_value - 1)
# returns the private key value
return private_key_value
def _build_get_url(self, base_url, parameters):
"""
Builds the URL for the given URL and parameters.
The URL is valid only for a get request.
:type base_url: String
:param base_url: The base URL to be used.
:type parameters: Dictionary
:param parameters: The parameters to be used for URL construction.
:rtype: String
:return: The built URL for the given parameters.
"""
# encodes the parameters with the URL encode
parameters_encoded = colony.url_encode(parameters)
# in case the base URL does not contain any parameters
if base_url.find("?") == -1:
# creates the URL value by appending the base URL with
# the parameters encoded (new parameters)
url = base_url + "?" + parameters_encoded
# otherwise
else:
# creates the URL value by appending the base URL with
# the parameters encoded (existing parameters)
url = base_url + "&" + parameters_encoded
# returns the built URL
return url
def _encode_key_value(self, values_map):
"""
Encodes the given values map into the key value
encoding.
:type values_map: Dictionary
:param values_map: The map containing the values to be
encoded.
:rtype: String
:return: The key value encoded string.
"""
return "\n".join([key + ":" + value for key, value in colony.legacy.items(values_map)])
class OpenidClient(object):
"""
The class that represents an OpenID client connection.
"""
api_openid_plugin = None
""" The API OpenID plugin """
client_http_plugin = None
""" The client HTTP plugin """
api_yadis_plugin = None
""" The API Yadis plugin """
api_openid = None
""" The API OpenID """
openid_structure = None
""" The OpenID structure """
http_client = None
""" The HTTP client for the connection """
yadis_client = None
""" The Yadis (remote) client for the connection """
def __init__(
self,
api_openid_plugin = None,
client_http_plugin = None,
api_yadis_plugin = None,
api_openid = None,
openid_structure = None
):
"""
Constructor of the class.
:type api_openid_plugin: APIOpenidPlugin
:param api_openid_plugin: The API OpenID plugin.
:type client_http_plugin: ClientHTTPPlugin
:param client_http_plugin: The client HTTP plugin.
:type api_yadis_plugin: APIYadisPlugin
:param api_yadis_plugin: The API Yadis plugin.
:type api_openid: ServiceOpenid
:param api_openid: The API OpenID.
:type openid_structure: OpenidStructure
:param openid_structure: The OpenID structure.
"""
self.api_openid_plugin = api_openid_plugin
self.client_http_plugin = client_http_plugin
self.api_yadis_plugin = api_yadis_plugin
self.api_openid = api_openid
self.openid_structure = openid_structure
def open(self):
"""
Opens the OpenID client.
"""
pass
def close(self):
"""
Closes the OpenID client.
"""
# in case an HTTP client is defined, must close
# it to avoid any leak in HTTP associated resources
if self.http_client: self.http_client.close({})
# in case an Yadis (remote) client is defined, must
# close it to avoid any leak in resources
if self.yadis_client: self.yadis_client.close()
def generate_openid_structure(
self,
provider_url,
claimed_id,
identity,
return_to,
realm,
association_type = DEFAULT_OPENID_ASSOCIATE_TYPE,
session_type = DEFAULT_OPENID_SESSION_TYPE,
set_structure = True
):
# creates a new OpenID structure
openid_structure = OpenidStructure(provider_url, claimed_id, identity, return_to, realm, association_type, session_type)
# in case the structure is meant to be set
if set_structure:
# sets the OpenID structure