-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxmlseclibs.php
1664 lines (1646 loc) · 71.4 KB
/
xmlseclibs.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
/**
* xmlseclibs.php
*
* Copyright (c) 2007-2013, Robert Richards <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Robert Richards nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @author Robert Richards <[email protected]>
* @copyright 2007-2013 Robert Richards <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version 1.3.1
*/
/*
Functions to generate simple cases of Exclusive Canonical XML - Callable function is C14NGeneral()
i.e.: $canonical = C14NGeneral($domelement, TRUE);
*/
/* helper function */
function sortAndAddAttrs($element, $arAtts) {
$newAtts = array();
foreach ($arAtts AS $attnode) {
$newAtts[$attnode->nodeName] = $attnode;
}
ksort($newAtts);
foreach ($newAtts as $attnode) {
$element->setAttribute($attnode->nodeName, $attnode->nodeValue);
}
}
/* helper function */
function canonical($tree, $element, $withcomments) {
if ($tree->nodeType != XML_DOCUMENT_NODE) {
$dom = $tree->ownerDocument;
} else {
$dom = $tree;
}
if ($element->nodeType != XML_ELEMENT_NODE) {
if ($element->nodeType == XML_DOCUMENT_NODE) {
foreach ($element->childNodes AS $node) {
canonical($dom, $node, $withcomments);
}
return;
}
if ($element->nodeType == XML_COMMENT_NODE && ! $withcomments) {
return;
}
$tree->appendChild($dom->importNode($element, TRUE));
return;
}
$arNS = array();
if ($element->namespaceURI != "") {
if ($element->prefix == "") {
$elCopy = $dom->createElementNS($element->namespaceURI, $element->nodeName);
} else {
$prefix = $tree->lookupPrefix($element->namespaceURI);
if ($prefix == $element->prefix) {
$elCopy = $dom->createElementNS($element->namespaceURI, $element->nodeName);
} else {
$elCopy = $dom->createElement($element->nodeName);
$arNS[$element->namespaceURI] = $element->prefix;
}
}
} else {
$elCopy = $dom->createElement($element->nodeName);
}
$tree->appendChild($elCopy);
/* Create DOMXPath based on original document */
$xPath = new DOMXPath($element->ownerDocument);
/* Get namespaced attributes */
$arAtts = $xPath->query('attribute::*[namespace-uri(.) != ""]', $element);
/* Create an array with namespace URIs as keys, and sort them */
foreach ($arAtts AS $attnode) {
if (array_key_exists($attnode->namespaceURI, $arNS) &&
($arNS[$attnode->namespaceURI] == $attnode->prefix)) {
continue;
}
$prefix = $tree->lookupPrefix($attnode->namespaceURI);
if ($prefix != $attnode->prefix) {
$arNS[$attnode->namespaceURI] = $attnode->prefix;
} else {
$arNS[$attnode->namespaceURI] = NULL;
}
}
if (count($arNS) > 0) {
asort($arNS);
}
/* Add namespace nodes */
foreach ($arNS AS $namespaceURI=>$prefix) {
if ($prefix != NULL) {
$elCopy->setAttributeNS("http://www.w3.org/2000/xmlns/",
"xmlns:".$prefix, $namespaceURI);
}
}
if (count($arNS) > 0) {
ksort($arNS);
}
/* Get attributes not in a namespace, and then sort and add them */
$arAtts = $xPath->query('attribute::*[namespace-uri(.) = ""]', $element);
sortAndAddAttrs($elCopy, $arAtts);
/* Loop through the URIs, and then sort and add attributes within that namespace */
foreach ($arNS as $nsURI=>$prefix) {
$arAtts = $xPath->query('attribute::*[namespace-uri(.) = "'.$nsURI.'"]', $element);
sortAndAddAttrs($elCopy, $arAtts);
}
foreach ($element->childNodes AS $node) {
canonical($elCopy, $node, $withcomments);
}
}
/*
$element - DOMElement for which to produce the canonical version of
$exclusive - boolean to indicate exclusive canonicalization (must pass TRUE)
$withcomments - boolean indicating wether or not to include comments in canonicalized form
*/
function C14NGeneral($element, $exclusive=FALSE, $withcomments=FALSE) {
/* IF PHP 5.2+ then use built in canonical functionality */
$php_version = explode('.', PHP_VERSION);
if (($php_version[0] > 5) || ($php_version[0] == 5 && $php_version[1] >= 2) ) {
return $element->C14N($exclusive, $withcomments);
}
/* Must be element or document */
if (! $element instanceof DOMElement && ! $element instanceof DOMDocument) {
return NULL;
}
/* Currently only exclusive XML is supported */
if ($exclusive == FALSE) {
throw new Exception("Only exclusive canonicalization is supported in this version of PHP");
}
$copyDoc = new DOMDocument();
canonical($copyDoc, $element, $withcomments);
return $copyDoc->saveXML($copyDoc->documentElement, LIBXML_NOEMPTYTAG);
}
class XMLSecurityKey {
const TRIPLEDES_CBC = 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc';
const AES128_CBC = 'http://www.w3.org/2001/04/xmlenc#aes128-cbc';
const AES192_CBC = 'http://www.w3.org/2001/04/xmlenc#aes192-cbc';
const AES256_CBC = 'http://www.w3.org/2001/04/xmlenc#aes256-cbc';
const RSA_1_5 = 'http://www.w3.org/2001/04/xmlenc#rsa-1_5';
const RSA_OAEP_MGF1P = 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p';
const DSA_SHA1 = 'http://www.w3.org/2000/09/xmldsig#dsa-sha1';
const RSA_SHA1 = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1';
const RSA_SHA256 = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256';
const RSA_SHA384 = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha384';
const RSA_SHA512 = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512';
private $cryptParams = array();
public $type = 0;
public $key = NULL;
public $passphrase = "";
public $iv = NULL;
public $name = NULL;
public $keyChain = NULL;
public $isEncrypted = FALSE;
public $encryptedCtx = NULL;
public $guid = NULL;
/**
* This variable contains the certificate as a string if this key represents an X509-certificate.
* If this key doesn't represent a certificate, this will be NULL.
*/
private $x509Certificate = NULL;
/* This variable contains the certificate thunbprint if we have loaded an X509-certificate. */
private $X509Thumbprint = NULL;
public function __construct($type, $params=NULL) {
srand();
switch ($type) {
case (XMLSecurityKey::TRIPLEDES_CBC):
$this->cryptParams['library'] = 'mcrypt';
$this->cryptParams['cipher'] = MCRYPT_TRIPLEDES;
$this->cryptParams['mode'] = MCRYPT_MODE_CBC;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc';
$this->cryptParams['keysize'] = 24;
break;
case (XMLSecurityKey::AES128_CBC):
$this->cryptParams['library'] = 'mcrypt';
$this->cryptParams['cipher'] = MCRYPT_RIJNDAEL_128;
$this->cryptParams['mode'] = MCRYPT_MODE_CBC;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#aes128-cbc';
$this->cryptParams['keysize'] = 16;
break;
case (XMLSecurityKey::AES192_CBC):
$this->cryptParams['library'] = 'mcrypt';
$this->cryptParams['cipher'] = MCRYPT_RIJNDAEL_128;
$this->cryptParams['mode'] = MCRYPT_MODE_CBC;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#aes192-cbc';
$this->cryptParams['keysize'] = 24;
break;
case (XMLSecurityKey::AES256_CBC):
$this->cryptParams['library'] = 'mcrypt';
$this->cryptParams['cipher'] = MCRYPT_RIJNDAEL_128;
$this->cryptParams['mode'] = MCRYPT_MODE_CBC;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#aes256-cbc';
$this->cryptParams['keysize'] = 32;
break;
case (XMLSecurityKey::RSA_1_5):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#rsa-1_5';
if (is_array($params) && ! empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
return;
case (XMLSecurityKey::RSA_OAEP_MGF1P):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['padding'] = OPENSSL_PKCS1_OAEP_PADDING;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p';
$this->cryptParams['hash'] = NULL;
if (is_array($params) && ! empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
return;
case (XMLSecurityKey::RSA_SHA1):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['method'] = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
if (is_array($params) && ! empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
break;
case (XMLSecurityKey::RSA_SHA256):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
$this->cryptParams['digest'] = 'SHA256';
if (is_array($params) && ! empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
break;
case (XMLSecurityKey::RSA_SHA384):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha384';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
$this->cryptParams['digest'] = 'SHA384';
if (is_array($params) && ! empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
case (XMLSecurityKey::RSA_SHA512):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
$this->cryptParams['digest'] = 'SHA512';
if (is_array($params) && ! empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
default:
throw new Exception('Invalid Key Type');
return;
}
$this->type = $type;
}
/**
* Retrieve the key size for the symmetric encryption algorithm..
*
* If the key size is unknown, or this isn't a symmetric encryption algorithm,
* NULL is returned.
*
* @return int|NULL The number of bytes in the key.
*/
public function getSymmetricKeySize() {
if (! isset($this->cryptParams['keysize'])) {
return NULL;
}
return $this->cryptParams['keysize'];
}
public function generateSessionKey() {
if (!isset($this->cryptParams['keysize'])) {
throw new Exception('Unknown key size for type "' . $this->type . '".');
}
$keysize = $this->cryptParams['keysize'];
if (function_exists('openssl_random_pseudo_bytes')) {
/* We have PHP >= 5.3 - use openssl to generate session key. */
$key = openssl_random_pseudo_bytes($keysize);
} else {
/* Generating random key using iv generation routines */
$key = mcrypt_create_iv($keysize, MCRYPT_RAND);
}
if ($this->type === XMLSecurityKey::TRIPLEDES_CBC) {
/* Make sure that the generated key has the proper parity bits set.
* Mcrypt doesn't care about the parity bits, but others may care.
*/
for ($i = 0; $i < strlen($key); $i++) {
$byte = ord($key[$i]) & 0xfe;
$parity = 1;
for ($j = 1; $j < 8; $j++) {
$parity ^= ($byte >> $j) & 1;
}
$byte |= $parity;
$key[$i] = chr($byte);
}
}
$this->key = $key;
return $key;
}
public static function getRawThumbprint($cert) {
$arCert = explode("\n", $cert);
$data = '';
$inData = FALSE;
foreach ($arCert AS $curData) {
if (! $inData) {
if (strncmp($curData, '-----BEGIN CERTIFICATE', 22) == 0) {
$inData = TRUE;
}
} else {
if (strncmp($curData, '-----END CERTIFICATE', 20) == 0) {
$inData = FALSE;
break;
}
$data .= trim($curData);
}
}
if (! empty($data)) {
return strtolower(sha1(base64_decode($data)));
}
return NULL;
}
public function loadKey($key, $isFile=FALSE, $isCert = FALSE) {
if ($isFile) {
$this->key = file_get_contents($key);
} else {
$this->key = $key;
}
if ($isCert) {
$this->key = openssl_x509_read($this->key);
openssl_x509_export($this->key, $str_cert);
$this->x509Certificate = $str_cert;
$this->key = $str_cert;
} else {
$this->x509Certificate = NULL;
}
if ($this->cryptParams['library'] == 'openssl') {
if ($this->cryptParams['type'] == 'public') {
if ($isCert) {
/* Load the thumbprint if this is an X509 certificate. */
$this->X509Thumbprint = self::getRawThumbprint($this->key);
}
$this->key = openssl_get_publickey($this->key);
} else {
$this->key = openssl_get_privatekey($this->key, $this->passphrase);
}
} else if ($this->cryptParams['cipher'] == MCRYPT_RIJNDAEL_128) {
/* Check key length */
switch ($this->type) {
case (XMLSecurityKey::AES256_CBC):
if (strlen($this->key) < 25) {
throw new Exception('Key must contain at least 25 characters for this cipher');
}
break;
case (XMLSecurityKey::AES192_CBC):
if (strlen($this->key) < 17) {
throw new Exception('Key must contain at least 17 characters for this cipher');
}
break;
}
}
}
private function encryptMcrypt($data) {
$td = mcrypt_module_open($this->cryptParams['cipher'], '', $this->cryptParams['mode'], '');
$this->iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $this->key, $this->iv);
if ($this->cryptParams['mode'] == MCRYPT_MODE_CBC) {
$bs = mcrypt_enc_get_block_size($td);
for ($datalen0=$datalen=strlen($data); (($datalen%$bs)!=($bs-1)); $datalen++)
$data.=chr(rand(1, 127));
$data.=chr($datalen-$datalen0+1);
}
$encrypted_data = $this->iv.mcrypt_generic($td, $data);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $encrypted_data;
}
private function decryptMcrypt($data) {
$td = mcrypt_module_open($this->cryptParams['cipher'], '', $this->cryptParams['mode'], '');
$iv_length = mcrypt_enc_get_iv_size($td);
$this->iv = substr($data, 0, $iv_length);
$data = substr($data, $iv_length);
mcrypt_generic_init($td, $this->key, $this->iv);
$decrypted_data = mdecrypt_generic($td, $data);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
if ($this->cryptParams['mode'] == MCRYPT_MODE_CBC) {
$dataLen = strlen($decrypted_data);
$paddingLength = substr($decrypted_data, $dataLen - 1, 1);
$decrypted_data = substr($decrypted_data, 0, $dataLen - ord($paddingLength));
}
return $decrypted_data;
}
private function encryptOpenSSL($data) {
if ($this->cryptParams['type'] == 'public') {
if (! openssl_public_encrypt($data, $encrypted_data, $this->key, $this->cryptParams['padding'])) {
throw new Exception('Failure encrypting Data');
return;
}
} else {
if (! openssl_private_encrypt($data, $encrypted_data, $this->key, $this->cryptParams['padding'])) {
throw new Exception('Failure encrypting Data');
return;
}
}
return $encrypted_data;
}
private function decryptOpenSSL($data) {
if ($this->cryptParams['type'] == 'public') {
if (! openssl_public_decrypt($data, $decrypted, $this->key, $this->cryptParams['padding'])) {
throw new Exception('Failure decrypting Data');
return;
}
} else {
if (! openssl_private_decrypt($data, $decrypted, $this->key, $this->cryptParams['padding'])) {
throw new Exception('Failure decrypting Data');
return;
}
}
return $decrypted;
}
private function signOpenSSL($data) {
$algo = OPENSSL_ALGO_SHA1;
if (! empty($this->cryptParams['digest'])) {
$algo = $this->cryptParams['digest'];
}
if (! openssl_sign ($data, $signature, $this->key, $algo)) {
throw new Exception('Failure Signing Data: ' . openssl_error_string() . ' - ' . $algo);
return;
}
return $signature;
}
private function verifyOpenSSL($data, $signature) {
$algo = OPENSSL_ALGO_SHA1;
if (! empty($this->cryptParams['digest'])) {
$algo = $this->cryptParams['digest'];
}
return openssl_verify ($data, $signature, $this->key, $algo);
}
public function encryptData($data) {
switch ($this->cryptParams['library']) {
case 'mcrypt':
return $this->encryptMcrypt($data);
break;
case 'openssl':
return $this->encryptOpenSSL($data);
break;
}
}
public function decryptData($data) {
switch ($this->cryptParams['library']) {
case 'mcrypt':
return $this->decryptMcrypt($data);
break;
case 'openssl':
return $this->decryptOpenSSL($data);
break;
}
}
public function signData($data) {
switch ($this->cryptParams['library']) {
case 'openssl':
return $this->signOpenSSL($data);
break;
}
}
public function verifySignature($data, $signature) {
switch ($this->cryptParams['library']) {
case 'openssl':
return $this->verifyOpenSSL($data, $signature);
break;
}
}
public function getAlgorith() {
return $this->cryptParams['method'];
}
static function makeAsnSegment($type, $string) {
switch ($type){
case 0x02:
if (ord($string) > 0x7f)
$string = chr(0).$string;
break;
case 0x03:
$string = chr(0).$string;
break;
}
$length = strlen($string);
if ($length < 128){
$output = sprintf("%c%c%s", $type, $length, $string);
} else if ($length < 0x0100){
$output = sprintf("%c%c%c%s", $type, 0x81, $length, $string);
} else if ($length < 0x010000) {
$output = sprintf("%c%c%c%c%s", $type, 0x82, $length/0x0100, $length%0x0100, $string);
} else {
$output = NULL;
}
return($output);
}
/* Modulus and Exponent must already be base64 decoded */
static function convertRSA($modulus, $exponent) {
/* make an ASN publicKeyInfo */
$exponentEncoding = XMLSecurityKey::makeAsnSegment(0x02, $exponent);
$modulusEncoding = XMLSecurityKey::makeAsnSegment(0x02, $modulus);
$sequenceEncoding = XMLSecurityKey:: makeAsnSegment(0x30, $modulusEncoding.$exponentEncoding);
$bitstringEncoding = XMLSecurityKey::makeAsnSegment(0x03, $sequenceEncoding);
$rsaAlgorithmIdentifier = pack("H*", "300D06092A864886F70D0101010500");
$publicKeyInfo = XMLSecurityKey::makeAsnSegment (0x30, $rsaAlgorithmIdentifier.$bitstringEncoding);
/* encode the publicKeyInfo in base64 and add PEM brackets */
$publicKeyInfoBase64 = base64_encode($publicKeyInfo);
$encoding = "-----BEGIN PUBLIC KEY-----\n";
$offset = 0;
while ($segment=substr($publicKeyInfoBase64, $offset, 64)){
$encoding = $encoding.$segment."\n";
$offset += 64;
}
return $encoding."-----END PUBLIC KEY-----\n";
}
public function serializeKey($parent) {
}
/**
* Retrieve the X509 certificate this key represents.
*
* Will return the X509 certificate in PEM-format if this key represents
* an X509 certificate.
*
* @return The X509 certificate or NULL if this key doesn't represent an X509-certificate.
*/
public function getX509Certificate() {
return $this->x509Certificate;
}
/* Get the thumbprint of this X509 certificate.
*
* Returns:
* The thumbprint as a lowercase 40-character hexadecimal number, or NULL
* if this isn't a X509 certificate.
*/
public function getX509Thumbprint() {
return $this->X509Thumbprint;
}
/**
* Create key from an EncryptedKey-element.
*
* @param DOMElement $element The EncryptedKey-element.
* @return XMLSecurityKey The new key.
*/
public static function fromEncryptedKeyElement(DOMElement $element) {
$objenc = new XMLSecEnc();
$objenc->setNode($element);
if (! $objKey = $objenc->locateKey()) {
throw new Exception("Unable to locate algorithm for this Encrypted Key");
}
$objKey->isEncrypted = TRUE;
$objKey->encryptedCtx = $objenc;
XMLSecEnc::staticLocateKeyInfo($objKey, $element);
return $objKey;
}
}
class XMLSecurityDSig {
const XMLDSIGNS = 'http://www.w3.org/2000/09/xmldsig#';
const SHA1 = 'http://www.w3.org/2000/09/xmldsig#sha1';
const SHA256 = 'http://www.w3.org/2001/04/xmlenc#sha256';
const SHA384 = 'http://www.w3.org/2001/04/xmldsig-more#sha384';
const SHA512 = 'http://www.w3.org/2001/04/xmlenc#sha512';
const RIPEMD160 = 'http://www.w3.org/2001/04/xmlenc#ripemd160';
const C14N = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
const C14N_COMMENTS = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments';
const EXC_C14N = 'http://www.w3.org/2001/10/xml-exc-c14n#';
const EXC_C14N_COMMENTS = 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments';
const template = '<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:SignatureMethod />
</ds:SignedInfo>
</ds:Signature>';
public $sigNode = NULL;
public $idKeys = array();
public $idNS = array();
private $signedInfo = NULL;
private $xPathCtx = NULL;
private $canonicalMethod = NULL;
private $prefix = 'ds';
private $searchpfx = 'secdsig';
/* This variable contains an associative array of validated nodes. */
private $validatedNodes = NULL;
public function __construct() {
$sigdoc = new DOMDocument();
$sigdoc->loadXML(XMLSecurityDSig::template);
$this->sigNode = $sigdoc->documentElement;
}
private function resetXPathObj() {
$this->xPathCtx = NULL;
}
private function getXPathObj() {
if (empty($this->xPathCtx) && ! empty($this->sigNode)) {
$xpath = new DOMXPath($this->sigNode->ownerDocument);
$xpath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS);
$this->xPathCtx = $xpath;
}
return $this->xPathCtx;
}
static function generate_GUID($prefix='pfx') {
$uuid = md5(uniqid(rand(), true));
$guid = $prefix.substr($uuid,0,8)."-".
substr($uuid,8,4)."-".
substr($uuid,12,4)."-".
substr($uuid,16,4)."-".
substr($uuid,20,12);
return $guid;
}
public function locateSignature($objDoc) {
if ($objDoc instanceof DOMDocument) {
$doc = $objDoc;
} else {
$doc = $objDoc->ownerDocument;
}
if ($doc) {
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS);
$query = ".//secdsig:Signature";
$nodeset = $xpath->query($query, $objDoc);
$this->sigNode = $nodeset->item(0);
return $this->sigNode;
}
return NULL;
}
public function createNewSignNode($name, $value=NULL) {
$doc = $this->sigNode->ownerDocument;
if (! is_null($value)) {
$node = $doc->createElementNS(XMLSecurityDSig::XMLDSIGNS, $this->prefix.':'.$name, $value);
} else {
$node = $doc->createElementNS(XMLSecurityDSig::XMLDSIGNS, $this->prefix.':'.$name);
}
return $node;
}
public function setCanonicalMethod($method) {
switch ($method) {
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315':
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments':
case 'http://www.w3.org/2001/10/xml-exc-c14n#':
case 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments':
$this->canonicalMethod = $method;
break;
default:
throw new Exception('Invalid Canonical Method');
}
if ($xpath = $this->getXPathObj()) {
$query = './'.$this->searchpfx.':SignedInfo';
$nodeset = $xpath->query($query, $this->sigNode);
if ($sinfo = $nodeset->item(0)) {
$query = './'.$this->searchpfx.'CanonicalizationMethod';
$nodeset = $xpath->query($query, $sinfo);
if (! ($canonNode = $nodeset->item(0))) {
$canonNode = $this->createNewSignNode('CanonicalizationMethod');
$sinfo->insertBefore($canonNode, $sinfo->firstChild);
}
$canonNode->setAttribute('Algorithm', $this->canonicalMethod);
}
}
}
private function canonicalizeData($node, $canonicalmethod, $arXPath=NULL, $prefixList=NULL) {
$exclusive = FALSE;
$withComments = FALSE;
switch ($canonicalmethod) {
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315':
$exclusive = FALSE;
$withComments = FALSE;
break;
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments':
$withComments = TRUE;
break;
case 'http://www.w3.org/2001/10/xml-exc-c14n#':
$exclusive = TRUE;
break;
case 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments':
$exclusive = TRUE;
$withComments = TRUE;
break;
}
/* Support PHP versions < 5.2 not containing C14N methods in DOM extension */
$php_version = explode('.', PHP_VERSION);
if (($php_version[0] < 5) || ($php_version[0] == 5 && $php_version[1] < 2) ) {
if (! is_null($arXPath)) {
throw new Exception("PHP 5.2.0 or higher is required to perform XPath Transformations");
}
return C14NGeneral($node, $exclusive, $withComments);
}
return $node->C14N($exclusive, $withComments, $arXPath, $prefixList);
}
public function canonicalizeSignedInfo() {
$doc = $this->sigNode->ownerDocument;
$canonicalmethod = NULL;
if ($doc) {
$xpath = $this->getXPathObj();
$query = "./secdsig:SignedInfo";
$nodeset = $xpath->query($query, $this->sigNode);
if ($signInfoNode = $nodeset->item(0)) {
$query = "./secdsig:CanonicalizationMethod";
$nodeset = $xpath->query($query, $signInfoNode);
if ($canonNode = $nodeset->item(0)) {
$canonicalmethod = $canonNode->getAttribute('Algorithm');
}
$this->signedInfo = $this->canonicalizeData($signInfoNode, $canonicalmethod);
return $this->signedInfo;
}
}
return NULL;
}
public function calculateDigest ($digestAlgorithm, $data) {
switch ($digestAlgorithm) {
case XMLSecurityDSig::SHA1:
$alg = 'sha1';
break;
case XMLSecurityDSig::SHA256:
$alg = 'sha256';
break;
case XMLSecurityDSig::SHA384:
$alg = 'sha384';
break;
case XMLSecurityDSig::SHA512:
$alg = 'sha512';
break;
case XMLSecurityDSig::RIPEMD160:
$alg = 'ripemd160';
break;
default:
throw new Exception("Cannot validate digest: Unsupported Algorith <$digestAlgorithm>");
}
if (function_exists('hash')) {
return base64_encode(hash($alg, $data, TRUE));
} elseif (function_exists('mhash')) {
$alg = "MHASH_" . strtoupper($alg);
return base64_encode(mhash(constant($alg), $data));
} elseif ($alg === 'sha1') {
return base64_encode(sha1($data, TRUE));
} else {
throw new Exception('xmlseclibs is unable to calculate a digest. Maybe you need the mhash library?');
}
}
public function validateDigest($refNode, $data) {
$xpath = new DOMXPath($refNode->ownerDocument);
$xpath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS);
$query = 'string(./secdsig:DigestMethod/@Algorithm)';
$digestAlgorithm = $xpath->evaluate($query, $refNode);
$digValue = $this->calculateDigest($digestAlgorithm, $data);
$query = 'string(./secdsig:DigestValue)';
$digestValue = $xpath->evaluate($query, $refNode);
return ($digValue == $digestValue);
}
public function processTransforms($refNode, $objData, $includeCommentNodes = TRUE) {
$data = $objData;
$xpath = new DOMXPath($refNode->ownerDocument);
$xpath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS);
$query = './secdsig:Transforms/secdsig:Transform';
$nodelist = $xpath->query($query, $refNode);
$canonicalMethod = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
$arXPath = NULL;
$prefixList = NULL;
foreach ($nodelist AS $transform) {
$algorithm = $transform->getAttribute("Algorithm");
switch ($algorithm) {
case 'http://www.w3.org/2001/10/xml-exc-c14n#':
case 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments':
if(!$includeCommentNodes) {
/* We remove comment nodes by forcing it to use a canonicalization
* without comments.
*/
$canonicalMethod = 'http://www.w3.org/2001/10/xml-exc-c14n#';
} else {
$canonicalMethod = $algorithm;
}
$node = $transform->firstChild;
while ($node) {
if ($node->localName == 'InclusiveNamespaces') {
if ($pfx = $node->getAttribute('PrefixList')) {
$arpfx = array();
$pfxlist = explode(" ", $pfx);
foreach ($pfxlist AS $pfx) {
$val = trim($pfx);
if (! empty($val)) {
$arpfx[] = $val;
}
}
if (count($arpfx) > 0) {
$prefixList = $arpfx;
}
}
break;
}
$node = $node->nextSibling;
}
break;
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315':
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments':
if(!$includeCommentNodes) {
/* We remove comment nodes by forcing it to use a canonicalization
* without comments.
*/
$canonicalMethod = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
} else {
$canonicalMethod = $algorithm;
}
break;
case 'http://www.w3.org/TR/1999/REC-xpath-19991116':
$node = $transform->firstChild;
while ($node) {
if ($node->localName == 'XPath') {
$arXPath = array();
$arXPath['query'] = '(.//. | .//@* | .//namespace::*)['.$node->nodeValue.']';
$arXpath['namespaces'] = array();
$nslist = $xpath->query('./namespace::*', $node);
foreach ($nslist AS $nsnode) {
if ($nsnode->localName != "xml") {
$arXPath['namespaces'][$nsnode->localName] = $nsnode->nodeValue;
}
}
break;
}
$node = $node->nextSibling;
}
break;
}
}
if ($data instanceof DOMNode) {
$data = $this->canonicalizeData($objData, $canonicalMethod, $arXPath, $prefixList);
}
return $data;
}
public function processRefNode($refNode) {
$dataObject = NULL;
/*
* Depending on the URI, we may not want to include comments in the result
* See: http://www.w3.org/TR/xmldsig-core/#sec-ReferenceProcessingModel
*/
$includeCommentNodes = TRUE;
if ($uri = $refNode->getAttribute("URI")) {
$arUrl = parse_url($uri);
if (empty($arUrl['path'])) {
if ($identifier = $arUrl['fragment']) {
/* This reference identifies a node with the given id by using
* a URI on the form "#identifier". This should not include comments.
*/
$includeCommentNodes = FALSE;
$xPath = new DOMXPath($refNode->ownerDocument);
if ($this->idNS && is_array($this->idNS)) {
foreach ($this->idNS AS $nspf=>$ns) {
$xPath->registerNamespace($nspf, $ns);
}
}
$iDlist = '@Id="'.$identifier.'"';
if (is_array($this->idKeys)) {
foreach ($this->idKeys AS $idKey) {
$iDlist .= " or @$idKey='$identifier'";
}
}
$query = '//*['.$iDlist.']';
$dataObject = $xPath->query($query)->item(0);
} else {
$dataObject = $refNode->ownerDocument;
}
} else {
$dataObject = file_get_contents($arUrl);
}
} else {
/* This reference identifies the root node with an empty URI. This should
* not include comments.
*/
$includeCommentNodes = FALSE;
$dataObject = $refNode->ownerDocument;
}
$data = $this->processTransforms($refNode, $dataObject, $includeCommentNodes);
if (!$this->validateDigest($refNode, $data)) {
return FALSE;
}
if ($dataObject instanceof DOMNode) {
/* Add this node to the list of validated nodes. */
if(! empty($identifier)) {
$this->validatedNodes[$identifier] = $dataObject;
} else {
$this->validatedNodes[] = $dataObject;
}
}
return TRUE;
}
public function getRefNodeID($refNode) {
if ($uri = $refNode->getAttribute("URI")) {
$arUrl = parse_url($uri);
if (empty($arUrl['path'])) {
if ($identifier = $arUrl['fragment']) {
return $identifier;
}
}
}
return null;
}
public function getRefIDs() {
$refids = array();
$doc = $this->sigNode->ownerDocument;
$xpath = $this->getXPathObj();
$query = "./secdsig:SignedInfo/secdsig:Reference";
$nodeset = $xpath->query($query, $this->sigNode);
if ($nodeset->length == 0) {
throw new Exception("Reference nodes not found");
}
foreach ($nodeset AS $refNode) {
$refids[] = $this->getRefNodeID($refNode);
}
return $refids;
}
public function validateReference() {
$doc = $this->sigNode->ownerDocument;
if (! $doc->isSameNode($this->sigNode)) {
$this->sigNode->parentNode->removeChild($this->sigNode);
}
$xpath = $this->getXPathObj();
$query = "./secdsig:SignedInfo/secdsig:Reference";
$nodeset = $xpath->query($query, $this->sigNode);
if ($nodeset->length == 0) {
throw new Exception("Reference nodes not found");
}
/* Initialize/reset the list of validated nodes. */
$this->validatedNodes = array();
foreach ($nodeset AS $refNode) {
if (! $this->processRefNode($refNode)) {
/* Clear the list of validated nodes. */
$this->validatedNodes = NULL;
throw new Exception("Reference validation failed");
}
}
return TRUE;
}
private function addRefInternal($sinfoNode, $node, $algorithm, $arTransforms=NULL, $options=NULL) {
$prefix = NULL;
$prefix_ns = NULL;
$id_name = 'Id';
$overwrite_id = TRUE;
$force_uri = FALSE;
if (is_array($options)) {
$prefix = empty($options['prefix'])?NULL:$options['prefix'];
$prefix_ns = empty($options['prefix_ns'])?NULL:$options['prefix_ns'];
$id_name = empty($options['id_name'])?'Id':$options['id_name'];
$overwrite_id = !isset($options['overwrite'])?TRUE:(bool)$options['overwrite'];
$force_uri = !isset($options['force_uri'])?FALSE:(bool)$options['force_uri'];
}
$attname = $id_name;
if (! empty($prefix)) {
$attname = $prefix.':'.$attname;
}
$refNode = $this->createNewSignNode('Reference');
$sinfoNode->appendChild($refNode);
if (! $node instanceof DOMDocument) {
$uri = NULL;
if (! $overwrite_id) {
$uri = $node->getAttributeNS($prefix_ns, $id_name);
}