blib/lib/Crypt/NamedKeys.pm

filter: Statementstmt 99.0% 108 / 109 Branchbran 68.4% 26 / 38 Conditioncond 72.7% 8 / 11 MC/DCmcdc 57.1% 4 / 7 Subroutinesub 100% 23 / 23 Podpod 100% 6 / 6 totaltotal 90.2% 175 / 194 CC 24 SCAR 12.8
CC
24
Cov
90%
decrypt_data
8.1
encrypt_data
6.1
_from_payload
3.1
CRAP 3.6
↑ Summary
1 package Crypt::NamedKeys;
2  
3 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 =head1 NAME
8  
9 Crypt::NamedKeys - A Crypt::CBC wrapper with key rotation support
10  
11 =head1 SYNOPSYS
12  
13 use Crypt::NamedKeys;
14 my $crypt = Crypt::NamedKeys->new(keyname => 'href');
15 my $encrypted = $crypt->encrypt_data(data => $href);
16 my $restored_href = $crypt->decrypt_data(
17 data => $encrypted->{data},
18 mac => $encrypted->{mac},
19 );
20  
21 =head1 DESCRIPTION
22  
23 This module provides functions to serialize data for transfer via non-protected
24 channels with encryption and data integrity protection. The module tracks key
25 number used to encrypt information so that keys can be rotated without making
26 data unreadable.
27  
28 =head1 CONFIGURATION AND KEY ROTATION
29  
30 The keys are stored in the keyfile, configurable as below. Keys are numbered
31 starting at 1. Numbers must never be reused. Typically key rotation will be
32 done in several steps, each with its own rollout. These steps MUST be done as
33 separate releases because otherwise keys may not be available to decrypt data,
34 and so things may not work.
35  
36 =head2 keyfile location
37  
38 The keyfile can be set using the keyfile($path) function. There is no default.
39  
40 =head2 keyfile format
41  
42 The format of the keyfile is YAML, following a basic structure of
43  
44 keyname:
45 [keyhashdef]
46  
47 so for example:
48  
49 cryptedfeed:
50 default_keynum: 9
51 none: queith7eeTh0teejaichoodobooX9ceechee9Sai9gauChiengaeraew3aDiehei
52 1: aePh8ahBaNg1bee6ohj3er5cuzeepoophai1oogohpoixothah4AuYiongu4ahta
53 2: oht1eep8uxoo1eeshaSaemee9aem5chahqueu0Aedaa7eeXae9aeghe5umoNah6a
54 3: chigh4veifoofe0Vohphee4ohkaef9giz2iaje2ahF4ohboSh6ifaiNgohwohchi
55 4: Ahphahmisaingo5Ietheangeegi5ia1uuF9taerooShaitoh1Eophig3ohziejet
56 5: oe5wi2equee6FeiZohjah2peas6Ahquohniefeimai0beip2waxeizoo1OhthohN
57 6: eigaezee3CeuC8phae4giph6Miqu6piy3Eideipahticesheij7se9eecai9fiez
58 7: DuuGhohViGh0Sheihahr6ce4Phuin7ahpaiSa5jaiphie3eiz8oa3dohrohghuow
59 8: ahfoniemah4boemeN8seJ7hohhualeetei7aegohhai5ohwahlohnah2Ee2Ewal1
60 9: Ceixei4shelohxee1ohdoochuliebael1kae8eit0Geeth1so9fohZi0cohs8go4
61 10: boreiDe0shueNgie7shai7ooc1yaeveiKeihuox0xahp1hai8phe7aephiel2oob
62  
63 In general we assume key spefications to use numeric keys within the named
64 key hash. This makes key rotation a lot easier and prevents reusing key
65 numbers.
66  
67 Key names may not contain = or -.
68  
69 All keys listed can be used for decryption (with the special 'none' key used if
70 no key number is specified in the cyphertex), but by default only the default
71 keynumber (default_keynum, in this case 9) is used for encrypting.
72  
73 The keynumber is specified in the resulting cyphertext so we know which key
74 to use for decrypting the cyphertext even if we don't try to decrypt it. This
75 allows:
76  
77 =over
78  
79 =item Key checking
80  
81 If you store cyphertext in your rdbms, you can check which keys are used before
82 you remove decryption support for a key.
83  
84 =item Orderly key rotation
85  
86 You can add a key, and later depricate it, managing the transition (and perhaps
87 even using logging to know when the old key is no longer needed).
88  
89 =back
90  
91 =head2 Step 1: Adding a New Key
92  
93 In many cases you need to be able to add and remove keys without requiring that
94 everything gets the new keys at the same time. For example if you have multiple
95 production systems, they are likely to get updated in series, and if you expect
96 that everyone gets the keys at the same time, timing issues may occur.
97  
98 For this reason, we recommend breaking up the encryption key rollout into a
99 number of steps. The first one is making sure that everyone can use the
100 new key to decrypt before anyone uses it to encrypt.
101  
102 The first release is by adding a new key so that it is available for decryption.
103  
104 For example, in the keyfile suppose one has:
105  
106 mykey:
107 default_keynum: 1
108 none: rsdfagtiaueIUPOIUYHH
109 1: rsdfagtiaueIUPOIUYHH
110  
111 We might add another line
112  
113 2: IRvswqerituq-HPIOHJHGdeewrwyugfrGRSe3eyy6te
114  
115 Once this file is released, the key number 2 will be available globally for
116 decryption purposes, but everything will still be encrypted using key number 1.
117  
118 This means it is safe then to go onto the second step.
119  
120 =head2 Step 2: Setting the new key as default
121  
122 Once the new keys have been released, the next step is to change the default
123 keynumber. Data encrypted in this way will be available even to servers waiting
124 to be updated because the keys have previously been rolled out. To do this,
125 simply change the default_keynum:
126  
127 mykey:
128 default_keynum: 1
129 1: rsdfagtiaueIUPOIUYHH
130 2: IRvswqerituq-HPIOHJHGdeewrwyugfrGRSe3eyy6te
131  
132 becomes:
133  
134 mykey:
135 default_keynum: 2
136 1: rsdfagtiaueIUPOIUYHH
137 2: IRvswqerituq-HPIOHJHGdeewrwyugfrGRSe3eyy6te
138  
139 Now all new data will be encrypted using keynumber 2.
140  
141 =head2 Step 3: Retiring the old key
142  
143 Once the old key is no longer being used, it can be retired by deleting the
144 row.
145  
146 =head2 The Special 'none' keynum
147  
148 For aes keys before the key versioning was introduced, there is no keynum
149 associated with the cyphertext, so we use this key.
150  
151 =cut
152  
153 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
154 4 ▶use Crypt::CBC;
Subroutine BEGIN: called CC=1 SCAR=0.0
155 4 ▶use Digest::SHA qw(hmac_sha256_base64 sha256);
Subroutine BEGIN: called CC=1 SCAR=0.0
156 4 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
157 4 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
158 4 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
159 4 ▶use String::Compare::ConstantTime;
Subroutine BEGIN: called CC=1 SCAR=0.0
160 4 ▶use YAML::XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
161  
162 4 our $VERSION = '1.13';
163  
164 =head1 CONFIGURATION PARAMETERS
165  
166 =head2 $Crypt::NamedKeys::Escape_Eq;
167  
168 Set to true, using local or not, if you want to encode with - instead of =
169  
170 Note that on decryption both are handled.
171  
172 =cut
173  
174 4 our $Escape_Eq = 0;
175  
176 =head1 PROPERTIES
177  
178 =head2 keynum
179  
180 Defaults to the default keynumber specified in the keyfile (for encryption)
181  
182 =cut
183  
184 4 has keynum => (
185 is => 'ro',
186 lazy => 1,
187 builder => '_default_keynum',
188 );
189  
190 =head2 keyname
191  
192 The name of the key in the keyfile.
193  
194 =cut
195  
196 4 has keyname => (
197 is => 'ro',
198 required => 1,
199 );
200  
201 4 my $keyfile;
202  
203 =head1 METHODS AND FUNCTIONS
204  
205 =cut
206  
207 =head2 Crypt::NamedKeys->keyfile($path)
208  
209 Can also be called as Crypt::NamedKeys::keyfile($path)
210  
211 Sets the path of the keyfile. It does not load or reload it (that is done on
212 demand or by reload_keyfile() below
213  
214 =cut
215  
216 1 ▶sub keyfile {
Subroutine keyfile: called CC=3 SCAR=11.3
Pod documented
217 1 my $file = shift;
218 1 ▶ $file = shift if $file eq __PACKAGE__;
Branch: 1 branch
BranchTrueFalseTotal
if $file eq __PACKAGE__ 1 0 1
219 1 ▶ return $keyfile unless $file;
Branch: 1 branch
BranchTrueFalseTotal
unless $file 0 1 1
220 1 $keyfile = $file;
221 1 return $keyfile;
222 }
223  
224 my $keyhash;
225  
226 30 ▶my $get_keyhash = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
227 30 ▶ return $keyhash if $keyhash;
Branch: 1 branch
BranchTrueFalseTotal
if $keyhash 29 1 30
228 1 reload_keyhash();
229 1 return $keyhash;
230 4 };
231  
232 =head2 reload_keyhash
233  
234 Can be called as an object method or function (i.e.
235 Crypt::NamedKeys::reload_keyhash()
236  
237 Loads or reloads the keyfile. Can be used via event handlers to reload
238 confguration as needed
239  
240 =cut
241  
242 1 ▶sub reload_keyhash {
Subroutine reload_keyhash: called CC=2 SCAR=7.1
Pod documented
243 1 ▶ croak 'No keyfile defined (use keyfile() to set)' unless $keyfile;
Branch: 1 branch
BranchTrueFalseTotal
unless $keyfile 0 1 1
244 1 $keyhash = YAML::XS::LoadFile($keyfile);
245 1 return scalar keys %$keyhash;
246 }
247  
248 28 ▶my $get_secret = sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
249 28 my %args = @_;
250 28 ▶ croak 'No key name specified' unless $args{keyname};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"keyname"} 0 28 28
251 28 ▶ croak 'No key number specified' unless $args{keynum};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"keynum"} 0 28 28
252 28 my $keytab = &$get_keyhash()->{$args{keyname}};
253 28 return $keytab->{$args{keynum}};
254 4 };
255  
256 2 ▶sub _default_keynum {
Subroutine _default_keynum: called CC=2 SCAR=7.0
257 2 my $self = shift;
258 2 my $keytab = &$get_keyhash()->{$self->keyname};
259 warn 'No default key found for ' . $self->keyname
260 2 ▶ unless $keytab->{default_keynum};
Branch: 1 branch
BranchTrueFalseTotal
unless $keytab->{"default_keynum"} 0 2 2
261 2 return $keytab->{default_keynum};
262 }
263  
264 12 ▶my $mac_secret = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
265 12 my %args = @_;
266 12 return sha256(&$get_secret(@_)); ## nocritic
267 4 };
268  
269 =head2 $self->encrypt_data(data => $data)
270  
271 Serialize I<$data> to JSON, encrypt it, and encode as base64. Also compute HMAC
272 code for the encrypted data. Returns hash reference with 'data' and 'mac'
273 elements.
274  
275 Args include
276  
277 =over
278  
279 =item data
280  
281 Data structure reference to be encrypted
282  
283 =item cypher
284  
285 Cypher to use (default: Rijndael)
286  
287 =back
288  
289 =cut
290  
291 4 my $json = JSON::MaybeXS->new;
292  
293 6 ▶sub encrypt_data {
Subroutine encrypt_data: called CC=6 SCAR=18.1
Pod documented
294 6 my ($self, %args) = @_;
295 6 ▶ croak "data argument is required and must be a reference" unless $args{data} and ref $args{data};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"data"} and ref $args{"data"} 2 4 6
Condition100%3/3
$args{"data"} and ref $args{"data"}
!ll&&!rl&&r
114
MC/DC100%2/2
$args{"data"} and ref $args{"data"}
$args{"data"} ref $args{"data"}
Truth table100%3/3
A and B
A= $args{"data"}B= ref $args{"data"}
ABresult
0X0
100
111
296 4 my $json_data = Encode::encode_utf8($json->encode($args{data}));
297 3 ▶ my $cypher = $args{cypher} || 'Rijndael';
Condition50%1/2
$args{'cypher'} || 'Rijndael'
l!l
03
MC/DC0%0/1
$args{'cypher'} || 'Rijndael'
$args{'cypher'}
Truth table50%1/2
A
A= $args{'cypher'}
Aresult
11
00
298 # Crypt::CBC generates random 8 bytes salt that it uses to
299 # derive IV and encryption key from $args{secret}. It uses
300 # the same algorythm as OpenSSL, the output is identical to
301 # openssl enc -e -aes-256-cbc -k $args{secret} -salt
302 3 my $cbc = Crypt::CBC->new(
303 -key => &$get_secret(
304 keyname => $self->keyname,
305 keynum => $self->keynum,
306 ),
307 -cipher => $cypher,
308 -salt => 1,
309 );
310 3 my $data = encode_base64($cbc->encrypt($json_data), '');
311 3 my $mac = hmac_sha256_base64(
312 $data,
313 &$mac_secret(
314 keyname => $self->keyname,
315 keynum => $self->keynum
316 ));
317 3 ▶ $data =~ s/=/-/g if $Escape_Eq;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::NamedKeys::Escape_Eq 0 3 3
318 3 ▶ $mac =~ s/=/-/g if $Escape_Eq;
Branch: 1 branch
BranchTrueFalseTotal
if $Crypt::NamedKeys::Escape_Eq 0 3 3
319 return {
320 3 data => $self->keynum . '*' . $data,
321 mac => $mac,
322 };
323 }
324  
325 =head2 $self->decrypt_data(data => $data, mac => $mac)
326  
327 Decrypt data encrypted using I<encrypt_data>. First checks HMAC code for data.
328 If data was not tampered, decrypts it and decodes from JSON. Returns data, or
329 undef if decryption failed.
330  
331 =cut
332  
333 12 ▶sub decrypt_data {
Subroutine decrypt_data: called CC=8 SCAR=20.9
Pod documented
334 12 my ($self, %args) = @_;
335 12 ▶ croak "method requires data and mac arguments" unless $args{data} and $args{mac};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"data"} and $args{"mac"} 3 9 12
Condition100%3/3
$args{"data"} and $args{"mac"}
!ll&&!rl&&r
219
MC/DC100%2/2
$args{"data"} and $args{"mac"}
$args{"data"} $args{"mac"}
Truth table100%3/3
A and B
A= $args{"data"}B= $args{"mac"}
ABresult
0X0
100
111
336 # if the data was tampered do not try to decrypt it
337  
338 9 $args{data} =~ s/-/=/g;
339 9 $args{mac} =~ s/-/=/g;
340 9 my ($keynum, $cyphertext) = split /\*/, $args{data}, 2;
341  
342 9 ▶ if (!$cyphertext) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cyphertext) 1 8 9
343 1 $cyphertext = $keynum;
344 1 $keynum = 'none';
345 }
346 9 my $secret = &$get_secret(
347 keynum => $keynum,
348 keyname => $self->keyname
349 );
350 9 ▶ return unless ($cyphertext and $secret);
Branch: 1 branch
BranchTrueFalseTotal
unless $cyphertext and $secret 0 9 9
Condition33%1/3
$cyphertext and $secret
!ll&&!rl&&r
009
MC/DC0%0/2
$cyphertext and $secret
$cyphertext $secret
Truth table33%1/3
A and B
A= $cyphertextB= $secret
ABresult
0X0
100
111
351 9 my $msg_mac = hmac_sha256_base64(
352 $cyphertext,
353 &$mac_secret(
354 keynum => $keynum,
355 keyname => $self->keyname,
356 ));
357 9 ▶ return unless String::Compare::ConstantTime::equals($msg_mac, $args{mac});
Branch: 1 branch
BranchTrueFalseTotal
unless &String::Compare::ConstantTime::equals($msg_mac, $args{"mac"}) 5 4 9
358  
359 4 my $cbc = Crypt::CBC->new(
360 -key => &$get_secret(
361 keynum => $keynum,
362 keyname => $self->keyname
363 ),
364 -cipher => 'Rijndael',
365 -salt => 1,
366 );
367 4 my $decrypted = $cbc->decrypt(decode_base64($cyphertext));
368 4 ▶ warn "Unable to decrypt $args{data} with keynum $keynum and keyname " . $self->keyname unless defined $decrypted;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $decrypted 0 4 4
369 4 my $data = $json->decode(Encode::decode_utf8($decrypted));
370 4 return $data;
371 }
372  
373 =head2 $self->encrypt_payload(data => $data)
374  
375 Encrypts data using I<encrypt_data> and returns result as a string including
376 both cyphertext and hmac in base-64 format. This can work on arbitrary data
377 structures, scalars, and references provided that the data can be serialized
378 as an attribute on a JSON document.
379  
380 =cut
381  
382 2 ▶sub _to_payload {
Subroutine _to_payload: called CC=1 SCAR=0.0
383 2 my ($data) = @_;
384 return {
385 2 crypt_json_payload => $data,
386 crypt_json_version => $VERSION,
387 };
388 }
389  
390 4 ▶sub _from_payload {
Subroutine _from_payload: called CC=3 SCAR=11.4
391 4 my ($payload) = @_;
392 4 ▶ return unless defined $payload;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $payload 2 2 4
393 2 ▶ return $payload->{crypt_json_payload} if exists $payload->{crypt_json_payload};
Branch: 1 branch
BranchTrueFalseTotal
if exists $payload->{"crypt_json_payload"} 2 0 2
394 0 return $payload;
395 }
396  
397 2 ▶sub encrypt_payload {
Subroutine encrypt_payload: called CC=1 SCAR=0.0
Pod documented
398 2 my ($self, %args) = @_;
399 2 $args{data} = _to_payload($args{data});
400 2 my $enc = $self->encrypt_data(%args);
401 2 my $res = $enc->{data};
402 2 $res .= '.' . $enc->{mac};
403 2 return $res;
404 }
405  
406 =head2 $self->decrypt_payload(value => $value)
407  
408 Accepts payload encrypted with I<encrypt_payload>, checks HMAC and decrypts
409 the value. Returns decripted value or undef if check or decryption has failed.
410  
411 =cut
412  
413 5 ▶sub decrypt_payload {
Subroutine decrypt_payload: called CC=3 SCAR=11.0
Pod documented
414 5 my ($self, %args) = @_;
415 5 ▶ return unless $args{value}; # nothing to decrypt
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"value"} 0 5 5
416 5 ▶ $args{value} =~ /^([A-Za-z0-9+\/*]+[=-]*)\.([A-Za-z0-9+\/-=]+)$/ or return;
Branch: 1 branch
BranchTrueFalseTotal
$args{"value"} =~ m[^([A-Za-z0-9+/*]+[=-]*)\.([A-Za-z0-9+/-=]+)$] or return 4 1 5
417 4 my ($data, $mac) = ($1, $2);
418 4 return _from_payload(
419 $self->decrypt_data(
420 data => $data,
421 mac => $mac,
422 ));
423 }
424  
425 4 1;
↑ Summary