blib/lib/Postini/SAML.pm untested

filter: Statementstmt 0.0% 0 / 113 Branchbran 0.0% 0 / 6 Conditioncond 0.0% 0 / 4 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 155 CC 4 SCAR 11.1
CC
4
Cov
0%
new
6.0
_load_rsa_key
6.0
get_response_xml
6.0
CRAP 3.0
1 package Postini::SAML;
2 {
3 $Postini::SAML::VERSION = '0.001';
4 }
5  
6 use warnings;
7 use strict;
8  
9 use Crypt::OpenSSL::RSA;
10 use MIME::Base64 qw( encode_base64 );
11 use XML::Spice;
12 use Date::Format qw( time2str );
13 use Data::Random qw( rand_chars );
14 use XML::CanonicalizeXML;
15 use Digest::SHA1 qw( sha1 );
16 use Carp qw( croak );
17  
18 # Postini SAML ACS
19 my $ACS_URL = 'https://pfs.postini.com/pfs/spServlet';
20  
21 sub get_acs_url {
22 return $ACS_URL;
23 }
24  
25 sub new {
26 my ($class, $arg) = @_;
27  
28 my @missing = grep { not exists $arg->{$_} } qw( keyfile certfile issuer );
29 if ( @missing )
30 {
31 croak "missing args: " . join( q{ }, @missing );
32 }
33
34 my $self = bless {}, $class;
35  
36 $self->_load_rsa_key( $arg->{'keyfile'}, $arg->{'certfile'} );
37  
38 $self->{'issuer'} = $arg->{'issuer'};
39  
40 return $self;
41 }
42  
43 sub _load_rsa_key {
44 my ($self, $key_file, $cert_file) = @_;
45  
46 # load the keyfile and prepare a context for signing
47 open my $key_fh, '<', $key_file or croak "couldn't open $key_file for reading: $!";
48 my $key_text = do { local $/; <$key_fh> };
49 close $key_fh;
50  
51 my $key = Crypt::OpenSSL::RSA->new_private_key( $key_text );
52 if ( not $key )
53 {
54 croak "failed to instantiate Crypt::OpenSSL::RSA object from $key_file";
55 }
56  
57 $key->use_pkcs1_padding();
58 $self->{'key'} = $key;
59  
60 # we need to include the certificate without headers in the signed XML, so
61 # extract it
62 open my $cert_fh, '<', $cert_file or croak "couldn't open $cert_file for reading: $!";
63 my $cert_text = do { local $/; <$cert_fh> };
64 close $cert_fh;
65  
66 my ($cert_pem) = $cert_text =~ m{
67 -----BEGIN\sCERTIFICATE-----
68 (.+)
69 -----END\sCERTIFICATE-----
70 }smx;
71 $cert_pem =~ s{ [\r\n]+ }{}smxg;
72  
73 # build a XML fragment containing the key info. this will be included in
74 # the signature XML
75 $self->{'key_info_xml'} =
76 x('ds:KeyInfo',
77 x('ds:X509Data',
78 x('ds:X509Certificate', $cert_pem),
79 ),
80 ),
81 ;
82 }
83  
84 # return the current signature xml (actually XML::Spice chunk). deliberately
85 # returns undef if its not available, causing it to be ignored during chunk
86 # expansion
87 sub _get_cached_signature_xml {
88 my ($self) = @_;
89 return $self->{'signature_xml'};
90 }
91  
92 # generate a valid, signed response and return it
93 sub get_response_xml {
94 my ($self, $mail) = @_;
95  
96 if ( not $mail )
97 {
98 croak "required email address not provided";
99 }
100  
101 # INPUT:
102 # T, text-to-be-signed, a byte string;
103 # Ks, RSA private key;
104 #
105 # 1. Canonicalize the text-to-be-signed, C = C14n(T).
106 # 2. Compute the message digest of the canonicalized text, m = Hash(C).
107 # 3. Encapsulate the message digest in an XML <SignedInfo> element, SI, in canonicalized form.
108 # 4. Compute the RSA signatureValue of the canonicalized <SignedInfo> element, SV = RsaSign(Ks, SI).
109 # 5. Compose the final XML document including the signatureValue, this time in non-canonicalized form.
110
111 # get rid of any cached signature
112 delete $self->{'signature_xml'};
113  
114 # get the response data and canonicalise it
115 my $response_xml = $self->_response_xml( $mail );
116 my $canonical_response_xml = $self->_canonicalize_xml( $response_xml );
117  
118 # compute digest
119 my $response_digest = encode_base64( sha1( $canonical_response_xml ), q{} );
120  
121 # create a canonical signed info fragment
122 my $signed_info_xml = $self->_signed_info_xml( $response_digest );
123 my $canonical_signed_info_xml = $self->_canonicalize_xml( $signed_info_xml );
124  
125 # create the signature
126 my $signature = encode_base64( $self->{'key'}->sign( $canonical_signed_info_xml ), q{} );
127  
128 # now create the signature xml fragment
129 $self->{'signature_xml'} = $self->_signature_xml( $signed_info_xml, $signature );;
130  
131 # force the response chunk to be regenerated which will cause the
132 # signature to be included
133 $response_xml->forget;
134  
135 # stringify and return
136 return "".$response_xml;
137 }
138  
139 # generate a signature XML fragment, including the signature metadata fragment
140 # and the raw signature
141 sub _signature_xml {
142 my ($self, $signed_info_xml, $signature) = @_;
143  
144 my $signature_xml =
145 x('ds:Signature',
146 {
147 'xmlns:ds' => 'http://www.w3.org/2000/09/xmldsig#',
148 },
149 $signed_info_xml,
150 x('ds:SignatureValue', $signature),
151 $self->{'key_info_xml'},
152 ),
153 ;
154  
155 return $signature_xml;
156 }
157  
158 # generate a signature metadata XML fragement, including the message digest
159 sub _signed_info_xml {
160 my ($self, $digest) = @_;
161  
162 my $signed_info_xml =
163 x('ds:SignedInfo',
164 {
165 # we must include all the namespaces in use anywhere in the
166 # document so they can be included in the signature
167 'xmlns:ds' => 'http://www.w3.org/2000/09/xmldsig#',
168 'xmlns:saml' => 'urn:oasis:names:tc:SAML:1.0:assertion',
169 'xmlns:samlp' => 'urn:oasis:names:tc:SAML:1.0:protocol',
170 },
171  
172 x('ds:CanonicalizationMethod',
173 {
174 'Algorithm' => 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315',
175 },
176 ),
177 x('ds:SignatureMethod',
178 {
179 'Algorithm' => 'http://www.w3.org/2000/09/xmldsig#rsa-sha1',
180 },
181 ),
182  
183 x('ds:Reference',
184 {
185 'URI' => "",
186 },
187 x('ds:Transforms',
188 x('ds:Transform',
189 {
190 'Algorithm' => 'http://www.w3.org/2000/09/xmldsig#enveloped-signature',
191 },
192 ),
193 ),
194 x('ds:DigestMethod',
195 {
196 'Algorithm' => 'http://www.w3.org/2000/09/xmldsig#sha1',
197 }
198 ),
199 x('ds:DigestValue', $digest),
200 ),
201 ),
202 ;
203  
204 return $signed_info_xml;
205 }
206  
207 # build the SAML response, including the signature if available
208 sub _response_xml {
209 my ($self, $mail) = @_;
210  
211 my $now = time();
212 my $issue_instant = time2str( '%Y-%m-%dT%XZ', $now, 'UTC' );
213  
214 # assertion is valid for 60 seconds
215 my $not_on_or_after = time2str( '%Y-%m-%dT%XZ', $now+60, 'UTC' );
216  
217 # first character must not be a number to match xsd:ID
218 my $response_id = join q{}, 'z', rand_chars( 'set' => 'alphanumeric', 'size' => 40 );
219 my $assertion_id = join q{}, 'z', rand_chars( 'set' => 'alphanumeric', 'size' => 40 );
220 my $name_id = join q{}, 'z', rand_chars( 'set' => 'alphanumeric', 'size' => 40 );
221  
222 my $response_xml =
223 x('samlp:Response',
224 {
225 'xmlns:saml' => 'urn:oasis:names:tc:SAML:1.0:assertion',
226 'xmlns:samlp' => 'urn:oasis:names:tc:SAML:1.0:protocol',
227  
228 'MajorVersion' => '1',
229 'MinorVersion' => '1',
230  
231 'IssueInstant' => $issue_instant,
232 'ResponseID' => $response_id,
233 'Recipient' => $ACS_URL,
234 },
235  
236 # include the signature if its available. if not then it wil be
237 # undef and will be ignored
238 sub { $self->{'signature_xml'} },
239  
240 x('samlp:Status',
241 x('samlp:StatusCode',
242 {
243 'Value' => 'samlp:Success',
244 },
245 ),
246 ),
247  
248 x('saml:Assertion',
249 {
250 'MajorVersion' => '1',
251 'MinorVersion' => '1',
252  
253 'IssueInstant' => $issue_instant,
254 'AssertionID' => $assertion_id,
255 'Issuer' => $self->{'issuer'},
256 },
257  
258 x('saml:Conditions',
259 {
260 'NotBefore' => $issue_instant,
261 'NotOnOrAfter' => $not_on_or_after,
262 },
263 ),
264  
265 x('saml:AuthenticationStatement',
266 {
267 'AuthenticationInstant' => $issue_instant,
268 'AuthenticationMethod' => 'urn:oasis:names:tc:SAML:1.0:am:unspecified',
269 },
270  
271 x('saml:Subject',
272 x('saml:NameIdentifier', $name_id),
273 x('saml:SubjectConfirmation',
274 x('saml:ConfirmationMethod', 'urn:oasis:names:tc:SAML:1.0:cm:bearer'),
275 ),
276 ),
277 ),
278  
279 x('saml:AttributeStatement',
280 x('saml:Subject',
281 x('saml:NameIdentifier', $name_id),
282 x('saml:SubjectConfirmation',
283 x('saml:ConfirmationMethod', 'urn:oasis:names:tc:SAML:1.0:cm:bearer'),
284 ),
285 ),
286  
287 x('saml:Attribute',
288 {
289 'AttributeName' => 'personal_email',
290 'AttributeNamespace' => 'urn:mace:shibboleth:1.0:attributeNamespace:uri',
291 },
292 x('saml:AttributeValue', $mail),
293 ),
294 ),
295 ),
296 ),
297 ;
298  
299 return $response_xml;
300 }
301  
302 # canonicalise XML using W3C REC-xml-c14n-20010315 algorithm
303 # returns a string, not a XML::Spice chunk
304 sub _canonicalize_xml {
305 my ($self, $xml) = @_;
306  
307 my $xpath = '<XPath>(//. | //@* | //namespace::*)</XPath>';
308 return XML::CanonicalizeXML::canonicalize( $xml, $xpath, [], 0, 0 );
309 }
310  
311 sub get_form {
312 my ($self, $mail) = @_;
313  
314 my $saml_response = encode_base64( $self->get_response_xml( $mail ), q{} );
315  
316 my $html = join( q{},
317 qq{<form action="$ACS_URL" method="post">},
318 qq{<input type="hidden" name="SAMLResponse" value="$saml_response" />},
319 qq{<input type="hidden" name="TARGET" value="$ACS_URL" />},
320 qq{<input type="submit" name="Submit" value="Submit" />},
321 qq{</form>},
322 );
323  
324 return $html;
325 }
326  
327 __END__