-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqOpenid.php
1065 lines (952 loc) · 31.5 KB
/
sqOpenid.php
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
<?php
/**
* OpenID 2.0 Relay party
*
* @autor nbari - Oct 2012
* @package slashQuery
* @link http://openid.net/specs/openid-authentication-2_0.html
* @license http://www.opensource.org/licenses/bsd-license.php
*/
class sqOpenID {
/**
* openid.dh_modulus - base64(btwoc(p))
* Diffie-Hellman Key Exchange Default Value
*
* @see section 8.1.2 of specification
*/
const OPENID_DH_MODULUS = '155172898181473697471232257763715539915724801966915404479707795314057629378541917580651227423698188993727816152646631438561595825688188889951272158842675419950341258706556549803580104870537681476726513255747040765857479291291572334510643245094715007229621094194349783925984760375594985848253359305585439638443';
/**
* openid.dh_gen - base64(btwoc(g))
*
* @see section 8.1.2 of specification
*/
const OPENID_DH_GEN = 2;
/**
* ns
*
* @see section 5.1.2 of specification
*/
const OPENID_NS_2_0 = 'http://specs.openid.net/auth/2.0';
/**
* Extensible Resource Descriptor documents.
*/
const OPENID_NS_XRD = 'xri://$xrd*($v*2.0)';
/**
* identifier_select
*/
const OPENID_IDENTIFIER_SELECT = 'http://specs.openid.net/auth/2.0/identifier_select';
/**
* OpenID Simple Registration extension.
*/
const OPENID_NS_SREG = 'http://openid.net/extensions/sreg/1.1';
/**
* OpenID Attribute Exchange extension.
*
* @link http://openid.net/specs/openid-attribute-exchange-1_0.html
*/
const OPENID_AX = 'http://openid.net/srv/ax/1.0';
/**
* URI Generic Syntax
*
* @link http://www.ietf.org/rfc/rfc3986.txt
* @see Appendix B. Parsing a URI Reference with a Regular Expression
*/
const URI_REGEX = '@^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?@';
/**
* URL to which the OP SHOULD return the User-Agent with the response
* indicating the status of the request
*
* @var string
*/
private $return_to;
/**
* URL pattern the OP SHOULD ask the end user to trust
*
* @var string
*/
private $realm;
/**
* normalized into an Identifier
*
* @var string
*/
private $identity;
/**
* The Claimed Identifier set after the discovery proccess
*
* @var string
*/
private $claimed_id;
/**
* OP Endpoint URL
*
* @see 7.3.1. Discovered Information
* @link http://openid.net/specs/openid-authentication-2_0.html#discovery
* @var string
*/
private $provider;
/**
* Set Max number of request to avoid endless redirections.
*
* @var int
*/
private $max_requests = 5;
/**
* OpenID extensions
*
* @var array
*/
private $service_types = array ();
/**
* XRI identifier
*
* @var boolean
*/
private $xri = false;
/**
* curl Requests responses
*/
private $headers, $body;
/**
* OP response
*
* @var array
*/
private $response = array ();
/**
* AX <==> SREG
* @var array
*/
protected $ax_to_sreg = array (
'namePerson/friendly' => 'nickname',
'contact/email' => 'email',
'namePerson' => 'fullname',
'birthDate' => 'dob',
'person/gender' => 'gender',
'contact/postalCode/home' => 'postcode',
'contact/country/home' => 'country',
'pref/language' => 'language',
'pref/timezone' => 'timezone'
);
/**
* required, optional and params used for sreg,ax
*/
private $required = array(), $optional = array(), $params = array();
/**
* __construct
*
* @see http://openid.net/specs/openid-authentication-2_0.html#anchor27
* @param string $host The realm OP SHOULD ask the end user to trust.
*/
public function __construct($host = null) {
if (PHP_SAPI === 'cli') {
return;
}
if ($host) {
$host = strpos( $host, '://' ) ? $host : ($this->usingSSL() ? "https://$host" : "http://$host");
} else {
$host = ($this->usingSSL() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];
}
/* remove URI from host */
if (($host_end = strpos( $host, '/', 8 )) !== false) {
$host = substr( $host, 0, $host_end );
}
$this->realm = $host;
/* remove all openid. arguments from url */
$this->return_to = $host . rtrim( preg_replace( '#((?<=\?)|&)openid\.[^&]+#', '', $_SERVER['REQUEST_URI'] ), '?' );
/* store $_GET + $_POST */
$this->response = $_REQUEST;
}
/**
* getResponse
*
* @param string $key
* @return string/array $_REQUEST
*/
public function getResponse($key = null) {
if ($key) {
return (array_key_exists( $key, $this->response ) && isset( $this->response[$key] )) ? $this->response[$key] : false;
}
return $this->response;
}
/**
* usingSSL
*
* @return string/boolean
*/
public function usingSSL() {
return ((isset( $_SERVER['HTTPS'] ) && strtolower( $_SERVER['HTTPS'] ) == 'on') || (isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && strtolower( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) == 'https'));
}
/**
* setIdentity - The end user's input MUST be normalized into an Identifier.
*
* @link http://openid.net/specs/openid-authentication-2_0.html#normalization
* @param string $openid_identifier
* @return sqOpenID
*/
public function setIdentity($openid_identifier) {
$oi = preg_replace( '#/+$#', '', stripslashes( trim( $openid_identifier ) ) );
/**
* If the URL contains a fragment part, it MUST be stripped off together
* with the fragment delimiter character "#"
*
* @see 7.2. Normalization
*/
$oi = strtok( $oi, '#' );
if (preg_match( '#^xri:/*#i', $oi, $m )) {
$this->xri = true;
$oi = 'https://xri.net/' . substr( $oi, strlen( $m[0] ) );
} elseif (preg_match( '#^[=@+$!(]#', $oi )) {
$this->xri = true;
$oi = 'https://xri.net/' . $oi;
} elseif (preg_match( '#^https?://[^/]+$#i', $oi )) {
$oi .= '/';
} elseif (! preg_match( '#https?://#i', $oi )) {
$oi = "http://$oi/";
}
/**
* set the identity
*/
$this->identity = $this->normalizeURL($oi);
/**
* return this so it can be chainable
*/
return $this;
}
/**
* set required params
* @see OpenID Attribute Exchange 1.0 - Final
*/
public function required() {
$this->required = array_flip(func_get_args());
}
/**
* set optional params
* @see OpenID Attribute Exchange 1.0 - Final
*/
public function optional() {
$this->optional = array_flip(func_get_args());
}
/**
* getClaimedID
*
* The Claimed Identifier in a successful authentication response SHOULD be
* used by the Relying Party as a key for local storage of information about
* the user.
*
* @return string openid.claimed_id
*/
public function getClaimedID() {
return $this->claimed_id;
}
/**
* request
*
* @param string $url
* @return boolean
*/
protected function request($url, $xrds = true, $method = 'GET', $params = array()) {
$params = http_build_query( $params, '', '&' );
$ch = curl_init( $url . ($method == 'GET' && $params ? '?' . $params : '') );
curl_setopt( $ch, CURLOPT_USERAGENT, __CLASS__ . ' - OpenID v2' );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_HEADER, false );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
if ($method == 'POST') {
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $params );
} else {
curl_setopt( $ch, CURLOPT_HEADER, true );
curl_setopt( $ch, CURLOPT_HTTPGET, true );
}
if ($xrds) {
curl_setopt( $ch, CURLOPT_HTTPHEADER, array (
'Accept: application/xrds+xml, */*'
) );
}
$response = curl_exec( $ch );
if ($method == 'GET') {
$header_size = curl_getinfo( $ch, CURLINFO_HEADER_SIZE );
$header = substr( $response, 0, $header_size );
$this->body = substr( $response, $header_size );
} else {
$header = $response;
}
$headers = array ();
foreach ( explode( "\n", $header ) as $h ) {
$pos = strpos( $h, ':' );
if ($pos !== false) {
$name = strtolower( trim( substr( $h, 0, $pos ) ) );
$headers[$name] = trim( substr( $h, $pos + 1 ) );
}
}
$this->headers = $headers;
$effective_url = curl_getinfo( $ch, CURLINFO_EFFECTIVE_URL );
if ($effective_url != $url) {
$this->identity = $effective_url;
}
if (curl_errno( $ch )) {
return false;
}
return true;
}
/**
* Discover
*
* Discovery is the process where the Relying Party uses the
* Identifier to look up ("discover") the necessary information for initiating
* requests.
*
* @see http://openid.net/specs/openid-authentication-2_0.html#discovery
* @return boolean
*/
public function Discover() {
return $this->DiscoverYadis() ? : ($this->DiscoverHTML() ? : false);
}
/**
* DiscoverYadis
*
* @see 7.3.2. XRDS-Based Discovery
* @return boolean
*/
protected function DiscoverYadis($url = null) {
/* decrease max_requests -1 */
$this->max_requests --;
$url = isset( $url ) ? $url : $this->identity;
if ($this->request( $url ) && $this->max_requests) {
if (isset( $this->headers['content-type'] ) && (strpos( $this->headers['content-type'], 'application/xrds+xml' ) !== false)) {
$services = array ();
try {
$xml = @new SimpleXMLElement( $this->body );
foreach ( $xml->children( self::OPENID_NS_XRD )->XRD as $xrd ) {
foreach ( $xrd->children( self::OPENID_NS_XRD )->Service as $service_element ) {
$service = array (
'priority' => $service_element->attributes()->priority ? (int) $service_element->attributes()->priority : PHP_INT_MAX,
'types' => array (),
'uri' => (string) $service_element->URI,
'identity' => (string) $service_element->LocalID ? : false
);
/**
*
* @see 7.3.2.3. XRI and the CanonicalID Element
*/
if ($this->xri) {
$service['canonicalid'] = (string) $xrd->children( self::OPENID_NS_XRD )->CanonicalID;
}
foreach ($service_element->Type as $type) {
$service['types'][] = (string) $type;
}
/* search for openid v2 ns */
$ns = preg_quote( self::OPENID_NS_2_0, '#' );
if (! preg_grep( "#$ns#", $service['types'] )) {
continue;
}
$services[] = $service;
}
}
} catch ( Exception $e ) {
return false;
}
if (empty( $services )) {
return false;
}
/**
* Extensible Resource Identifier (XRI) Resolution Version 2.0, section
* 4.3.3:
* Find the service with the highest priority (lowest integer value).
* If there is a tie, select a random one, not just the first in the XML
* document.
*/
shuffle( $services );
$selected_service = NULL;
$selected_type_priority = FALSE;
$type_priority = 0;
foreach ($services as $service) {
if (! empty( $service['uri'] )) {
if (in_array( self::OPENID_NS_2_0 . '/server', $service['types'] )) {
$type_priority = 1;
} elseif (in_array( self::OPENID_NS_2_0 . '/signon', $service['types'] )) {
$type_priority = 2;
}
if ($type_priority && (! $selected_service || $type_priority < $selected_type_priority
|| ($type_priority == $selected_type_priority && $service['priority'] < $selected_service['priority']))) {
$selected_service = $service;
$selected_type_priority = $type_priority;
}
}
}
if ($selected_service) {
$this->provider = $selected_service['uri'];
if ($selected_type_priority == 1) {
/**
* If the end user entered an OP Identifier, there is no Claimed
* Identifier.
* For the purposes of making OpenID Authentication requests, the
* value "http://specs.openid.net/auth/2.0/identifier_select" MUST
* be used as both the Claimed Identifier and the OP-Local
* Identifier when an OP Identifier is entered.
*
* @see 7.3.1. Discovered Information
*/
$this->claimed_id = $this->identity = self::OPENID_IDENTIFIER_SELECT;
} elseif ($selected_service['identity']) {
/**
* <xrd:LocalID> tag (optional) whose text content is the
* OP-Local Identifier.
*
* @see 7.3.2.1.2. Claimed Identifier Element
*/
$this->claimed_id = $this->identity = $selected_service['identity'];
} elseif ($this->xri && ! empty( $selected_service['canonicalid'] )) {
$this->claimed_id = $this->identity = $selected_service['canonicalid'];
} else {
$this->claimed_id = $this->identity;
}
$this->service_types = $selected_service['types'];
return true;
} else {
return false;
}
} elseif (isset( $this->headers['x-xrds-location'] )) {
return $this->DiscoverYadis( $this->headers['x-xrds-location'] );
} else {
@$html_dom = DOMDocument::loadHTML( $this->body );
if ($html_dom) {
$html_element = simplexml_import_dom( $html_dom );
foreach ($html_element->head->meta as $meta) {
// The http-equiv attribute is case-insensitive.
if (strtolower( trim( $meta['http-equiv'] ) ) == 'x-xrds-location') {
return $this->DiscoverYadis( trim( $meta['content'] ) );
}
}
}
return false;
}
} else {
return false;
}
}
/**
* DiscoverHTML
*
* @see 7.3.3. HTML-Based Discovery
* @return boolean
*/
protected function DiscoverHTML() {
if ($this->parseHTML( $this->body )) {
return true;
} else {
return $this->request( $this->identity, false ) ? $this->parseHTML( $this->body ) : false;
}
}
/**
* parseHTML
* @retun boolean
*/
protected function parseHTML($body) {
@$html_dom = DOMDocument::loadHTML( $body );
if ($html_dom) {
$html_element = simplexml_import_dom( $html_dom );
foreach ($html_element->head->link as $link) {
if (preg_match( '#(\s|^)openid2.provider(\s|$)#i', $link['rel'] )) {
$this->provider = trim( $link['href'] );
}
if (preg_match( '#(\s|^)openid2.local_id(\s|$)#i', $link['rel'] )) {
$this->identity = $this->claimed_id = trim( $link['href'] );
}
}
if (! $this->claimed_id) {
$this->claimed_id = $this->identity = self::OPENID_IDENTIFIER_SELECT;
}
return ($this->provider) ? true : false;
}
return false;
}
/**
* Auth
*
* @see 9.1. Request Parameters
* @link http://openid.net/specs/openid-authentication-2_0.html#anchor27
* @return string OP Endpoint URL
*/
public function Auth() {
$this->params = array (
'openid.ns' => self::OPENID_NS_2_0,
'openid.mode' => 'checkid_setup',
'openid.claimed_id' => $this->claimed_id,
'openid.identity' => $this->identity,
'openid.return_to' => $this->return_to,
'openid.realm' => $this->realm
);
if ($this->required || $this->optional) {
$this->sregParams();
$this->axParams();
}
/**
* Create an Association and if possible store it in cache
*/
if ($association = $this->associate()) {
/**
* A handle for an association between the Relying Party and the OP that
* SHOULD be used to sign the response.
* Note: If no association handle is sent, the transaction will take
* place in Stateless Mode.
*/
$this->params['openid.assoc_handle'] = $association['assoc_handle'];
}
$s = strpos( $this->provider, '?' ) ? '&' : '?';
/**
* client must be redirected to the OP Endpoint URL
* we return the URL and don't use header('location: ...') here because 'AJAX'.
* developer must found a way to redirect the use to the OP Endpoint
*/
return $this->provider . $s . http_build_query( $this->params, '', '&' );
}
/**
* sregParams
*
* @link http://openid.net/specs/openid-simple-registration-extension-1_0.html
* @see 3. Request Format
*/
protected function sregParams() {
$this->params['openid.ns.sreg'] = self::OPENID_NS_SREG;
if ($this->required) {
$this->params['openid.sreg.required'] = implode(',', array_intersect_key( $this->ax_to_sreg, $this->required ) );
}
if ($this->optional) {
$this->params['openid.sreg.optional'] = implode(',', array_intersect_key( $this->ax_to_sreg, $this->optional ) );
}
}
/**
* AX parameters
*
* @link http://openid.net/specs/openid-attribute-exchange-1_0.html
* @see 5. Fetch Message
*/
protected function axParams() {
$this->params['openid.ns.ax'] = self::OPENID_AX;
$this->params['openid.ax.mode'] = 'fetch_request';
$aliases = array();
$required = array();
$optional = array();
/**
* $this->required contains an array of required AX parameters
* $this->optional contains an array of optional AX parameters.
*/
foreach ( array ('required', 'optional') as $type ) {
foreach ($this->$type as $path => $key) {
$alias = strtr($path, '/', '_');
$aliases[$alias] = 'http://axschema.org/' . $path;
${$type}[] = $alias;
}
}
foreach ($aliases as $alias => $ns) {
$this->params['openid.ax.type.' . $alias] = $ns;
}
if ($required) {
$this->params['openid.ax.required'] = implode( ',', $required );
}
if ($optional) {
$this->params['openid.ax.if_available'] = implode( ',', $optional );
}
}
/**
* validate
*
* @return boolean
*/
public function validate() {
if ($this->getResponse( 'openid_user_setup_url' )) {
return false;
}
if ($this->getResponse( 'openid_mode' ) != 'id_res') {
return false;
}
if ($this->getResponse( 'openid_return_to' ) != $this->return_to) {
return false;
}
if (!$this->getResponse(('openid_claimed_id'))) {
return false;
}
$this->identity = $this->claimed_id = $this->normalizeURL( $this->getResponse( 'openid_claimed_id' ) );
/**
* check for association data in cache
*/
if ( ($association = $this->cache($this->getResponse('openid_op_endpoint'))) && ! $this->getResponse('openid_invalidate_handle') ) {
if (isset( $association['assoc_handle'], $association['mac_key'] )) {
/**
* The Claimed Identifier. "openid.claimed_id" and "openid.identity"
* SHALL be either both present or both absent.
*/
if ( !$this->getResponse('openid_claimed_id') && !$this->getResponse(('openid_identity')) ) {
return false;
}
/**
* Verify that openid_sig matches signed parameters in openid_signed
* This list MUST contain at least "op_endpoint", "return_to"
* "response_nonce" and "assoc_handle", and if present in the response,
* "claimed_id" and "identity".
*/
$must = array (
'op_endpoint',
'return_to',
'response_nonce',
'assoc_handle',
'claimed_id',
'identity'
);
$signed = explode( ',', $this->getResponse( 'openid_signed' ) );
/**
* verify that open_signed has the 'must' parameters
*/
if (count( array_intersect( $must, $signed ) ) !== count( $must )) {
return false;
}
/**
* This is for checking the nonce, when app is behind a load balancer
* it is simpler to store session on a DB and available for all the
* instances rather to the local file system. same logic could apply to
* the association cache
*/
if (! isset( $_SESSION )) {
session_start();
}
/**
* When the Relying Party checks the signature on an assertion, the
* Relying Party SHOULD ensure that an assertion has not yet been accepted
* with the same value for "openid.response_nonce" from the same
* OP Endpoint URL.
*
* @see 11.3. Checking the Nonce
*/
if (isset( $_SESSION['response_nonce'] ) && $_SESSION['response_nonce'] == $this->getResponse( 'openid_response_nonce' )) {
return false;
} else {
$_SESSION['response_nonce'] = $this->getResponse( 'openid_response_nonce' );
}
/**
* prepare fiels to sign
*
* @see 6. Generating Signatures
*/
$tokens = '';
foreach ($signed as $key) {
$tokens .= sprintf( "%s:%s\n", $key, $this->getResponse( 'openid_' . strtr( $key, '.', '_' ) ) );
}
/**
* @see 6.2. Signature Algorithms
*/
$signature = base64_encode( hash_hmac( 'sha256', $tokens, base64_decode($association['mac_key']), true ) );
/**
* check if signatures match
*
* @return boolean
*/
return $this->getResponse( 'openid_sig' ) === $signature;
}
} else {
/**
* clean openid.invalidate_handle
* by setting a cache with an expiry in the past (-1) should be enough
*/
$this->cache($this->getResponse('openid_op_endpoint'), true, -1);
/**
* Stateless 'dumb' mode needs to found again the OP Endpoint URL.
*/
$this->Discover();
/**
* @see 11.4.2.1. Request Parameters Exact copies of all fields from the
* authentication response, except for "openid.mode".
*/
$params = array ();
foreach ( $this->getResponse() as $key => $value ) {
/* replace _ with . openid.* */
$params[preg_replace( '#_#', '.', $key, 1 )] = $value;
}
$params['openid.mode'] = 'check_authentication';
$this->request( $this->provider, false, 'POST', $params );
return (isset( $this->headers['is_valid'] ) && $this->headers['is_valid'] == 'true') ? true : false;
}
return false;
}
/**
* associate
*
* The Relying Party and the OP establish an association -- a shared secret
* established using Diffie-Hellman Key Exchange [RFC2631].
*
* @see 8. Establishing Associations
*/
protected function associate() {
/**
* check if we have an association in the cache
* @return array Association
*/
if ($association = $this->cache($this->provider)) {
return $association;
}
$private_key = gmp_random(16);
$public_key = base64_encode($this->btwocEncode(gmp_strval(gmp_powm(self::OPENID_DH_GEN, $private_key, self::OPENID_DH_MODULUS))));
/**
* @see 8.1.1. Common Request Parameters
*/
$params = array (
'openid.ns' => self::OPENID_NS_2_0,
'openid.mode' => 'associate',
'openid.assoc_type' => 'HMAC-SHA256',
'openid.session_type' => 'DH-SHA256',
'openid.dh_consumer_public' => $public_key
);
if ($this->request( $this->provider, false, 'POST', $params )) {
if (isset( $this->headers['dh_server_public'], $this->headers['enc_mac_key'] )) {
$dh_server_public = base64_decode( $this->headers['dh_server_public'] );
$enc_mac_key = $this->headers['enc_mac_key'];
$ZZ = $this->btwocEncode(gmp_strval(gmp_powm($this->btwocDecode($dh_server_public), $private_key, self::OPENID_DH_MODULUS)));
/**
* decrypt & return the mac_key (shared secret)
*/
$secret = $this->openidXOR( hash( 'sha256', $ZZ, true ), base64_decode( $enc_mac_key ) );
/**
* store association in cache
*/
if ($this->cache( $this->provider, json_encode( array_merge( $this->headers, array( 'op_endpoint' => $this->provider, 'mac_key' => base64_encode($secret)) ) ), $this->headers['expires_in'] ) ) {
return array('assoc_handle' => $this->headers['assoc_handle']);
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
/**
* cache for associations
*/
protected function cache($openid_op_endpoint, $data = false, $expire = null) {
$cache_dir = defined('OPENID_CACHE_DIR') ? OPENID_CACHE_DIR : '/tmp/openid/';
if (!file_exists($cache_dir)) {
if (!mkdir($cache_dir, 0750, true)) {
trigger_error('ERROR -> ' . __METHOD__ . ": Cache - Cannot create dir: $cache_dir", E_USER_NOTICE);
return false;
}
}
$cache_file = "$cache_dir/" . sha1($openid_op_endpoint);
/**
* write to cache
*/
if ($data) {
if (!($fp = fopen($cache_file, 'w'))) {
trigger_error('ERROR -> ' . __METHOD__ . ": Cache - Cannot create cache file $cache_file", E_USER_NOTICE);
return false;
}
if (flock($fp, LOCK_EX) && ftruncate($fp, 0)) {
if (fwrite($fp, $data)) {
flock($fp, LOCK_UN);
fclose($fp);
chmod($cache_file, 0644);
$time = time() + ($expire ?: 3600);
touch($cache_file, $time);
return true;
} else {
return false;
}
} else {
trigger_error('ERROR -> ' . __METHOD__ . ": Cache Cannot lock/truncate the cache file: $cache_file", E_USER_NOTICE);
return false;
}
} else {
/**
* get association from cache
*/
$content = @file_get_contents($cache_file);
if ($content) {
$cache = json_decode($content, 1);
$time = time();
$cache_time = filemtime($cache_file);
$life = $cache_time - $time;
if ( $life > 0 && is_array($cache) ) {
return $cache;
} else {
@unlink($cache_file);
return false;
}
} else {
return false;
}
}
}
/**
* btwocEncode
*
* @see 4.2. Integer Representations
* @param int $n
* @return big-endian two's complement representation
*/
public function btwocEncode($n) {
$cmp = gmp_cmp( $n, 0 );
if ($cmp == 0) {
return "\x00";
}
$bytes = array ();
while ( gmp_cmp( $n, 0 ) > 0 ) {
array_unshift( $bytes, gmp_mod( $n, 256 ) );
$n = gmp_div( $n, pow( 2, 8 ) );
}
if ($bytes && ($bytes[0] > 127)) {
array_unshift( $bytes, 0 );
}
$string = '';
foreach ($bytes as $byte) {
$string .= pack( 'C', $byte );
}
return $string;
}
/**
* btwocDecode
*
* @see 4.2. Integer Representations
* @param string $str
* @return Base 10 number
*/
public function btwocDecode($str) {
$bytes = array_merge( unpack( 'C*', $str ) );
$n = 0;
foreach ($bytes as $byte) {
$n = gmp_mul( $n, pow( 2, 8 ) );
$n = gmp_add( $n, $byte );
}
return gmp_strval( $n );
}
/**
* openidXOR
*/
public function openidXOR($x, $y) {
$a = '';
for ($i = 0; $i < strlen( $y ); $i ++) {
$a .= $x[$i] ^ $y[$i];
}
return $a;
}
/**
* normalizeURL - parse a URI Reference with a Regular Expression
*
* @see rfc3986
* @return array
*/
public function normalizeURL($uri) {
$parts = array (
'scheme' => '',
'host' => '',
'port' => '',
'user' => '',
'pass' => '',
'path' => '',
'query' => '',
'fragment' => ''
);
preg_match( self::URI_REGEX, $uri, $matches );
if (array_key_exists( 2, $matches )) $parts['scheme'] = strtolower($matches[2]);
if (array_key_exists( 4, $matches )) $authority = $matches[4];
if (array_key_exists( 5, $matches )) $parts['path'] = $matches[5];
if (array_key_exists( 7, $matches )) $parts['query'] = $matches[7];
if (array_key_exists( 9, $matches )) $parts['fragment'] = $matches[9];
/* Extract username, password, host and port from authority */
preg_match('"(([^:@]*)(:([^:@]*))?@)?([^:]*)(:(.*))?"', $authority, $matches);
if (array_key_exists( 2, $matches )) $parts['user'] = $matches[2];
if (array_key_exists( 4, $matches )) $parts['pass'] = $matches[4];
if (array_key_exists( 5, $matches )) $parts['host'] = strtolower($matches[5]);
if (array_key_exists( 7, $matches )) $parts['port'] = $matches[7];
$url = $parts['scheme'] . '://' .
(empty( $parts['user'] ) ? '' : (empty( $parts['pass'] ) ? "{$parts['user']}@" : "{$parts['user']}:{$parts['pass']}@")) .
$parts['host'] .
(empty( $parts['port'] ) ? '' : ":{$parts['port']}") .
(empty( $parts['path'] ) ? '' : $parts['path']) .
(empty( $parts['query'] ) ? '' : "?{$parts['query']}") .
(empty( $parts['fragment'] ) ? '' : "#{$parts['fragment']}");
return $url;
}
/**
* getAxAttributes
*
* @version LightOpenID
* @return array
*/
public function getAxAttributes() {
$alias = null;
if ($this->getResponse('openid_ns_ax') && $this->getResponse('openid_ns_ax') != self::OPENID_AX) { // It's the most likely case, so we'll check it before
$alias = 'ax';
} else {
// 'ax' prefix is either undefined, or points to another extension,
// so we search for another prefix
foreach ( $this->getResponse() as $key => $val ) {
if (substr( $key, 0, strlen( 'openid_ns_' ) ) == 'openid_ns_' && $val == self::OPENID_AX) {
$alias = substr( $key, strlen( 'openid_ns_' ) );
break;
}
}
}
if (! $alias) {
// An alias for AX schema has not been found,