| 1 | package Dancer2::Session::Pg::Cipher; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Moo::Role; | ||
| 7 | use Carp qw( croak ); | ||
| 8 | use Module::Runtime qw( use_module ); | ||
| 9 | |||
| 10 | our $VERSION = '0.002'; | ||
| 11 | |||
| 12 | requires qw( cipher_id cipher_name key_bytes iv_bytes tag_bytes seal unseal ); | ||
| 13 | |||
| 14 | # A plugged-in cipher is security-critical code this module did not write, so a | ||
| 15 | # candidate is exercised once when the engine is built rather than trusted until | ||
| 16 | # somebody's first login. Three ways one fails here: it describes itself | ||
| 17 | # impossibly, it cannot read back what it wrote, or it accepts a payload that has | ||
| 18 | # been altered -- the last being the whole reason only AEAD modes are allowed. | ||
| 19 | sub cipher_self_check { ## no critic (Subroutines::ProhibitExcessComplexity) -- one linear list of guards; splitting it to satisfy a metric would hide the sequence | ||
| 20 | my ($self) = @_; | ||
| 21 | |||
| 22 | # Called as both a class and an instance method, so take the name either way | ||
| 23 | # without the `ref $x || $x` idiom, which reads as a typo to half of Perl. | ||
| 24 | my $class = ref $self ? ref $self : $self; | ||
| 25 | |||
| 26 | for my $method (qw( cipher_id key_bytes iv_bytes tag_bytes )) { | ||
| 27 | my $value = $self->$method; | ||
| 28 | croak sprintf '%s: %s must be a positive integer (got %s)', $class, $method, ( defined $value ? "'$value'" : 'undef' ) | ||
| 29 | if !defined $value || $value !~ m/\A[0-9]+\z/msx || $value < 1; ## no critic (RegularExpressions::ProhibitEnumeratedClasses) -- [0-9] is ASCII-only; \d and [[:digit:]] both match Unicode digits | ||
| 30 | } | ||
| 31 | |||
| 32 | croak sprintf '%s: cipher_id must be in 1..255 (got %d)', $class, $self->cipher_id | ||
| 33 | if $self->cipher_id > 255; | ||
| 34 | |||
| 35 | my $name = $self->cipher_name; | ||
| 36 | croak "$class: cipher_name must be a non-empty string" | ||
| 37 | if !defined $name || !length $name; | ||
| 38 | |||
| 39 | my $key = 'K' x $self->key_bytes; | ||
| 40 | my $iv = 'N' x $self->iv_bytes; | ||
| 41 | my $plain = 'Dancer2::Session::Pg cipher self check'; | ||
| 42 | my $aad = 'session-id-one'; | ||
| 43 | |||
| 44 | my ( $ciphertext, $tag ) = $self->seal( $key, $iv, $plain, $aad ); | ||
| 45 | |||
| 46 | croak "$class: seal returned no ciphertext" | ||
| 47 | if !defined $ciphertext || !length $ciphertext; | ||
| 48 | croak sprintf '%s: seal returned a %d-byte tag but tag_bytes says %d', $class, | ||
| 49 | ( defined $tag ? length $tag : 0 ), $self->tag_bytes | ||
| 50 | if !defined $tag || length $tag != $self->tag_bytes; | ||
| 51 | |||
| 52 | # THE ONE THING THE REST OF THIS CHECK WOULD MISS. Everything above and | ||
| 53 | # below tests AUTHENTICATION -- that the tag is real, that altered input is | ||
| 54 | # refused, that the additional data is bound in. A cipher that computes a | ||
| 55 | # genuine MAC over the plaintext and then returns the plaintext as its | ||
| 56 | # ciphertext passes every one of those, round trips perfectly, refuses | ||
| 57 | # every forgery -- and writes sessions to the database IN THE CLEAR. | ||
| 58 | # | ||
| 59 | # That is not a hypothetical shape: it is what an encrypt-then-MAC wrapper | ||
| 60 | # degrades into if the author returns the wrong variable, and the failure | ||
| 61 | # is invisible from outside because every test of correctness still | ||
| 62 | # passes. For a module whose only purpose is encryption at rest, not | ||
| 63 | # checking that the cipher encrypts is the one omission that matters. | ||
| 64 | croak "$class: seal returned the plaintext unchanged as its ciphertext, so every " | ||
| 65 | . 'session would be stored in the clear. The tag may well be sound -- this is ' | ||
| 66 | . 'what an encrypt-then-MAC implementation looks like when it returns the ' | ||
| 67 | . 'plaintext instead of the encrypted bytes.' | ||
| 68 | if $ciphertext eq $plain; | ||
| 69 | |||
| 70 | my $back = eval { $self->unseal( $key, $iv, $ciphertext, $tag, $aad ) }; | ||
| 71 | croak "$class: unseal did not return what seal was given" | ||
| 72 | if !defined $back || $back ne $plain; | ||
| 73 | |||
| 74 | # The tag is the point, and the bar is ANY defined result rather than "not | ||
| 75 | # the original plaintext". An unauthenticated stream mode hands back | ||
| 76 | # *modified* plaintext for modified input, which is not a curiosity: it is | ||
| 77 | # the attack. Flipping the bits under `"admin":0` to make it `"admin":1` | ||
| 78 | # needs no key, and a session store that deserialises the result and then | ||
| 79 | # trusts it has given the whole thing away. So a cipher that returns anything | ||
| 80 | # at all for input it did not authenticate is refused here. | ||
| 81 | for my $case ( [ 'ciphertext', 0 ], [ 'tag', 1 ] ) { | ||
| 82 | my ( $part, $is_tag ) = @{$case}; | ||
| 83 | my @args = ( $ciphertext, $tag ); | ||
| 84 | my $i = $is_tag ? 1 : 0; | ||
| 85 | |||
| 86 | # 4-argument substr rather than the lvalue form, which Perl::Critic | ||
| 87 | # dislikes and which reads worse here anyway. | ||
| 88 | my $flipped = ( ord substr $args[$i], -1 ) ^ 0xFF; | ||
| 89 | substr $args[$i], -1, 1, chr $flipped; | ||
| 90 | |||
| 91 | my $forged = eval { $self->unseal( $key, $iv, @args, $aad ) }; | ||
| 92 | croak "$class: unseal returned data for a payload whose $part had been altered -- not an authenticated cipher" | ||
| 93 | if defined $forged; | ||
| 94 | } | ||
| 95 | |||
| 96 | # LAST, because it is the narrower fault: a cipher that fails the checks | ||
| 97 | # above does not authenticate at all, and saying so is more use than saying | ||
| 98 | # it mishandled the additional data. | ||
| 99 | # | ||
| 100 | # A cipher that accepts the additional data and then ignores it is the | ||
| 101 | # dangerous kind of wrong -- every round trip works, nothing looks amiss, | ||
| 102 | # and the engine's binding of a payload to its session id silently does not | ||
| 103 | # exist. That binding is what stops somebody with write access to the table | ||
| 104 | # moving an administrator's sealed payload into their own row, so it is | ||
| 105 | # tested rather than taken on trust. | ||
| 106 | my $wrong_aad = eval { $self->unseal( $key, $iv, $ciphertext, $tag, 'session-id-two' ) }; | ||
| 107 | croak "$class: unseal IGNORED the additional authenticated data -- " | ||
| 108 | . 'a payload sealed for one session id would open under another' | ||
| 109 | if defined $wrong_aad; | ||
| 110 | |||
| 111 | $self->_check_reserved_cipher_id( $key, $iv, $plain, $aad ); | ||
| 112 | |||
| 113 | return 1; | ||
| 114 | } | ||
| 115 | |||
| 116 | # WHAT CLAIMING A BUILT-IN ID PROMISES, enforced rather than documented. | ||
| 117 | # | ||
| 118 | # The id is one byte of every stored row and it is how a reader decides which | ||
| 119 | # cipher to hand a payload to. So a class claiming a built-in id is making a | ||
| 120 | # specific promise -- "I am that cipher, byte for byte" -- and the reason to | ||
| 121 | # allow it at all is the legitimate case: a different implementation of the same | ||
| 122 | # algorithm, hardware-accelerated or audited or vendored, that must read every | ||
| 123 | # row the original wrote. | ||
| 124 | # | ||
| 125 | # The accident is the common case, though. The documentation used to say "an | ||
| 126 | # integer in 1..255" and nothing else, so an author writing a genuinely new | ||
| 127 | # cipher would reasonably pick 1 -- and then every row AES-128-GCM had written | ||
| 128 | # became unreadable, with the header agreeing about the id and the tag failing. | ||
| 129 | # Prose does not stop that. A round trip does. | ||
| 130 | # | ||
| 131 | # Both directions, because both happen: the engine must read what the built-in | ||
| 132 | # wrote before the swap, and the built-in must read what the claimant wrote if it | ||
| 133 | # is ever removed. A cipher that passes only one way is not a drop-in. | ||
| 134 | # The core reserves 1..127; 128..255 belongs to whoever deploys a cipher of | ||
| 135 | # their own, where a collision is theirs to manage. | ||
| 136 | use constant CORE_ID_MAX => 128; | ||
| 137 | |||
| 138 | my %CORE_CIPHER_FOR_ID = ( | ||
| 139 | 1 => [ 'Dancer2::Session::Pg::Cipher::AESGCM', key_bytes => 16 ], | ||
| 140 | 2 => [ 'Dancer2::Session::Pg::Cipher::AESGCM', key_bytes => 24 ], | ||
| 141 | 3 => [ 'Dancer2::Session::Pg::Cipher::AESGCM', key_bytes => 32 ], | ||
| 142 | 4 => ['Dancer2::Session::Pg::Cipher::ChaCha20Poly1305'], | ||
| 143 | ); | ||
| 144 | |||
| 145 | sub _check_reserved_cipher_id { | ||
| 146 | my ( $self, $key, $iv, $plain, $aad ) = @_; | ||
| 147 | |||
| 148 | my $class = ref $self ? ref $self : $self; | ||
| 149 | my $id = $self->cipher_id; | ||
| 150 | my $spec = $CORE_CIPHER_FOR_ID{$id}; | ||
| 151 | |||
| 152 | # 5..127 is reserved for built-ins that do not exist yet. Refusing it is the | ||
| 153 | # point: a third-party cipher that takes id 5 today works perfectly until | ||
| 154 | # this distribution ships a built-in with that id, and then two different | ||
| 155 | # formats share one header byte and the older rows become unreadable. There | ||
| 156 | # is no interop check to offer, because there is nothing yet to interop | ||
| 157 | # with -- so the only safe answer is no. | ||
| 158 | croak sprintf '%s: cipher_id %d is in the range 1..127, which this distribution ' | ||
| 159 | . 'reserves for its own ciphers -- %d is not in use yet, and claiming it now ' | ||
| 160 | . 'would collide with a future built-in and make these rows unreadable. ' | ||
| 161 | . 'Pick an unused id in 128..255', $class, $id, $id | ||
| 162 | if !$spec && $id < CORE_ID_MAX; | ||
| 163 | |||
| 164 | return 1 if !$spec; # 128..255: the third-party range | ||
| 165 | my ( $core_class, @core_args ) = @{$spec}; | ||
| 166 | return 1 if $class eq $core_class; # the built-in itself | ||
| 167 | |||
| 168 | my $core = use_module($core_class)->new(@core_args); | ||
| 169 | |||
| 170 | # Declared lengths first: a mismatch here is the same fault with a clearer | ||
| 171 | # name than a round trip that merely fails. | ||
| 172 | for my $method (qw( key_bytes iv_bytes tag_bytes )) { | ||
| 173 | next if $self->$method == $core->$method; | ||
| 174 | croak sprintf '%s: cipher_id %d is %s, whose %s is %d, but this cipher says %d. ' | ||
| 175 | . 'An id identifies one stored format; pick an unused id in 128..255 instead', | ||
| 176 | $class, $id, $core->cipher_name, $method, $core->$method, $self->$method; | ||
| 177 | } | ||
| 178 | |||
| 179 | my $fail = | ||
| 180 | sprintf '%s: cipher_id %d belongs to %s, and claiming it means being able to ' | ||
| 181 | . 'read and write that cipher\'s rows byte for byte. This cipher cannot (%%s). ' | ||
| 182 | . 'If it is a NEW cipher rather than a replacement, pick an unused id in 128..255', | ||
| 183 | $class, $id, $core->cipher_name; | ||
| 184 | |||
| 185 | my ( $core_ct, $core_tag ) = $core->seal( $key, $iv, $plain, $aad ); | ||
| 186 | my $read = eval { $self->unseal( $key, $iv, $core_ct, $core_tag, $aad ) }; | ||
| 187 | croak sprintf $fail, 'it cannot read what ' . $core->cipher_name . ' wrote' | ||
| 188 | if !defined $read || $read ne $plain; | ||
| 189 | |||
| 190 | my ( $own_ct, $own_tag ) = $self->seal( $key, $iv, $plain, $aad ); | ||
| 191 | my $back = eval { $core->unseal( $key, $iv, $own_ct, $own_tag, $aad ) }; | ||
| 192 | croak sprintf $fail, $core->cipher_name . ' cannot read what it wrote' | ||
| 193 | if !defined $back || $back ne $plain; | ||
| 194 | |||
| 195 | return 1; | ||
| 196 | } | ||
| 197 | |||
| 198 | 1; | ||
| 199 | |||
| 200 | __END__ |