blib/lib/Google/SAML/Response.pm

filter: Statementstmt 73.8% 110 / 149 Branchbran 57.6% 15 / 26 Conditioncond 66.6% 2 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 85.7% 18 / 21 Podpod 100% 3 / 3 totaltotal 72.5% 148 / 204 CC 16 SCAR 12.2
CC
16
Cov
71%
new
7.3
_canonicalize_xml
4.7
get_response_xml
4.4
CRAP 3.4
↑ Summary
1 # Copyright (c) 2013 Manni Heumann. All rights reserved.
2 #
3 # This program is free software; you can redistribute it and/or
4 # modify it under the same terms as Perl itself.
5 #
6  
7 package Google::SAML::Response;
8  
9 =head1 NAME
10  
11 Google::SAML::Response - Generate signed XML documents as SAML responses for
12 Google's SSO implementation
13  
14 =head1 VERSION
15  
16 You are currently reading the documentation for version 0.15
17  
18 =head1 DESCRIPTION
19  
20 Google::SAML::Response can be used to generate a signed XML document that is
21 needed for logging your users into Google using SSO.
22  
23 You have some sort of web application that can identify and authenticate users.
24 You want users to be able to use some sort of Google service such as Google mail.
25  
26 When using SSO with your Google partner account, your users will send a request
27 to a Google URL. If the user isn't already logged in to Google, Google will
28 redirect him to a URL that you can define. Behind this URL, you need to have
29 a script that authenticates users in your original framework and generates a
30 SAML response for Google that you send back to the user whose browser will then
31 submit it back to Google. If everything works, users will then be logged into
32 their Google account and they don't even have to know their usernames or
33 passwords.
34  
35 =head1 SYNOPSIS
36  
37 use Google::SAML::Response;
38 use CGI;
39  
40 # get SAMLRequest parameter:
41 my $req = CGI->new->param('SAMLRequest');
42  
43 # authenticate user
44 ...
45  
46 # find our user's login for Google
47 ...
48  
49 # Generate SAML response
50 my $saml = Google::SAML::Response->new( {
51 key => $key,
52 login => $login,
53 request => $req
54 } );
55 my $xml = $saml->get_response_xml;
56  
57 # Alternatively, send a HTML page to the client that will redirect
58 # her to Google. You have to extract the RelayState param from the
59 # cgi environment first.
60  
61 print $saml->get_google_form( $relayState );
62  
63 =head1 PREREQUISITES
64  
65 You will need the following modules installed:
66  
67 =over
68  
69 =item * L<Crypt::OpenSSL::RSA|Crypt::OpenSSL::RSA>
70  
71 =item * L<Crypt::OpenSSL::Bignum|Crypt::OpenSSL::Bignum>
72  
73 =item * L<XML::Canonical or XML::CanonicalizeXML|XML::Canonical or XML::CanonicalizeXML>
74  
75 =item * L<Digest::SHA|Digest::SHA>
76  
77 =item * L<Date::Format|Date::Format>
78  
79 =item * L<Google::SAML::Request|Google::SAML::Request>
80  
81 =back
82  
83 =head1 RESOURCES
84  
85 =over
86  
87 =item XML-Signature Syntax and Processing
88  
89 L<http://www.w3.org/TR/xmldsig-core/>
90  
91 =item Google-Documentation on SSO and SAML
92  
93 L<https://developers.google.com/google-apps/sso/saml_reference_implementation>
94  
95 =item XML Security Library
96  
97 L<http://www.aleksey.com/xmlsec/>
98  
99 =back
100  
101 =head1 METHODS
102  
103 =cut
104  
105 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
106 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
107  
108 5 ▶use Crypt::OpenSSL::RSA;
Subroutine BEGIN: called CC=1 SCAR=0.0
109 5 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
110 5 ▶use Digest::SHA qw/ sha1 /;
Subroutine BEGIN: called CC=1 SCAR=0.0
111 5 ▶use Date::Format;
Subroutine BEGIN: called CC=1 SCAR=0.0
112 5 ▶use Compress::Zlib;
Subroutine BEGIN: called CC=1 SCAR=0.0
113 5 ▶use Google::SAML::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
114 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
115 5 ▶use HTML::Entities;
Subroutine BEGIN: called CC=1 SCAR=0.0
116  
117  
118 5 our $VERSION = '0.15';
119  
120 =head2 new
121  
122 Creates a new object and needs to have all parameters needed to generate
123 the signed xml later on. Parameters are passed in as a hash-reference.
124  
125 =head3 Required parameters
126  
127 =over
128  
129 =item * request
130  
131 The SAML request, base64-encoded and all, just as retrieved from the GET
132 request your user contacted you with (make sure that it's not url-encoded, though)
133  
134 =item * key
135  
136 The path to your private key that will be used to sign the response. Currently,
137 only RSA and DSA keys without pass phrases are supported. B<NOTE>: To handle DSA keys,
138 the module L<Crypt::OpenSSL::DSA|Crypt::OpenSSL::DSA> needs to be installed. However,
139 it is not listed as a requirement in the Makefile for Google::SAML::Response, so make
140 sure it really is installed before using DSA keys.
141  
142 =item * login
143  
144 Your user's login name with Google
145  
146 =back
147  
148 =head3 Optional parameters
149  
150 =over
151  
152 =item * ttl
153  
154 Time to live: Number of seconds your response should be valid. Default is two minutes.
155  
156 =item * canonicalizer
157  
158 The name of the module that will be used to canonicalize parts of our xml. Currently,
159 L<XML::Canonical|XML::Canonical> and L<XML::CanonicalizeXML|XML::CanonicalizeXML> are
160 supported. L<XML::CanonicalizeXML|XML::CanonicalizeXML> is the default.
161  
162 =back
163  
164 =cut
165  
166  
167 14 ▶sub new {
Subroutine new: called CC=7 SCAR=19.9
Pod documented
168 14 my $class = shift;
169 14 my $params = shift;
170  
171 14 my $self = bless {}, $class;
172  
173 14 foreach my $required ( qw/ request key login / ) {
174 37 ▶ if ( exists $params->{ $required } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params->{$required}) { } 33 4 37
175 33 $self->{ $required } = $params->{ $required };
176 }
177 else {
178 4 confess "You need to provide the $required parameter!";
179 }
180 }
181  
182 10 my $request = Google::SAML::Request->new_from_string( $self->{ request } );
183  
184 10 ▶ if ( $request && $self->_load_key ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request and $self->_load_key) { } 8 0 8
Condition66%2/3
$request and $self->_load_key
!ll&&!rl&&r
028
MC/DC0%0/2
$request and $self->_load_key
$request $self->_load_key
Truth table33%1/3
A and B
A= $requestB= $self->_load_key
ABresult
0X0
100
111
185 8 $self->{ service_url } = $request->AssertionConsumerServiceURL;
186 8 $self->{ request_id } = $request->ID;
187 8 ▶ $self->{ ttl } = ( exists $params->{ ttl } ) ? $params->{ ttl } : 60*2;
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{'ttl'} ? : 0 8 8
188 $self->{ canonicalizer } = exists $params->{ canonicalizer }
189 ? $params->{ canonicalizer }
190 8 ▶ : 'XML::CanonicalizeXML';
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{'canonicalizer'} ? : 0 8 8
191  
192 8 return $self;
193 }
194 else {
195 0 return;
196 }
197 }
198  
199  
200 1 ▶sub _load_dsa_key {
Subroutine _load_dsa_key: called CC=3 SCAR=11.1
201 1 my $self = shift;
202 1 my $key_text = shift;
203  
204 1 eval {
205 1 require Crypt::OpenSSL::DSA;
206 };
207  
208 1 ▶ confess 'Crypt::OpenSSL::DSA needs to be installed so that we can handle DSA keys.' if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
209  
210 1 my $dsa_key = Crypt::OpenSSL::DSA->read_priv_key_str( $key_text );
211  
212 1 ▶ if ( $dsa_key ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dsa_key) { } 1 0 1
213 1 $self->{ key_obj } = $dsa_key;
214 1 my $g = encode_base64( $dsa_key->get_g, '' );
215 1 my $p = encode_base64( $dsa_key->get_p, '' );
216 1 my $q = encode_base64( $dsa_key->get_q, '' );
217 1 my $y = encode_base64( $dsa_key->get_pub_key, '' );
218  
219 1 $self->{ KeyInfo } = "<KeyInfo><KeyValue><DSAKeyValue><P>$p</P><Q>$q</Q><G>$g</G><Y>$y</Y></DSAKeyValue></KeyValue></KeyInfo>";
220 1 $self->{ key_type } = 'dsa';
221 }
222 else {
223 0 confess 'did not get a new Crypt::OpenSSL::RSA object';
224 }
225 }
226  
227  
228 7 ▶sub _load_rsa_key {
Subroutine _load_rsa_key: called CC=2 SCAR=7.0
229 7 my $self = shift;
230 7 my $key_text = shift;
231  
232 7 my $rsa_key = Crypt::OpenSSL::RSA->new_private_key( $key_text );
233  
234 7 ▶ if ( $rsa_key ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rsa_key) { } 7 0 7
235 7 $self->{ key_obj } = $rsa_key;
236  
237 7 my $big_num = ( $rsa_key->get_key_parameters )[ 1 ];
238 7 my $bin = $big_num->to_bin;
239 7 my $exp = encode_base64( $bin, '' );
240  
241 7 $big_num = ( $rsa_key->get_key_parameters )[ 0 ];
242 7 $bin = $big_num->to_bin;
243 7 my $mod = encode_base64( $bin, '' );
244 7 $self->{ KeyInfo } = "<KeyInfo><KeyValue><RSAKeyValue><Modulus>$mod</Modulus><Exponent>$exp</Exponent></RSAKeyValue></KeyValue></KeyInfo>";
245 7 $self->{ key_type } = 'rsa';
246 }
247 else {
248 0 confess 'did not get a new Crypt::OpenSSL::RSA object';
249 }
250 }
251  
252  
253 10 ▶sub _load_key {
Subroutine _load_key: called CC=4 SCAR=14.0
254 10 my $self = shift;
255  
256 10 my $file = $self->{ key };
257  
258 10 ▶ if ( open my $KEY, '<', $file ) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $KEY, '<', $file) { } 8 2 10
259 8 my $text = '';
260 8 local $/ = undef;
261 8 $text = <$KEY>;
262 8 close $KEY;
263  
264 8 ▶ if ( $text =~ m/BEGIN ([DR]SA) PRIVATE KEY/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /BEGIN ([DR]SA) PRIVATE KEY/) { } 8 0 8
265 8 my $key_used = $1;
266  
267 8 ▶ if ( $key_used eq 'RSA' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key_used eq 'RSA') { } 7 1 8
268 7 $self->_load_rsa_key( $text );
269 }
270 else {
271 1 $self->_load_dsa_key( $text );
272 }
273  
274 8 return 1;
275 }
276 else {
277 0 confess "Could not detect type of key $file.";
278 }
279 }
280 else {
281 2 confess "Could not load key $file: $!";
282 }
283  
284 0 return;
285 }
286  
287  
288 =head2 get_response_xml
289  
290 Generate the signed response xml and return it as a string
291  
292 The method does what the w3c tells us to do (L<http://www.w3.org/TR/xmldsig-core/#sec-CoreGeneration>):
293  
294 =over
295  
296 3.1.1 Reference Generation
297  
298 For each data object being signed:
299  
300 1. Apply the Transforms, as determined by the application, to the data object.
301  
302 2. Calculate the digest value over the resulting data object.
303  
304 3. Create a Reference element, including the (optional) identification of the data object, any (optional) transform elements, the digest algorithm and the DigestValue. (Note, it is the canonical form of these references that are signed in 3.1.2 and validated in 3.2.1 .)
305  
306 3.1.2 Signature Generation
307  
308 1. Create SignedInfo element with SignatureMethod, CanonicalizationMethod and Reference(s).
309  
310 2. Canonicalize and then calculate the SignatureValue over SignedInfo based on algorithms specified in SignedInfo.
311  
312 3. Construct the Signature element that includes SignedInfo, Object(s) (if desired, encoding may be different than that used for signing), KeyInfo (if required), and SignatureValue.
313  
314 =back
315  
316 =cut
317  
318 1 ▶sub get_response_xml {
Subroutine get_response_xml: called CC=2 SCAR=14.8
Pod documented
319 1 my $self = shift;
320  
321 # This is the xml response without any signatures or digests:
322 1 my $xml = $self->_response_xml;
323  
324 # We now calculate the SHA1 digest of the canoncial response xml
325 1 my $canonical = $self->_canonicalize_xml( $xml );
326  
327 0 my $bin_digest = sha1( $canonical );
328 0 my $digest = encode_base64( $bin_digest, '' );
329  
330 # Create a xml fragment containing the digest:
331 0 my $digest_xml = $self->_reference_xml( $digest );
332  
333 # create a xml fragment consisting of the SignedInfo element
334 0 my $signed_info = $self->_signedinfo_xml( $digest_xml );
335  
336 # We now calculate a signature over the canonical SignedInfo element
337  
338 0 $canonical = $self->_canonicalize_xml( $signed_info );
339 0 my $signature;
340  
341 0 ▶ if ( $self->{ key_type } eq 'dsa' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'key_type'} eq 'dsa') { } 0 0 0
342 0 my $sig = $self->{ key_obj }->do_sign( sha1( $canonical ) );
343 0 $signature = encode_base64( $sig->get_r . $sig->get_s );
344 }
345 else {
346 0 my $bin_signature = $self->{ key_obj }->sign( $canonical );
347 0 $signature = encode_base64( $bin_signature, "\n" );
348 }
349  
350 # With the signature value and the signedinfo element, we create
351 # a Signature element:
352 0 my $signature_xml = $self->_signature_xml( $signed_info, $signature );
353  
354 # Now insert the signature xml into our response xml
355 0 $xml =~ s/<samlp:Status>/$signature_xml<samlp:Status>/;
356  
357 0 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" . $xml;
358 }
359  
360  
361 0 ▶sub _signature_xml {
Subroutine _signature_xml: not called CC=1 SCAR=6.9
362 0 my $self = shift;
363 0 my $signed_info = shift;
364 0 my $signature_value = shift;
365  
366 0 return qq|<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
367 $signed_info
368 <SignatureValue>$signature_value</SignatureValue>
369 $self->{ KeyInfo }
370 </Signature>|;
371 }
372  
373  
374 0 ▶sub _signedinfo_xml {
Subroutine _signedinfo_xml: not called CC=1 SCAR=6.9
375 0 my $self = shift;
376 0 my $digest_xml = shift;
377  
378 0 return qq|<SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
379 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments" />
380 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#$self->{ key_type }-sha1" />
381 $digest_xml
382 </SignedInfo>|;
383 }
384  
385  
386 0 ▶sub _reference_xml {
Subroutine _reference_xml: not called CC=1 SCAR=6.9
387 0 my $self = shift;
388 0 my $digest = shift;
389  
390 0 return qq|<Reference URI="">
391 <Transforms>
392 <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
393 </Transforms>
394 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
395 <DigestValue>$digest</DigestValue>
396 </Reference>|;
397 }
398  
399  
400 1 ▶sub _canonicalize_xml {
Subroutine _canonicalize_xml: called CC=3 SCAR=15.4
401 1 my $self = shift;
402 1 my $xml = shift;
403  
404 1 ▶ if ( $self->{ canonicalizer } eq 'XML::Canonical' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'canonicalizer'} eq 'XML::Canonical') { } 0 1 1
elsif ($self->{'canonicalizer'} eq 'XML::CanonicalizeXML') { } 1 0 1
405 0 require XML::Canonical;
406 0 my $xmlcanon = XML::Canonical->new( comments => 1 );
407 0 return $xmlcanon->canonicalize_string( $xml );
408 }
409 elsif ( $self->{ canonicalizer } eq 'XML::CanonicalizeXML' ) {
410 1 require XML::CanonicalizeXML;
411 0 my $xpath = '<XPath>(//. | //@* | //namespace::*)</XPath>';
412 0 return XML::CanonicalizeXML::canonicalize( $xml, $xpath, [], 0, 0 );
413 }
414 else {
415 0 confess 'Unknown XML canonicalizer module.';
416 }
417 }
418  
419  
420 1 ▶sub _response_xml {
Subroutine _response_xml: called CC=1 SCAR=0.0
421 1 my $self = shift;
422  
423 # A 160-bit string containing a set of randomly generated characters.
424 # The ID MUST start with a character
425 1 my $response_id = sprintf 'GOSAML%0d%04d', time, rand( 10000 );
426  
427 # A timestamp indicating the date and time that the SAML response was generated
428 # Bsp: 2006-08-17T10:05:29Z
429 # All SAML time values have the type xs:dateTime, which is built in to the W3C XML Schema Datatypes
430 # specification [Schema2], and MUST be expressed in UTC form, with no time zone component.
431 1 my $issue_instant = time2str( "%Y-%m-%dT%XZ", time, 'UTC' );
432  
433 # A 160-bit string containing a set of randomly generated characters.
434 1 my $assertion_id = sprintf 'GOSAML%010d%04d', time, rand( 10000 );
435  
436 # The acs url
437 1 my $assertion_url = $self->{ service_url };
438  
439 # The username for the authenticated user.
440 1 my $username = $self->{ login };
441  
442 # A timestamp identifying the date and time after which the SAML response is deemed invalid.
443 1 my $best_before = time2str( '%Y-%m-%dT%XZ', time + $self->{ ttl }, 'UTC' );
444  
445 # A timestamp indicating the date and time that you authenticated the user.
446 1 my $authn_instant = $issue_instant;
447  
448 1 my $request_id = $self->{ request_id };
449  
450 return
451 1 qq|<samlp:Response xmlns="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" ID="$response_id" IssueInstant="$issue_instant" Version="2.0">
452 <samlp:Status>
453 <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"></samlp:StatusCode>
454 </samlp:Status>
455 <Assertion ID="$assertion_id" IssueInstant="$issue_instant" Version="2.0">
456 <Issuer>https://www.opensaml.org/IDP</Issuer>
457 <Subject>
458 <NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">$username</NameID>
459 <SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
460 <SubjectConfirmationData
461 Recipient="$assertion_url"
462 NotOnOrAfter="$best_before"
463 InResponseTo="$request_id"
464 />
465 </SubjectConfirmation>
466 </Subject>
467 <Conditions NotBefore="$issue_instant" NotOnOrAfter="$best_before">
468 <AudienceRestriction>
469 <Audience>$assertion_url</Audience>
470 </AudienceRestriction>
471 </Conditions>
472 <AuthnStatement AuthnInstant="$authn_instant">
473 <AuthnContext>
474 <AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</AuthnContextClassRef>
475 </AuthnContext>
476 </AuthnStatement>
477 </Assertion>
478 </samlp:Response>
479 |;
480 }
481  
482  
483 =head2 get_google_form
484  
485 This function will give you a complete HTML page that you can send to clients
486 to have them redirected to Google. Note that former versions of this module
487 also included a Content-Type HTTP header. Fortunately, this is no longer the
488 case and you will have to send a "Content-Type: text/html" yourself using
489 whatever method your framework provides.
490  
491 After all the hi-tec stuff Google wants us to do to parse their request and
492 generate a response, this is where it gets low-tec and messy. We are supposed
493 to give clients a html page that contains a hidden form that uses Javascript
494 to post that form to Google. Ugly, but it works. The form will contain a textarea
495 containing the response xml and a textarea containing the relay state.
496  
497 Hence the only required argument: the RelayState parameter from the user's GET request
498  
499 =cut
500  
501 1 ▶sub get_google_form {
Subroutine get_google_form: called CC=1 SCAR=0.6
Pod documented
502 1 my $self = shift;
503 1 my $rs = shift;
504  
505 1 my $url = $self->{ service_url };
506 1 my $output = "<!DOCTYPE html>\n";
507 1 $output .= "<html><head></head><body onload='javascript:document.acsForm.submit()'>\n";
508  
509 1 my $xml = $self->get_response_xml;
510 0 my $encoded_rs = encode_entities( $rs );
511  
512 0 $output .= qq|
513 <div style="display: none;">
514 <form name="acsForm" action="$url" method="post">
515 <textarea name="SAMLResponse">$xml</textarea>
516 <textarea name="RelayState">$encoded_rs</textarea>
517 <input type="submit" value="Submit SAML Response" />
518 </form>
519 </div>
520 |;
521  
522 0 $output .= "</body></html>\n";
523  
524 0 return $output;
525 }
526  
527  
528 5 1;
529  
530 __END__
↑ Summary