Mojo/XMLSig.pm

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Mojo/SAML/IdP.pm ↑ Summary Mojo/SAML/Document.pm »
1 package Mojo::XMLSig;
2  
3 2 ▶use Mojo::Base -strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 2 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Digest::SHA;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Mojo::DOM;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Mojo::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 0 ▶use XML::CanonicalizeXML;
Subroutine BEGIN: called CC=1 SCAR=2.6
10  
11 my $isa = sub {
12 my ($obj, $class) = @_;
13 Scalar::Util::blessed($obj) && $obj->isa($class);
14 };
15 my %ns = (ds => 'http://www.w3.org/2000/09/xmldsig#');
16  
17 my %actions = (
18 # xml
19 'http://www.w3.org/2000/09/xmldsig#enveloped-signature' => \&_enveloped_signature,
20  
21 # canonical
22 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315' => _mk_canon(0,0),
23 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments' => _mk_canon(0,1),
24 'http://www.w3.org/2006/12/xml-c14n11' => _mk_canon(2,0),
25 'http://www.w3.org/2006/12/xml-c14n11#WithComments' => _mk_canon(2,1),
26 'http://www.w3.org/2001/10/xml-exc-c14n#' => _mk_canon(1,0),
27 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments' => _mk_canon(1,1),
28  
29 # encoding
30 'http://www.w3.org/2000/09/xmldsig#base64' => sub { Mojo::Util::b64_encode(shift, '') },
31  
32 # digest
33 'http://www.w3.org/2000/09/xmldsig#sha1' => sub { _get_digest(sha1 => @_) },
34 'http://www.w3.org/2001/04/xmlenc#sha256' => sub { _get_digest(sha256 => @_) },
35 'http://www.w3.org/2001/04/xmldsig-more#sha224' => sub { _get_digest(sha224 => @_) },
36 'http://www.w3.org/2001/04/xmldsig-more#sha384' => sub { _get_digest(sha384 => @_) },
37 'http://www.w3.org/2001/04/xmlenc#sha512' => sub { _get_digest(sha512 => @_) },
38  
39 # sign
40 'http://www.w3.org/2000/09/xmldsig#rsa-sha1' => sub { _rsa(sha1 => @_) },
41 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha224' => sub { _rsa(sha224 => @_) },
42 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' => sub { _rsa(sha256 => @_) },
43 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha384' => sub { _rsa(sha384 => @_) },
44 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512' => sub { _rsa(sha512 => @_) },
45 );
46  
47 sub digest { _digest(0, @_) }
48  
49 sub format_cert {
50 my $cert = shift;
51 $cert =~ s/\n//g;
52 $cert = Mojo::Util::trim $cert;
53 $cert = Mojo::Util::b64_encode(Mojo::Util::b64_decode($cert), "\n");
54 $cert = Mojo::Util::trim $cert;
55 $cert = "-----BEGIN CERTIFICATE-----\n$cert\n-----END CERTIFICATE-----\n";
56 return $cert;
57 }
58  
59 sub has_signature {
60 my $dom = shift;
61 $dom = _dom($dom)
62 unless $dom->$isa('Mojo::DOM');
63 return !!$dom->at('ds|Signature ds|SignatureValue:not(:empty)', %ns);
64 }
65  
66 sub sign {
67 my ($xml, $key) = @_;
68 _signature(0, _digest(0, $xml), $key);
69 }
70  
71 sub trim_cert {
72 my $cert = shift;
73 $cert =~ s/-----[^-]*-----//gm;
74 $cert =~ s/[\r\n]//g;
75 return Mojo::Util::trim($cert);
76 }
77  
78 sub verify {
79 my ($dom, $key) = @_;
80 my $ret = eval { _digest(1, $dom); 1 };
81 warn "$@" if $@;
82 return 0 unless $ret;
83 $ret = eval { _signature(1, $dom, $key); 1 };
84 warn "$@" if $@;
85 return $ret ? 1 : 0;
86 }
87  
88 my $set_algo = sub {
89 my ($key, $algo) = @_;
90 Carp::croak 'Key must be an instance of Crypt::OpenSSL::RSA'
91 unless $key->$isa('Crypt::OpenSSL::RSA');
92 Carp::croak 'Unsupported RSA algorithm'
93 unless my $method = $key->can("use_${algo}_hash");
94 $key->$method;
95 return $key;
96 };
97  
98 sub _digest {
99 my ($verify, $dom) = @_;
100 $dom = _dom($dom)
101 unless $dom->$isa('Mojo::DOM');
102 Carp::croak 'No Signature section found'
103 unless my $sig = $dom->at('ds|Signature', %ns);
104  
105 my $refs = $sig->find('ds|Reference', %ns);
106 Carp::croak 'Nothing to verify'
107 unless $refs->size;
108  
109 $refs->each(sub{
110 my $ref = shift;
111 my $uri = $ref->{URI};
112 Carp::croak "Cannot process references other than ID. Got: $uri"
113 unless $uri =~ s/^#//;
114  
115 my $clone = _dom($dom);
116 Carp::croak "Cannot find element ID=$uri"
117 unless my $elem = $clone->at(qq![ID="$uri"]!);
118  
119 $ref->find('ds|Transforms > ds|Transform', %ns)->each(sub{
120 my $trans = shift->{Algorithm};
121 $elem = _do_action($trans, $elem);
122 Carp::croak "Transform $trans resulted in no value"
123 unless defined $elem && length "$elem";
124 });
125  
126 Carp::croak 'No DigestMethod was defined'
127 unless my $algo = $ref->at('ds|DigestMethod', %ns);
128 my $digest = _do_action($algo->{Algorithm}, "$elem");
129  
130 my $value = $ref->at('ds|DigestValue', %ns);
131  
132 if ($value) {
133 if ($value->matches(':empty') && !$verify) {
134 $value->content($digest);
135 } else {
136 $value = Mojo::Util::trim($value->text);
137 Carp::croak "Existing digest '$value' does not equal calculated value '$digest'"
138 unless $value eq $digest;
139 }
140 } else {
141 # Originally this method could create the tag, but I want to enforce that
142 # the structure come from the document itself
143  
144 Carp::croak "No DigestValue exists"; # if $verify;
145 #my $tag = $ref->tag;
146 #$tag =~ s/Reference/DigestValue/; # preserve prefix
147 #$ref->append_content("<$tag>$digest</$tag>");
148 }
149 });
150  
151 return $dom;
152 }
153  
154 sub _do_action {
155 my $action = shift;
156 Carp::croak "Action $action not understood"
157 unless my $code = $actions{$action};
158 return $code->(@_);
159 }
160  
161 sub _dom { Mojo::DOM->new->xml(1)->parse("$_[0]") }
162  
163 sub _get_digest {
164 my ($algo, $content) = @_;
165 my $digest = Digest::SHA->can("${algo}_base64")->($content);
166 while (length($digest) % 4) { $digest .= '=' }
167 return $digest;
168 }
169  
170 sub _enveloped_signature {
171 my $dom = shift;
172 my $sig = $dom->at('ds|Signature', %ns);
173 $sig ? $sig->remove : warn 'No Signature was removed';
174 return $dom;
175 }
176  
177 sub _mk_canon {
178 my ($ex, $comment) = @_;
179 return sub { XML::CanonicalizeXML::canonicalize("$_[0]", '<XPath>(//. | //@* | //namespace::*)</XPath>', '', $ex, $comment) };
180 }
181  
182 sub _rsa {
183 my ($algo, $verify, $text, $dom, $key) = @_;
184 return $verify ? _verify_rsa($algo, $text, $dom, $key) : _sign_rsa($algo, $text, $dom, $key);
185 }
186  
187 sub _sign_rsa {
188 my ($algo, $text, $dom, $key) = @_;
189 $key->$set_algo($algo);
190  
191 Carp::croak 'No X509Certificate element found for cert storage'
192 unless my $elem = $dom->at('ds|KeyInfo > ds|X509Data > ds|X509Certificate', %ns);
193 return Mojo::Util::b64_encode($key->sign(Mojo::Util::trim $text), '');
194 }
195  
196 sub _signature {
197 my ($verify, $dom, $key) = @_;
198 $dom = _dom($dom)
199 unless $dom->$isa('Mojo::DOM');
200 Carp::croak 'No Signature section found'
201 unless my $elem = $dom->at('ds|Signature', %ns);
202  
203 Carp::croak 'Nothing to verify'
204 unless $elem->find('ds|Reference > ds|DigestValue:not(:empty)', %ns)->size;
205  
206 Carp::croak 'No CanonicalizationMethod is specified'
207 unless my $c_method = $elem->at('ds|CanonicalizationMethod[Algorithm]', %ns)->{Algorithm};
208 Carp::croak 'No SignatureMethod is specified'
209 unless my $s_method = $elem->at('ds|SignatureMethod[Algorithm]', %ns)->{Algorithm};
210  
211 my $siginfo = $elem->at('ds|SignedInfo', %ns);
212  
213 # inject namespace if necessary
214 if ($siginfo->tag =~ /^([^:]+):/) {
215 my $prefix = $1;
216 my $ns = $siginfo->namespace;
217 $siginfo = _dom($siginfo);
218 $siginfo->at(':root')->attr("xmlns:$prefix" => $ns);
219 }
220  
221 my $canon = _do_action($c_method, $siginfo);
222 my $value = _do_action($s_method, $verify, $canon, $elem, $key);
223  
224 unless ($verify) {
225 Carp::croak 'No SignatureValue present'
226 unless my $sig = $dom->at('ds|SignatureValue', %ns);
227 $sig->content($value);
228 }
229  
230 return $dom;
231 }
232  
233 sub _verify_rsa {
234 my ($algo, $text, $dom, $key) = @_;
235 unless ($key) {
236 Carp::croak 'No X509Certificate element found for cert storage'
237 unless my $elem = $dom->at('ds|KeyInfo > ds|X509Data > ds|X509Certificate:not(:empty)', %ns);
238 my $cert = format_cert($elem->text);
239  
240 require Crypt::OpenSSL::X509;
241 require Crypt::OpenSSL::RSA;
242 $cert = Crypt::OpenSSL::X509->new_from_string($cert);
243 $key = Crypt::OpenSSL::RSA->new_public_key($cert->pubkey);
244 }
245  
246 $key->$set_algo($algo);
247 Carp::croak 'No SignatureValue present'
248 unless my $sig = $dom->at('ds|SignatureValue:not(:empty)', %ns);
249 $sig = Mojo::Util::b64_decode($sig->text);
250  
251 Carp::croak 'Signature does not verify'
252 unless $key->verify($text, $sig);
253  
254 return $sig;
255 }
256  
257 1;
258  
259 =head1 NAME
260  
261 Mojo::XMLSig - An implementation of XML-Sig using the Mojo toolkit
262  
263 =head1 SYNOPSIS
264  
265 use Mojo::XMLSig;
266  
267 # sign
268 my $xml = ...;
269 my $key = Crypt::OpenSSL::RSA->new_private_key(...);
270 my $signed = Mojo::XMLSig::sign($xml, $key);
271  
272 # verify using an embedded certificate
273 my $verified = Mojo::XMLSig::verify($signed);
274  
275 # verify using a known public certificate
276 my $pub = Crypt::OpenSSL::RSA->new_public_key(...);
277 my $verified = Mojo::XMLSig::verify($signed, $pub);
278  
279 =head1 DESCRIPTION
280  
281 L<Mojo::XMLSig> is an implementation of the L<XML Signature Syntax and Processing Version 1.1|https://www.w3.org/TR/xmldsig-core1/> spec.
282 It allows a user to sign and verify documents in XML format.
283 This is a requirement for many SAML documents and recommended in nearly all others.
284  
285 It is important to note that module does not create any tags.
286 Rather it relies on you passing in a document with the relevant sections included.
287 It will then fill out the computed sections given the parameters and algorithms specified.
288 In this way signing and verifying are actually quite similar.
289  
290 An example document to be signed could be as follows.
291  
292 <Thing ID="abc123">
293 <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
294 <ds:SignedInfo>
295 <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
296 <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
297 <ds:Reference URI="#abc123">
298 <ds:Transforms>
299 <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
300 <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
301 </ds:Transforms>
302 <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
303 <ds:DigestValue></ds:DigestValue>
304 </ds:Reference>
305 </ds:SignedInfo>
306 <ds:SignatureValue></ds:SignatureValue>
307 <ds:KeyInfo>
308 <ds:X509Data>
309 <ds:X509Certificate>$cert</ds:X509Certificate>
310 </ds:X509Data>
311 </ds:KeyInfo>
312 </ds:Signature>
313  
314 <Important>Cool Stuff</Important>
315 </Thing>
316  
317 where C<$cert> is an x509 certificate, base64 encoded (but typically stripped of all formatting), if embedding the certificate.
318 Note that the KeyInfo section is not required if not embedding the certificate.
319  
320 Calling L</sign> on this document will return a new document with the DigestValue and SignatureValue elements populated.
321 While multiple Reference tags are supported, if multiple Signature tags are provided only the first one will be used.
322  
323 Note that L<Mojo::SAML::Document::Signature> and other relevant documents can be used to produce the signature for you if need be.
324  
325 =head1 CAVEATS
326  
327 This implementation only covers RSA signing and cannot process XPath directives.
328 Once other algorithms are implemented, the apis will accept more than just RSA keys.
329 I'm sure there are plenty of other things it can't do too.
330  
331 =head1 FUNCTIONS
332  
333 L<Mojo::XMLSig> is current only functions (though an OO interface is a possibility in the future).
334 It provides the following functions.
335  
336 =head2 digest
337  
338 my $output_xml = digest($input_xml);
339  
340 This intermediate function is unlikely to be used by the end consumer, however it might be useful in validating certain documents.
341 It injects the digested values of the Referenced sectioned into the DigestValue tags.
342 If you don't know why you should use it, you probably don't need it.
343  
344 =head2 format_cert
345  
346 my $cert = format_cert($text);
347  
348 A helper function that takes a base64 encoded certificate and properly formats it for use by L<Crypt::OpenSSL::X509>.
349 This is useful when extracting embedded certificates and is provided as public api for resuse in portions of L<Mojo::SAML>.
350  
351 =head2 has_signature
352  
353 my $boolean = has_signature($xml);
354  
355 Checks an XML document for the existence of a non-empty SignatureValue tag in the correct structure.
356  
357 =head2 sign
358  
359 my $signed_xml = sign($xml, $key);
360  
361 Signs a given XML document using a given L<Crypt::OpenSSL::RSA> private key.
362  
363 =head2 trim_cert
364  
365 my $text = trim_cert($cert);
366  
367 A helper function that takes a base64 encoded certificate and strips it of formatting for embedding in an XML Signature.
368 This is useful when extracting embedded certificates and is provided as public api for resuse in portions of L<Mojo::SAML>.
369  
370 =head2 verify
371  
372 my $boolean = verify($xml);
373 my $boolean = verify($xml, $key);
374  
375 Verifies the signature of a given XML document.
376 When passed a L<Crypt::OpenSSL::RSA> public key, it will verify it using that.
377 If not passed a key, it will attempt to verify the document using an embedded key.
378  
379 For security purposes, verifying using a known and previously exchanged public key is far more preferred.
380 Without this, all you can know is that the document hasn't been tampered with, not who signed it, since an attacker could have intercepted the document and modified both the contents and the signature.
381  
« Mojo/SAML/IdP.pm ↑ Summary Mojo/SAML/Document.pm »