OpenToken.pm

filter: Statementstmt 96.5% 167 / 173 Branchbran 56.4% 35 / 62 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 31 / 31 Podpod 100% 2 / 2 totaltotal 87.6% 235 / 268 CC 33 SCAR 15.9
CC
33
Cov
86%
parse
10.3
create
9.4
_rand_iv
8.6
CRAP 4.9
↑ Summary OpenToken/Serializer.pm »
1 package Crypt::OpenToken;
2  
3 6 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 6 ▶use Fcntl qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
5 6 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 6 ▶use MIME::Base64 qw(encode_base64 decode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 6 ▶use Compress::Zlib;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use Digest::SHA1;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 6 ▶use Digest::HMAC_SHA1;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 6 ▶use Data::Dumper qw(Dumper);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 6 ▶use Crypt::OpenToken::KeyGenerator;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 6 ▶use Crypt::OpenToken::Serializer;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 6 ▶use Crypt::OpenToken::Token;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 6 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 6 our $VERSION = '0.11';
17 6 our $DEBUG = 0;
18  
19 # shared encryption password
20 6 has 'password' => (
21 is => 'rw',
22 isa => 'Str',
23 required => 1,
24 );
25  
26 # http://tools.ietf.org/html/draft-smith-opentoken-02
27 6 ▶use constant TOKEN_PACK =>
Subroutine BEGIN: called CC=1 SCAR=0.0
28 'a3'. # literal 'OTK'
29 'C'. # version (unsigned-byte)
30 'C'. # cipher
31 'a20'. # hmac string (20 bytes for SHA1/SHA1_HMAC)
32 'C/a*'. # IV (with unsigned-byte length-prefix)
33 'C/a*'. # key (with unsigned-byte length-prefix)
34 6 'n/a*'; # payload (with network-endian short length-prefix)
35  
36 # List of ciphers supported by OpenToken
37 6 ▶use constant CIPHER_NULL => 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 6 ▶use constant CIPHER_AES256 => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 6 ▶use constant CIPHER_AES128 => 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 6 ▶use constant CIPHER_DES3 => 3;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 6 ▶use constant CIPHERS => [qw(null AES256 AES128 DES3)];
Subroutine BEGIN: called CC=1 SCAR=0.0
42  
43 16 ▶sub _cipher {
Subroutine _cipher: called CC=4 SCAR=14.2
44 16 my ($self, $cipher) = @_;
45  
46 16 my $impl = CIPHERS->[$cipher];
47 16 ▶ croak "unsupported OTK cipher; '$cipher'" unless ($impl);
Branch: 1 branch
BranchTrueFalseTotal
unless $impl 1 15 16
48  
49 15 my $mod = "Crypt::OpenToken::Cipher::$impl";
50 15 eval "require $mod";
51 15 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 15 15
52 0 croak "unable to load cipher '$impl'; $@";
53 }
54 15 ▶ print "selected cipher: $impl\n" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 15 15
55 15 return $mod->new;
56 }
57  
58 10 ▶sub parse {
Subroutine parse: called CC=9 SCAR=23.3
Pod documented
59 10 my ($self, $token_str) = @_;
60 10 ▶ print "parsing token: $token_str\n" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 10 10
61  
62 # base64 decode the OTK
63 10 $token_str = $self->_base64_decode($token_str);
64  
65 # unpack the OTK token into its component fields
66 10 my $fields = $self->_unpack($token_str);
67 10 ▶ print "unpacked fields: " . Dumper($fields) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 10 10
68  
69 # get the chosen cipher, and make sure the IV length is valid
70 10 my $cipher = $self->_cipher( $fields->{cipher} );
71 10 my $iv_len = $fields->{iv_len};
72 10 ▶ unless ($iv_len == $cipher->iv_len) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($iv_len == $cipher->iv_len) 0 10 10
73 0 croak "invalid IV length ($iv_len) for selected cipher ($cipher)";
74 }
75  
76 # generate a decryption key for this cipher
77 10 my $key = Crypt::OpenToken::KeyGenerator::generate(
78 $self->password, $cipher->keysize,
79 );
80 10 ▶ print "generated key: " . encode_base64($key) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 10 10
81  
82 # decrypt the payload
83 10 my $crypto = $cipher->cipher($key, $fields->{iv});
84 10 my $decrypted = $crypto->decrypt($fields->{payload});
85 10 ▶ print "decrypted payload: " . encode_base64($decrypted) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 10 10
86  
87 # uncompress the payload
88 10 my $plaintext = Compress::Zlib::uncompress($decrypted);
89 10 ▶ print "plaintext:\n$plaintext\n" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 10 10
90  
91 # verify the HMAC
92 10 my $hmac = $self->_create_hmac($key, $fields, $plaintext);
93 10 ▶ unless ($hmac eq $fields->{hmac}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($hmac eq $fields->{"hmac"}) 0 10 10
94 0 croak "invalid HMAC";
95 }
96  
97 # deserialize the plaintext payload
98 10 my %params = Crypt::OpenToken::Serializer::thaw($plaintext);
99 10 ▶ print "payload: " . Dumper(\%params) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 10 10
100 10 $fields->{data} = \%params;
101  
102 # instantiate the token object
103 10 my $token = Crypt::OpenToken::Token->new($fields);
104 10 return $token;
105 }
106  
107 6 ▶sub create {
Subroutine create: called CC=9 SCAR=22.4
Pod documented
108 6 my ($self, $cipher, $data) = @_;
109  
110 # get the chosen cipher, and generate a random IV for the encryption
111 6 my $cipher_obj = $self->_cipher($cipher);
112 5 my $iv = '';
113 5 ▶ if (my $len = $cipher_obj->iv_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $len = $cipher_obj->iv_len) 4 1 5
114 4 $iv = _rand_iv($len);
115 }
116  
117 # generate an encryption key for this cipher
118 5 my $key = Crypt::OpenToken::KeyGenerator::generate(
119 $self->password, $cipher_obj->keysize,
120 );
121 5 ▶ print "generated key: " . encode_base64($key) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 5 5
122  
123 # serialize the data into a payload
124 5 my $plaintext = Crypt::OpenToken::Serializer::freeze(%{$data});
125 5 ▶ print "plaintext:\n$plaintext\n" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 5 5
126  
127 # compress the payload
128 5 my $compressed = Compress::Zlib::compress($plaintext);
129 5 ▶ print "compressed plaintext: " . encode_base64($compressed) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 5 5
130  
131 # encrypt the token, w/PKCS5 padding
132 5 my $crypto = $cipher_obj->cipher($key, $iv);
133 5 my $padded = $self->_pkcs5_padded($compressed, $crypto->blocksize());
134 5 my $encrypted = $crypto->encrypt($padded);
135 5 ▶ print "encrypted payload: " . encode_base64($encrypted) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 5 5
136  
137 # gather up all of the fields
138 5 my %fields = (
139 version => 1,
140 cipher => $cipher,
141 iv_len => bytes::length($iv),
142 iv => $iv,
143 key_len => bytes::length($key),
144 key => $key,
145 payload_len => bytes::length($encrypted),
146 payload => $encrypted,
147 );
148  
149 # create an HMAC
150 5 my $hmac = $self->_create_hmac($key, \%fields, $plaintext);
151 5 ▶ print "calculated hmac: " . encode_base64($hmac) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 5 5
152 5 $fields{hmac} = $hmac;
153  
154 # pack the OTK token together from its component fields
155 5 my $token = $self->_pack(%fields);
156 5 ▶ print "binary token: $token\n" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 5 5
157  
158 # base64 encode the token
159 5 my $token_str = $self->_base64_encode($token);
160 5 ▶ print "token created: $token_str\n" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::OpenToken::DEBUG 0 5 5
161 5 return $token_str;
162 }
163  
164 4 ▶sub _rand_iv {
Subroutine _rand_iv: called CC=7 SCAR=21.5
165 4 my $len = shift;
166 4 my $iv = '';
167 6 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
168  
169 # try to use a reasonably unguessable source of random bytes.
170 # /dev/random isn't needed for IVs in general.
171 4 eval {
172 4 ▶ sysopen my $urand, '/dev/urandom', Fcntl::O_RDONLY() or die $!;
Branch: 1 branch
BranchTrueFalseTotal
sysopen my $urand, "/dev/urandom", 0 or die $! 4 0 4
173 4 ▶ binmode $urand or die $!;
Branch: 1 branch
BranchTrueFalseTotal
binmode $urand or die $! 4 0 4
174 4 ▶ sysread $urand, $iv, $len or die $!;
Branch: 1 branch
BranchTrueFalseTotal
sysread $urand, $iv, $len or die $! 4 0 4
175 };
176 4 ▶ warn __PACKAGE__."::_rand_iv can't use /dev/urandom: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4 4
177  
178 # fill up with less random bytes
179 4 ▶ if (length($iv) < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $iv < $len) 0 4 4
180 0 ▶ $iv .= chr(int(rand(256))) until (length($iv) == $len);
Branch: 1 branch
BranchTrueFalseTotal
length $iv == $len or do { $iv .= chr(int rand 256) } 0 0 0
181 }
182  
183 4 return $iv;
184 }
185  
186 5 ▶sub _pkcs5_padded {
Subroutine _pkcs5_padded: called CC=2 SCAR=7.0
187 5 my ($self, $data, $bsize) = @_;
188 5 ▶ if ($bsize) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bsize) 5 0 5
189 5 my $data_len = bytes::length($data);
190 5 my $pad_needed = $bsize - ($data_len % $bsize);
191 5 $data .= chr($pad_needed) x $pad_needed;
192 }
193 5 return $data;
194 }
195  
196 15 ▶sub _create_hmac {
Subroutine _create_hmac: called CC=4 SCAR=13.9
197 15 my ($self, $key, $fields, $plaintext) = @_;
198  
199 # NULL cipher uses SHA1 digest, all other ciphers use an HMAC_SHA1
200 my $digest =
201 15 ▶ ($fields->{cipher} == CIPHER_NULL)
Branch: 1 branch
BranchTrueFalseTotal
$fields->{'cipher'} == 0 ? : 3 12 15
202 ? Digest::SHA1->new()
203 : Digest::HMAC_SHA1->new($key);
204  
205 15 $digest->add(chr($fields->{version}));
206 15 $digest->add(chr($fields->{cipher}));
207 15 ▶ $digest->add($fields->{iv}) if ($fields->{iv_len} > 0);
Branch: 1 branch
BranchTrueFalseTotal
if $fields->{"iv_len"} > 0 12 3 15
208 15 ▶ $digest->add($fields->{key}) if ($fields->{key_len} > 0);
Branch: 1 branch
BranchTrueFalseTotal
if $fields->{"key_len"} > 0 8 7 15
209 15 $digest->add($plaintext);
210  
211 15 return $digest->digest;
212 }
213  
214 10 ▶sub _unpack {
Subroutine _unpack: called CC=3 SCAR=11.7
215 10 my ($self, $token_str) = @_;
216 6 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
217  
218 10 my ($otk, $ver, $cipher, $hmac, $iv, $key, $payload)
219 = unpack(TOKEN_PACK, $token_str);
220 10 ▶ unless ($otk eq 'OTK') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($otk eq "OTK") 0 10 10
221 0 croak "invalid literal identifier in OTK; '$otk'";
222 }
223 10 ▶ unless ($ver == 1) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ver == 1) 0 10 10
224 0 croak "unsupported OTK version; '$ver'";
225 }
226  
227 return {
228 10 version => $ver,
229 cipher => $cipher,
230 hmac => $hmac,
231 iv_len => length($iv),
232 iv => $iv,
233 key_len => length($key),
234 key => $key,
235 payload_len => length($payload),
236 payload => $payload,
237 };
238 }
239  
240 5 ▶sub _pack {
Subroutine _pack: called CC=2 SCAR=6.9
241 5 my ($self, %fields) = @_;
242  
243 # truncate to specified lengths
244 5 for (qw(iv key payload)) {
245 15 substr($fields{$_}, $fields{ $_ . "_len" }) = '';
246 }
247  
248 my $token_str = pack(TOKEN_PACK,
249 5 'OTK', @fields{qw(version cipher hmac iv key payload)}
250 );
251 5 return $token_str;
252 }
253  
254 # Custom Base64 decoding; OTK has some oddities in how they encode things
255 # using Base64.
256 11 ▶sub _base64_decode {
Subroutine _base64_decode: called CC=1 SCAR=0.0
257 11 my ($self, $token_str) = @_;
258  
259 # fixup: convert trailing "*"s into "="s (OTK specific encoding)
260 11 $token_str =~ s/(\*+)$/'=' x length($1)/e;
261  
262 # fixup: convert "_" to "/" (PingId PHP bindings encode this way)
263 # fixup: convert "-" to "+" (PingId PHP bindings encode this way)
264 11 $token_str =~ tr{_-}{/+};
265  
266 # Base64 decode it, and we're done.
267 11 my $decoded = decode_base64($token_str);
268 11 return $decoded;
269 }
270  
271 # Custom Base64 encoding; OTK has some oddities in how they encode things
272 # using Base64.
273 6 ▶sub _base64_encode {
Subroutine _base64_encode: called CC=1 SCAR=0.0
274 6 my ($self, $token_str) = @_;
275  
276 # Base64 encode the token string
277 6 my $encoded = encode_base64($token_str, '');
278  
279 # fixup: convert "+" to "-" (PingId PHP bindings encode this way)
280 # fixup: convert "/" to "_" (PingId PHP bindings encode this way)
281 6 $encoded =~ tr{/+}{_-};
282  
283 # fixup: convert trailing "="s to "*"s (OTK specific encoding)
284 6 $encoded =~ s/(\=+)$/'*' x length($1)/e;
285  
286 6 return $encoded;
287 }
288  
289 6 ▶no Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
290  
291 6 1;
292  
293 =for stopwords OpenTokens Socialtext PingFederate TripleDES Base64 decrypts merchantability
294  
295 =head1 NAME
296  
297 Crypt::OpenToken - Perl implementation of Ping Identity's "OpenToken"
298  
299 =head1 SYNOPSIS
300  
301 use Crypt::OpenToken;
302  
303 my $data = {
304 foo => 'bar',
305 bar => 'baz',
306 };
307  
308 # create an OpenToken factory based on a given shared password
309 my $factory = Crypt::OpenToken->new(password => 'abc123');
310  
311 # encrypt a hash-ref of data into an OpenToken.
312 my $token_str = $factory->create(
313 Crypt::OpenToken::CIPHER_AES128,
314 $data,
315 );
316  
317 # decrypt an OpenToken, check if its valid, and get data back out
318 my $token = $factory->parse($token_str);
319 if ($token->is_valid) {
320 $data = $token->data();
321 }
322  
323 =head1 DESCRIPTION
324  
325 This module provides a Perl implementation of the "OpenToken" standard as
326 defined by Ping Identity in their IETF Draft.
327  
328 =head1 METHODS
329  
330 =over
331  
332 =item Crypt::OpenToken->new(password => $password)
333  
334 Instantiates a new OpenToken factory, which can encrypt/decrypt OpenTokens
335 using the specified shared C<$password>.
336  
337 =item $factory->create($cipher, $data)
338  
339 Encrypts the given hash-ref of C<$data> using the specified C<$cipher> (which
340 should be one of the C<CIPHER_*> constants).
341  
342 Returns back to the caller a Base64 encoded string which represents the
343 OpenToken.
344  
345 B<NOTE:> during the encryption of the OpenToken, a random Initialization
346 Vector will be selected; as such it is I<not> possible to encrypt the same
347 data more than once and get the same OpenToken back.
348  
349 =item $factory->parse($token)
350  
351 Decrypts a Base64 encoded OpenToken, returning a C<Crypt::OpenToken::Token>
352 object back to the caller. Throws a fatal exception in the event of an error.
353  
354 It is the callers responsibility to then check to see if the token itself is
355 valid (see L<Crypt::OpenToken::Token> for details).
356  
357 =back
358  
359 =head1 CONSTANTS
360  
361 The following constant values are available for selecting an encryption cipher
362 to use:
363  
364 =over
365  
366 =item Crypt::OpenToken::CIPHER_NULL
367  
368 "Null" encryption (e.g. no encryption whatsoever). Requires C<Crypt::NULL>.
369  
370 =item Crypt::OpenToken::CIPHER_AES256
371  
372 "AES" encryption, 256-bit. Requires C<Crypt::Rijndael>.
373  
374 =item Crypt::OpenToken::CIPHER_AES128
375  
376 "AES" encryption, 128-bit. Requires C<Crypt::Rijndael>.
377  
378 =item Crypt::OpenToken::CIPHER_DES3
379  
380 "TripleDES" encryption, 168-bit. Requires C<Crypt::DES>.
381  
382 =back
383  
384 =for Pod::Coverage CIPHERS TOKEN_PACK
385  
386 =head1 CAVEATS
387  
388 =over
389  
390 =item *
391  
392 This module does not (yet) support the "obfuscate password" option that is
393 configurable within PingFederate's OpenToken adapter.
394  
395 =back
396  
397 =head1 AUTHOR
398  
399 Graham TerMarsch (cpan@howlingfrog.com)
400  
401 Shawn Devlin (shawn.devlin@socialtext.com)
402  
403 =head2 Contributors
404  
405 Thanks to those who have provided feedback, comments, and patches:
406  
407 Jeremy Stashewsky
408 Travis Spencer
409  
410 =head2 Sponsors
411  
412 B<BIG> thanks also go out to those who sponsored C<Crypt::OpenToken>:
413  
414 =over
415  
416 =item Socialtext
417  
418 Thanks for sponsoring the initial development of C<Crypt::OpenToken>, and then
419 being willing to release it to the world.
420  
421 =item Ping Identity
422  
423 Thanks for your assistance during the initial development, providing feedback
424 along the way, and answering our questions as they arose.
425  
426 =back
427  
428 =head1 COPYRIGHT & LICENSE
429  
430 =head2 Crypt::OpenToken
431  
432 C<Crypt::OpenToken> is Copyright (C) 2010, Socialtext, and is released under
433 the Artistic-2.0 license.
434  
435 =head2 OpenToken specification
436  
437 The OpenToken specification is Copyright (C) 2007-2010 Ping Identity
438 Corporation, and released under the MIT License:
439  
440 =over
441  
442 Permission is hereby granted, free of charge, to any person obtaining a copy
443 of this software and associated documentation files (the "Software"), to deal
444 in the Software without restriction, including without limitation the rights
445 to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
446 copies of the Software, and to permit persons to whom the Software is
447 furnished to do so, subject to the following conditions:
448  
449 The above copyright notice and this permission notice shall be included in all
450 copies or substantial portions of the Software.
451  
452 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
453 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
454 FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
455 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
456 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
457 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
458 SOFTWARE.
459  
460 =back
461  
462 =head1 SEE ALSO
463  
464 =over
465  
466 =item L<http://tools.ietf.org/html/draft-smith-opentoken-02>
467  
468 =item L<http://www.pingidentity.com/opentoken>
469  
470 =back
471  
472 =cut
↑ Summary OpenToken/Serializer.pm »