-
Notifications
You must be signed in to change notification settings - Fork 2
/
Sig.pm
1390 lines (1149 loc) · 42.1 KB
/
Sig.pm
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
package XML::Sig;
use strict;
use warnings;
=head1 NAME
XML::Sig - A toolkit to help sign and verify XML Digital Signatures.
=head1 SYNOPSIS
my $xml = '<foo ID="abc">123</foo>';
my $signer = XML::Sig->new({
key => 'path/to/private.key',
});
# create a signature
my $signed = $signer->sign($xml);
print "Signed XML: $signed\n";
# verify a signature
$signer->verify($signed)
or die "Signature Invalid.";
print "Signature valid.\n";
=head1 DESCRIPTION
This perl module provides two primary capabilities: given an XML string, create
and insert digital signatures, or if one is already present in the string verify
it -- all in accordance with the W3C standard governing XML signatures.
=cut
# use 'our' on v5.6.0
use vars qw($VERSION @EXPORT_OK %EXPORT_TAGS $DEBUG);
$DEBUG = 0;
$VERSION = '0.34';
use base qw(Class::Accessor);
XML::Sig->mk_accessors(qw(key));
# We are exporting functions
use base qw/Exporter/;
# Export list - to allow fine tuning of export table
@EXPORT_OK = qw( sign verify );
=head1 PREREQUISITES
=over
=item L<Digest::SHA>
=item L<XML::LibXML>
=item L<MIME::Base64>
=item L<Crypt::OpenSSL::X509>
=item L<Crypt::OpenSSL::Bignum>
=item L<Crypt::OpenSSL::RSA>
=item L<Crypt::OpenSSL::DSA>
=back
=cut
use Digest::SHA qw(sha1 sha224 sha256 sha384 sha512);
use XML::LibXML;
use MIME::Base64;
use Carp;
=head1 USAGE
=head2 SUPPORTED ALGORITHMS & TRANSFORMS
This module supports the following signature methods:
=over
=item DSA
=item RSA
=item RSA encoded as x509
=back
This module supports the following canonicalization methods and transforms:
=over
=item Enveloped Signature
=item REC-xml-c14n-20010315#
=item REC-xml-c14n-20010315#WithComments
=item REC-xml-c14n11-20080502
=item REC-xml-c14n11-20080502#WithComments
=item xml-exc-c14n#
=item xml-exc-c14n#WithComments
=back
=cut
use constant TRANSFORM_ENV_SIG => 'http://www.w3.org/2000/09/xmldsig#enveloped-signature';
use constant TRANSFORM_C14N => 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#';
use constant TRANSFORM_C14N_COMMENTS => 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments';
use constant TRANSFORM_C14N_V1_1 => 'http://www.w3.org/TR/2008/REC-xml-c14n11-20080502';
use constant TRANSFORM_C14N_V1_1_COMMENTS => 'http://www.w3.org/TR/2008/REC-xml-c14n11-20080502#WithComments';
use constant TRANSFORM_EXC_C14N => 'http://www.w3.org/2001/10/xml-exc-c14n#';
use constant TRANSFORM_EXC_C14N_COMMENTS => 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments';
sub DESTROY { }
$SIG{INT} = sub { die "Interrupted\n"; };
$| = 1; # autoflush
=head2 OPTIONS
Each of the following options are also accessors on the main
XML::Sig object. TODO Not strictly correct rewrite
=over
=item B<key>
The path to a file containing the contents of a private key. This option
is used only when generating signatures.
=item B<cert>
The path to a file containing a PEM-formatted X509 certificate. This
option is used only when generating signatures with the "x509"
option. This certificate will be embedded in the signed document, and
should match the private key used for the signature.
=item B<cert_text>
A string containing a PEM-formatted X509 certificate. This
option is used only when generating signatures with the "x509"
option. This certificate will be embedded in the signed document, and
should match the private key used for the signature.
=item B<x509>
Takes a true (1) or false (0) value and indicates how you want the
signature to be encoded. When true, the X509 certificate supplied will
be encoded in the signature. Otherwise the native encoding format for
RSA and DSA will be used.
=back
=head2 METHODS
=head3 B<new(...)>
Constructor; see OPTIONS above.
=cut
sub new {
my $class = shift;
my $params = shift;
my $self = {};
foreach my $prop ( qw/ key cert cert_text / ) {
if ( exists $params->{ $prop } ) {
$self->{ $prop } = $params->{ $prop };
}
# else {
# confess "You need to provide the $prop parameter!";
# }
}
bless $self, $class;
$self->{ 'x509' } = exists $params->{ x509 } ? 1 : 0;
if ( exists $params->{ 'key' } ) {
$self->_load_key( $params->{ 'key' } );
}
if ( exists $params->{ 'cert' } ) {
$self->_load_cert_file( $params->{ 'cert' } );
}
if ( exists $params->{ 'cert_text' } ) {
$self->_load_cert_text( $params->{ 'cert_text' } );
}
return $self;
}
=head3 B<sign($xml)>
When given a string of XML, it will return the same string with a signature
generated from the key provided when the XML::Sig object was initialized.
This method will sign all elements in your XML with an ID (case sensitive)
attribute. Each element with an ID attribute will be the basis for a seperate
signature. It will correspond to the URI attribute in the Reference element
that will be contained by the signature. If no ID attribute can be found on
an element, the signature will not be created.
The elements are signed in reverse order currently assuming (possibly
incorrectly) that the lower element in the tree may need to be signed
inclusive of its Signature because it is a child of the higher element.
Arguments:
$xml: string XML string
Returns: string Signed XML
=cut
sub sign {
my $self = shift;
my ($xml) = @_;
die "You cannot sign XML without a private key." unless $self->key;
my $dom = XML::LibXML->load_xml( string => $xml );
$self->{ parser } = XML::LibXML::XPathContext->new($dom);
$self->{ parser }->registerNs('dsig', 'http://www.w3.org/2000/09/xmldsig#');
$self->{ parser }->registerNs('ec', 'http://www.w3.org/2001/10/xml-exc-c14n#');
$self->{ parser }->registerNs('saml', 'urn:oasis:names:tc:SAML:2.0:assertion');
print ("Signing XML\n") if $DEBUG;
my @ids_to_sign = $self->_get_ids_to_sign();
foreach (@ids_to_sign) {
my $signid = $_;
# Temporarily create the Signature XML from the part
# TODO: ths section needs a rewrite to create the xml in
# a better way.
# Create a Reference xml fragment including digest section
my $digest_xml = $self->_reference_xml( $signid, "REPLACE DIGEST " . $signid );
# Create a SignedInfo xml fragment including digest section
my $signed_info = $self->_signedinfo_xml( $digest_xml );
# Create a Signature xml fragment including SignedInfo section
my $signature_xml = $self->_signature_xml( $signed_info, 'REPLACE SIGNATURE ' . $signid );
print ("Sign ID: $signid\n") if $DEBUG;
# Get the XML note to sign base on the ID
my $xml = $self->_get_xml_to_sign($signid);
# Set the namespace but do not apply it to the XML
$xml->setNamespace("http://www.w3.org/2000/09/xmldsig#", "dsig", 0);
# Canonicalize the XML to http://www.w3.org/2001/10/xml-exc-c14n#
# TODO Change the Canonicalization method in the xml fragment from _signedinfo_xml
# <dsig:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
# <dsig:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
my $xml_canon = $xml->toStringEC14N();
# Calculate the sha1 digest of the XML being signed
my $bin_digest = sha1( $xml_canon );
my $digest = encode_base64( $bin_digest, '' );
print (" Digest: $digest\n") if $DEBUG;
# Display the ID of the XML being signed for debugging
my $reference = $signid; #$self->{parser}->findvalue('//@ID', $xml);
print (" Reference URI: $reference\n") if $DEBUG;
# Add the Signature to the xml being signed
$xml->appendWellBalancedChunk($signature_xml, 'UTF-8');
# Canonicalize the SignedInfo to http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments
# TODO Change the Canonicalization method in the xml fragment from _signedinfo_xml
my ($signature_node) = $xml->findnodes(
'./dsig:Signature', $xml);
my ($signed_info_node) = $xml->findnodes(
'./dsig:Signature/dsig:SignedInfo',$xml);
# Add the digest value to the Signed info
my ($digest_value_node) = $xml->findnodes(
'./dsig:Signature/dsig:SignedInfo/dsig:Reference/dsig:DigestValue', $signature_node);
$digest_value_node->removeChildNodes();
$digest_value_node->appendText($digest);
# At this point the SignedInfo includes the information
# to allow us to use the _canonicalize_xml with the $signature_node
my $signed_info_canon = $self->_canonicalize_xml($signed_info_node, $signature_node);
# Calculate the signature of the Canonical Form of SignedInfo
my $signature;
if ($self->{key_type} eq 'dsa') {
print (" Signing SignedInfo using DSA key type\n") if $DEBUG;
# DSA only permits the signing of 20 bytes or less, hence the sha1
my $bin_signature = $self->{key_obj}->do_sign( sha1($signed_info_canon) );
# https://www.w3.org/TR/2002/REC-xmldsig-core-20020212/#sec-SignatureAlg
# The output of the DSA algorithm consists of a pair of integers
# The signature value consists of the base64 encoding of the
# concatonation of r and s in that order ($r . $s)
my $r = $bin_signature->get_r;
my $s = $bin_signature->get_s;
$signature = encode_base64( $r . $s, "\n" );
} else {
print (" Signing SignedInfo using RSA key type\n") if $DEBUG;
my $bin_signature = $self->{key_obj}->sign( $signed_info_canon );
$signature = encode_base64( $bin_signature, "\n" );
}
# Add the Signature to the SignatureValue
my ($signature_value_node) = $xml->findnodes(
'./dsig:Signature/dsig:SignatureValue', $signature_node);
$signature_value_node->removeChildNodes();
$signature_value_node->appendText($signature);
print ("\n\n\n SignatureValue:\n" . $signature_value_node . "\n\n\n") if $DEBUG;
}
return $dom;
}
=head3 B<verify($xml)>
Returns true or false based upon whether the signature is valid or not.
When using XML::Sig exclusively to verify a signature, no key needs to be
specified during initialization given that the public key should be
transmitted with the signature.
XML::Sig checks all signature in the provided xml and will fail should any
signature pointing to an existing ID in the XML fail to verify.
Should there be a Signature included that does not point to an existing node
in the XML it is ignored and other Signaures are checked. If there are no
other Signatures it will return false.
Arguments:
$xml: string XML string
Returns: string Signed XML
=cut
sub verify {
my $self = shift;
delete $self->{signer_cert};
my ($xml) = @_;
my $dom = XML::LibXML->load_xml( string => $xml );
$self->{ parser } = XML::LibXML::XPathContext->new($dom);
$self->{ parser }->registerNs('dsig', 'http://www.w3.org/2000/09/xmldsig#');
$self->{ parser }->registerNs('ec', 'http://www.w3.org/2001/10/xml-exc-c14n#');
$self->{ parser }->registerNs('saml', 'urn:oasis:names:tc:SAML:2.0:assertion');
my $signature_nodeset = $self->{ parser }->findnodes('//dsig:Signature');
my $numsigs = $signature_nodeset->size();
print ("NodeSet Size: $numsigs\n") if $DEBUG;
# Loop through each Signature in the document checking each
my $i;
while (my $signature_node = $signature_nodeset->shift()) {
$i++;
print ("\nSignature $i\n") if $DEBUG;
# set the namespace for the signature to a known prefix
$signature_node->setNamespace(
'http://www.w3.org/2000/09/xmldsig#', 'dsig', 1 );
# Get SignedInfo Reference ID
my $reference = $self->{ parser }->findvalue(
'dsig:SignedInfo/dsig:Reference/@URI', $signature_node);
$reference =~ s/#//g;
print (" Reference URI: $reference\n") if $DEBUG;
# The reference ID must point to something in the document
# if not disregard it and look for another signature
# TODO check to ensure that if there is only a single reference
# like this it won't accidentally validate
if (! $self->{ parser }->findvalue('//*[@ID=\''. $reference . '\']')) {
print (" Signature reference $reference is not signing anything in this xml\n") if $DEBUG;
if ($numsigs <= 1) {
return 0;
}
else {
next;
}
}
# Get SignedInfo DigestMethod Algorithim
my $digest_method = $self->{ parser }->findvalue(
'dsig:SignedInfo/dsig:Reference/dsig:DigestMethod/@Algorithm', $signature_node);
$digest_method =~ s/^.*[#]//;
print (" Digest Method: $digest_method\n") if $DEBUG;
# Get the DigestValue used to verify Canonical XML
my $refdigest = _trim($self->{ parser }->findvalue(
'dsig:SignedInfo/dsig:Reference/dsig:DigestValue', $signature_node));
print (" Digest Value: $refdigest\n") if $DEBUG;
# Get the SignatureValue used to verify the SignedInfo
my $signature = _trim($self->{ parser }->findvalue('dsig:SignatureValue', $signature_node));
print (" Signature: $signature\n") if $DEBUG;
# Get SignatureMethod Algorithim
my $signature_method = $self->{ parser }->findvalue(
'dsig:SignedInfo/dsig:SignatureMethod/@Algorithm', $signature_node);
$signature_method =~ s/^.*[#]//;
$signature_method =~ s/^rsa-//;
print (" SignatureMethod: $signature_method\n") if $DEBUG;
# Get the SignedInfo and obtain its Canonical form
my ($signed_info) = $self->{ parser }->findnodes('dsig:SignedInfo', $signature_node);
my $signed_info_canon = $self->_canonicalize_xml($signed_info, $signature_node);
if(Digest::SHA->can($digest_method)) {
my $rsa_hash = "use_$digest_method" . "_hash";
$self->{rsa_hash} = "use_$digest_method" . "_hash";
$self->{signature_method} = \&$signature_method; #FIXEME move
$self->{digest_method} = \&$digest_method;
}
else {
die("Can't handle $digest_method");
}
# If a cert was provided to XML::Sig->new() use it to
# verify the SignedInfo signature
if (defined $self->{cert_obj}) {
# use the provided cert to verify
unless ($self->_verify_x509_cert($self->{cert_obj},$signed_info_canon,$signature)) {
print STDERR "not verified by x509\n";
return 0;
}
}
# Extract the XML provided certificate and use it to
# verify the SignedInfo signature
else {
# extract the certficate or key from the document
my %verify_dispatch = (
'X509Data' => '_verify_x509',
'RSAKeyValue' => '_verify_rsa',
'DSAKeyValue' => '_verify_dsa',
);
my $keyinfo_nodeset;
foreach my $key_info_sig_type ( qw/X509Data RSAKeyValue DSAKeyValue/ ) {
if ( $key_info_sig_type eq 'X509Data' ) {
$keyinfo_nodeset = $self->{ parser }->find(
"dsig:KeyInfo/dsig:$key_info_sig_type", $signature_node);
#print (" keyinfo_nodeset X509Data: $keyinfo_nodeset\n") if $DEBUG;
} else {
$keyinfo_nodeset = $self->{ parser }->find(
"dsig:KeyInfo/dsig:KeyValue/dsig:$key_info_sig_type", $signature_node);
#print (" keyinfo_nodeset [DR]SAKeyValue: $keyinfo_nodeset\n") if $DEBUG;
}
if ( $keyinfo_nodeset->size ) {
my $verify_method = $verify_dispatch{$key_info_sig_type};
print (" Verify Method: $verify_method\n") if $DEBUG;
if ( ! $self->$verify_method($keyinfo_nodeset->get_node(0),
$signed_info_canon, $signature) ) {
print ("keyinfo_nodeset->get_node: " . $keyinfo_nodeset->get_node(0) . "\n") if $DEBUG;
print STDERR "Failed to verify using $verify_method\n";
return 0;
} else {
print ("Success Verifying\n") if $DEBUG;
}
last;
}
}
die "Unrecognized key type or no KeyInfo in document" unless (
$keyinfo_nodeset && $keyinfo_nodeset->size > 0);
}
# Signature of SignedInfo was verified above now obtain the
# Canonical form of the XML and verify the DigestValue of the XML
# Remove the Signature from the signed XML
my $signed_xml = $self->_get_signed_xml( $signature_node );
$signed_xml->removeChild( $signature_node );
# Obtain the Canonical form of the XML
my $canonical = $self->_transform($signed_xml, $signature_node);
# Add the $signature_node back to the $signed_xml to allow other
# signatures to be validated if they exist
$signed_xml->addChild( $signature_node );
# Obtain the DigestValue of the Canonical XML
my $digest = $self->{digest_method}->($canonical);
print ( " Reference Digest " . _trim($refdigest) ."\n") if $DEBUG;
print ( " Calculated Digest: ". _trim(encode_base64($digest, '')) ."\n") if $DEBUG;
# Return 0 - fail verification on the first XML signature that fails
return 0 unless ($refdigest eq _trim(encode_base64($digest, '')));
print ( "Signature $i Valid\n") if $DEBUG;
}
return 1;
}
=head3 B<signer_cert()>
Following a successful verify with an X509 certificate, returns the
signer's certificate as embedded in the XML document for verification
against a CA certificate. The certificate is returned as a
Crypt::OpenSSL::X509 object.
Arguments: none
Returns: Crypt::OpenSSL::X509: Certificate used to sign the XML
=cut
sub signer_cert {
my $self = shift;
return $self->{signer_cert};
}
##
## _get_ids_to_sign()
##
## Arguments:
##
## Returns: array Value of ID attributes from XML
##
## Finds all the values of the ID attributes in the XML
## and return them in reverse order found. Reverse order
## assumes that the Signatures should be performed on lower
## Nodes first.
##
sub _get_ids_to_sign {
my $self = shift;
my @id = $self->{parser}->findnodes('//@ID');
my @ids;
foreach (@id) {
my $i = $_;
$_ =~ m/^.*\"(.*)\".*$/;
$i = $1;
#//*[@ID='identifier_1']
die "You cannot sign an XML document without identifying the element to sign with an ID attribute" unless $i;
unshift @ids, $i;
}
return @ids;
}
##
## _get_xml_to_sign()
##
## Arguments:
## $id: string ID of the Node for the XML to retrieve
##
## Returns: XML NodeSet to sign
##
## Find the XML node with the ID = $id and return the
## XML NodeSet
##
sub _get_xml_to_sign {
my $self = shift;
my $id = shift;
die "You cannot sign an XML document without identifying the element to sign with an ID attribute" unless $id;
my $xpath = "//*[\@ID='$id']";
my ($node) = $self->_get_node( $xpath );
return $node;
}
##
## _get_signed_xml($context)
##
## Arguments:
## $context: string XML NodeSet used as context
##
## Returns: XML NodeSet for with ID equal to the URI
##
## Find the XML node with the ID = $URI and return the
## XML NodeSet
##
sub _get_signed_xml {
my $self = shift;
my ($context) = @_;
my $id = $self->{parser}->findvalue('./dsig:SignedInfo/dsig:Reference/@URI', $context);
$id =~ s/^#//;
print (" Signed XML id: $id\n") if $DEBUG;
$self->{'sign_id'} = $id;
my $xpath = "//*[\@ID='$id']";
return $self->_get_node( $xpath, $context );
}
##
## _transform($xml, $context)
##
## Arguments:
## $xml: string XML NodeSet
## $context: string XML Context
##
## Returns: string Transformed XML
##
## Canonicalizes/Transforms xml based on the Transforms
## from the SignedInfo.
##
sub _transform {
my $self = shift;
my ($xml, $context) = @_;
$context->setNamespace( 'http://www.w3.org/2000/09/xmldsig#', 'dsig' );
my $transforms = $self->{parser}->find(
'dsig:SignedInfo/dsig:Reference/dsig:Transforms/dsig:Transform',
$context
);
foreach my $node ($transforms->get_nodelist) {
my $alg = $node->getAttribute('Algorithm');
print "Algorithm: $alg\n" if $DEBUG;
if ($alg eq TRANSFORM_ENV_SIG) {
# TODO the xml being passed here currently has the
# Signature removed. May be better to do it all here
next;
}
elsif ($alg eq TRANSFORM_C14N) {
$xml = $xml->toStringC14N();
}
elsif ($alg eq TRANSFORM_C14N_COMMENTS) {
$xml = $xml->toStringC14N(1);
}
elsif ($alg eq TRANSFORM_EXC_C14N) {
$xml = $xml->toStringEC14N();
}
elsif ($alg eq TRANSFORM_EXC_C14N_COMMENTS) {
$xml = $xml->toStringEC14N(1);
}
else {
die "Unsupported transform: $alg";
}
}
return $xml;
}
##
## _verify_rsa($context,$canonical,$sig)
##
## Arguments:
## $context: string XML Context to use
## $canonical: string Canonical XML to verify
## $sig: string Base64 encode of RSA Signature
##
## Returns: integer (1 True, 0 False) if signature is valid
##
## Verify the RSA signature of Canonical XML
##
sub _verify_rsa {
my $self = shift;
my ($context,$canonical,$sig) = @_;
# Generate Public Key from XML
my $mod = _trim($self->{parser}->findvalue('dsig:Modulus', $context));
my $modBin = decode_base64( $mod );
my $exp = _trim($self->{parser}->findvalue('dsig:Exponent', $context));
my $expBin = decode_base64( $exp );
my $n = Crypt::OpenSSL::Bignum->new_from_bin($modBin);
my $e = Crypt::OpenSSL::Bignum->new_from_bin($expBin);
my $rsa_pub = Crypt::OpenSSL::RSA->new_key_from_parameters( $n, $e );
# Decode signature and verify
my $bin_signature = decode_base64($sig);
return 1 if ($rsa_pub->verify( $canonical, $bin_signature ));
return 0;
}
##
## _clean_x509($cert)
##
## Arguments:
## $cert: string Certificate in base64 from XML
##
## Returns: string Certificate in Valid PEM format
##
## Reformats Certifcate string into PEM format 64 characters
## with proper header and footer
##
sub _clean_x509 {
my $self = shift;
my ($cert) = @_;
$cert = $cert->value() if(ref $cert);
chomp($cert);
# rewrap the base64 data from the certificate; it may not be
# wrapped at 64 characters as PEM requires
$cert =~ s/\n//g;
my @lines;
while (length $cert > 64) {
push @lines, substr $cert, 0, 64, '';
}
push @lines, $cert;
$cert = join "\n", @lines;
$cert = "-----BEGIN CERTIFICATE-----\n" . $cert . "\n-----END CERTIFICATE-----\n";
return $cert;
}
##
## _verify_x509($context,$canonical,$sig)
##
## Arguments:
## $context: string XML Context to use
## $canonical: string Canonical XML to verify
## $sig: string Base64 encode of RSA Signature
##
## Returns: integer (1 True, 0 False) if signature is valid
##
## Verify the RSA signature of Canonical XML using an X509
##
sub _verify_x509 {
my $self = shift;
my ($context,$canonical,$sig) = @_;
eval {
require Crypt::OpenSSL::X509;
};
confess "Crypt::OpenSSL::X509 needs to be installed so that we can handle X509 certificates" if $@;
# Generate Public Key from XML
my $certificate = _trim($self->{parser}->findvalue('dsig:X509Certificate', $context));
# This is added because the X509 parser requires it for self-identification
$certificate = $self->_clean_x509($certificate);
my $cert = Crypt::OpenSSL::X509->new_from_string($certificate);
return $self->_verify_x509_cert($cert, $canonical, $sig);
}
##
## _verify_x509_cert($cert,$canonical,$sig)
##
## Arguments:
## $cert: string X509 Certificate
## $canonical: string Canonical XML to verify
## $sig: string Base64 encode of RSA Signature
##
## Returns: integer (1 True, 0 False) if signature is valid
##
## Verify the X509 signature of Canonical XML
##
sub _verify_x509_cert {
my $self = shift;
my ($cert, $canonical, $sig) = @_;
eval {
require Crypt::OpenSSL::RSA;
};
my $rsa_pub = Crypt::OpenSSL::RSA->new_public_key($cert->pubkey);
# Decode signature and verify
my $bin_signature = decode_base64($sig);
my $rsa_hash = $self->{rsa_hash};
$rsa_pub->$rsa_hash();
# If successful verify, store the signer's cert for validation
if ($rsa_pub->verify( $canonical, $bin_signature )) {
$self->{signer_cert} = $cert;
return 1;
}
return 0;
}
##
## _verify_dsa($context,$canonical,$sig)
##
## Arguments:
## $context: string XML Context to use
## $canonical: string Canonical XML to verify
## $sig: string Base64 encode 40 byte string of r and s
##
## Returns: integer (1 True, 0 False) if signature is valid
##
## Verify the DSA signature of Canonical XML
##
sub _verify_dsa {
my $self = shift;
my ($context,$canonical,$sig) = @_;
eval {
require Crypt::OpenSSL::DSA;
};
# Generate Public Key from XML
my $p = decode_base64(_trim($self->{parser}->findvalue('dsig:P', $context)));
my $q = decode_base64(_trim($self->{parser}->findvalue('dsig:Q', $context)));
my $g = decode_base64(_trim($self->{parser}->findvalue('dsig:G', $context)));
my $y = decode_base64(_trim($self->{parser}->findvalue('dsig:Y', $context)));
my $dsa_pub = Crypt::OpenSSL::DSA->new();
$dsa_pub->set_p($p);
$dsa_pub->set_q($q);
$dsa_pub->set_g($g);
$dsa_pub->set_pub_key($y);
# Decode signature and verify
my $bin_signature = decode_base64($sig);
# https://www.w3.org/TR/2002/REC-xmldsig-core-20020212/#sec-SignatureAlg
# The output of the DSA algorithm consists of a pair of integers
# The signature value consists of the base64 encoding of the
# concatonation of r and s in that order ($r . $s)
# Binary Signature is stored as a concatonation of r and s
my ($r, $s) = unpack('a20 a20', $bin_signature);
# Create a new Signature Object from r and s
my $sigobj = Crypt::OpenSSL::DSA::Signature->new();
$sigobj->set_r($r);
$sigobj->set_s($s);
# DSA signatures are limited to a message body of 20 characters, so a sha1 digest is taken
return 1 if ($dsa_pub->do_verify( $self->{digest_method}->($canonical), $sigobj ));
return 0;
}
##
## _get_node($xpath, context)
##
## Arguments:
## $xpath: string XML XPath to use
## $context: string XML context
##
## Returns: string XML NodeSet
##
## Return a NodeSet based on the xpath string
##
sub _get_node {
my $self = shift;
my ($xpath, $context) = @_;
my $nodeset;
if ($context) {
$nodeset = $self->{parser}->find($xpath, $context);
} else {
$nodeset = $self->{parser}->find($xpath);
}
foreach my $node ($nodeset->get_nodelist) {
return $node;
}
}
# TODO remove unused?
sub _get_node_as_text {
my $self = shift;
my ($xpath, $context) = @_;
my $node = $self->_get_node($xpath, $context);
if ($node) {
return $node->toString;
} else {
return '';
}
}
# TODO remove unused?
sub _transform_env_sig {
my $self = shift;
my ($str) = @_;
my $prefix = '';
if (defined $self->{dsig_prefix} && length $self->{dsig_prefix}) {
$prefix = $self->{dsig_prefix} . ':';
}
# This removes the first Signature tag from the XML - even if there is another XML tree with another Signature inside and that comes first.
# TODO: Remove the outermost Signature only.
$str =~ s/(<${prefix}Signature(.*?)>(.*?)\<\/${prefix}Signature>)//is;
return $str;
}
##
## _trim($string)
##
## Arguments:
## $string: string String to remove whitespace
##
## Returns: string Trimmed String
##
## Trim the whitespace from the begining and end of the string
##
sub _trim {
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
##
## _load_dsa_key($key_text)
##
## Arguments:
## $key_text: string DSA Private Key as String
##
## Returns: nothing
##
## Populate:
## self->{KeyInfo}
## self->{key_obj}
## self->{key_type}
##
sub _load_dsa_key {
my $self = shift;
my $key_text = shift;
eval {
require Crypt::OpenSSL::DSA;
};
confess "Crypt::OpenSSL::DSA needs to be installed so that we can handle DSA keys." if $@;
my $dsa_key = Crypt::OpenSSL::DSA->read_priv_key_str( $key_text );
if ( $dsa_key ) {
$self->{ key_obj } = $dsa_key;
my $g = encode_base64( $dsa_key->get_g(), '' );
my $p = encode_base64( $dsa_key->get_p(), '' );
my $q = encode_base64( $dsa_key->get_q(), '' );
my $y = encode_base64( $dsa_key->get_pub_key(), '' );
$self->{KeyInfo} = "<dsig:KeyInfo>
<dsig:KeyValue>
<dsig:DSAKeyValue>
<dsig:P>$p</dsig:P>
<dsig:Q>$q</dsig:Q>
<dsig:G>$g</dsig:G>
<dsig:Y>$y</dsig:Y>
</dsig:DSAKeyValue>
</dsig:KeyValue>
</dsig:KeyInfo>";
$self->{key_type} = 'dsa';
}
else {
confess "did not get a new Crypt::OpenSSL::RSA object";
}
}
##
## _load_rsa_key($key_text)
##
## Arguments:
## $key_text: string RSA Private Key as String
##
## Returns: nothing
##
## Populate:
## self->{KeyInfo}
## self->{key_obj}
## self->{key_type}
##
sub _load_rsa_key {
my $self = shift;
my ($key_text) = @_;
eval {
require Crypt::OpenSSL::RSA;
};
my $rsaKey = Crypt::OpenSSL::RSA->new_private_key( $key_text );
if ( $rsaKey ) {
$rsaKey->use_pkcs1_padding();
$self->{ key_obj } = $rsaKey;
$self->{ key_type } = 'rsa';
if (!$self->{ x509 }) {
my $bigNum = ( $rsaKey->get_key_parameters() )[1];
my $bin = $bigNum->to_bin();
my $exp = encode_base64( $bin, '' );
$bigNum = ( $rsaKey->get_key_parameters() )[0];
$bin = $bigNum->to_bin();
my $mod = encode_base64( $bin, '' );
$self->{KeyInfo} = "<dsig:KeyInfo>
<dsig:KeyValue>
<dsig:RSAKeyValue>
<dsig:Modulus>$mod</dsig:Modulus>
<dsig:Exponent>$exp</dsig:Exponent>
</dsig:RSAKeyValue>
</dsig:KeyValue>
</dsig:KeyInfo>";
}
}
else {
confess "did not get a new Crypt::OpenSSL::RSA object";
}
}
##
## _load_x509_key($key_text)
##
## Arguments:
## $key_text: string RSA Private Key as String
##
## Returns: nothing
##