This repository was archived by the owner on Apr 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathMigrateEncryptionCommand.php
357 lines (303 loc) · 11.5 KB
/
MigrateEncryptionCommand.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
<?php
/**
* src/Console/Commands/MigrateEncryptionCommand.php.
*
* @author Austin Heap <me@austinheap.com>
* @version v0.1.0
*/
declare(strict_types=1);
namespace AustinHeap\Database\Encryption\Console\Commands;
use Exception;
use RuntimeException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Encryption\Encrypter;
use Illuminate\Support\Facades\Config;
use AustinHeap\Database\Encryption\EncryptionFacade as DatabaseEncryption;
/**
* Class MigrateEncryptionCommand.
*
* This console job locates data in the database that contains data encrypted
* using a wrong/deprecated encryption key, and re-encrypts it using the
* correct/new encryption key.
*
* It can be used to fix badly encrypted data, or can be used to decrypt data using
* one key and re-encrypt using another key.
*
* ### Installation
*
* * Override this class and change the setupKeys() function to set the keys that
* are to be used ($old_keys and $new_key) as well as the array of $table names.
*
* * Add 'App\Console\Commands\MigrateEncryptionCommand' to the $commands array in
* your 'App\Console\Kernel' package.
*
* ### Example
*
* <code>
* php artisan migrate:encryption
* </code>
*/
class MigrateEncryptionCommand extends \Illuminate\Console\Command
{
/**
* The stats of the last run of the console command.
*
* @var array
*/
private static $stats = null;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'migrate:encryption';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Rotate keys used for database encryption';
/**
* An array of old keys. Each one is to be tried in turn.
*
* @var array
*/
protected $old_keys = null;
/**
* The new encryption key.
*
* @var string
*/
protected $new_key = null;
/**
* The list of tables to be scanned.
*
* @var array
*/
protected $tables = null;
/**
* Get the configuration setting for the prefix used to determine if a string is encrypted.
*
* @return string
*/
protected function getEncryptionPrefix(): string
{
return DatabaseEncryption::getPrefix();
}
/**
* Determine whether a string has already been encrypted.
*
* @param mixed $value
*
* @return bool
*/
protected function isEncrypted($value): bool
{
return strpos((string) $value, $this->getEncryptionPrefix()) === 0;
}
/**
* Return the encrypted value of an attribute's value.
*
* @param string $value
* @param Encrypter $cipher
*
* @return null|string
*/
public function encryptedAttribute($value, $cipher): ?string
{
return $this->getEncryptionPrefix().$cipher->encrypt($value);
}
/**
* Return the decrypted value of an attribute's encrypted value.
*
* @param string $value
* @param Encrypter $cipher
*
* @return null|string
*/
public function decryptedAttribute($value, $cipher): ?string
{
return $cipher->decrypt(str_replace($this->getEncryptionPrefix(), '', $value));
}
/**
* Set up keys.
*
* @return void
*/
protected function setupKeys()
{
// Over-ride this function to set:
//
// * $this->old_keys
// * $this->new_key
// * $this->tables
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// Keys
$this->setupKeys();
throw_if(! is_array($this->old_keys) || empty($this->old_keys) || count($this->old_keys) == 0,
RuntimeException::class,
'You must override this class with (array)$old_keys set correctly.');
throw_if(! is_string($this->new_key) || empty($this->new_key), RuntimeException::class,
'You must override this class with (string)$new_key set correctly.');
throw_if(! is_array($this->tables) || empty($this->tables) || count($this->tables) == 0, RuntimeException::class,
'You must override this class with (array)$tables set correctly.');
// Encrypter objects
$cipher = Config::get('app.cipher', 'AES-256-CBC');
$base_encrypter = new Encrypter($this->new_key, $cipher);
$old_encrypter = [];
foreach ($this->old_keys as $key => $value) {
$old_encrypter[$key] = new Encrypter($value, $cipher);
}
// Stats
$stats = [
'tables' => count($this->tables),
'rows' => 0,
'attributes' => 0,
'failed' => 0,
'migrated' => 0,
'skipped' => 0,
];
// Main
$this->writeln('<fg=green>Migrating <fg=blue>'.count($this->old_keys).'</> old database encryption key(s) on <fg=blue>'.$stats['tables'].'</> table(s).</>');
foreach ($this->tables as $table_name) {
// Process table
$this->writeln('<fg=yellow>Fetching data from: <fg=white>"</><fg=green>'.$table_name.'<fg=white>"</>.</>');
// Setup table stats
$table_stats = ['rows' => 0, 'attributes' => 0, 'failed' => 0, 'migrated' => 0, 'skipped' => 0];
// Get count of records
$count = DB::table($table_name)
->count();
// Create progress bar
$bar = defined('LARAVEL_DATABASE_ENCRYPTION_TESTS') ? null : $this->output->createProgressBar($count);
$this->writeln('<fg=yellow>Found <fg=blue>'.number_format($count, 0).'</> record(s) in database; checking encryption keys.</>');
// Get table object
$table_data = DB::table($table_name)
->orderBy('id');
// Cycle through table data 1k records at a time
$chunk = 1000;
$table_data->chunk($chunk, function ($data) use (
&$stats,
&$table_stats,
$bar,
$chunk,
$base_encrypter,
$old_encrypter,
$table_name
) {
foreach ($data as $datum) {
// Check every column of the table for an encrypted value. If the value is
// encrypted then try to decrypt it with the base encrypter.
$datum_array = get_object_vars($datum);
$adjust = [];
$table_stats['rows'] += 1;
foreach ($datum_array as $key => $value) {
$table_stats['attributes'] += 1;
if (! $this->isEncrypted($value)) {
$table_stats['skipped'] += 1;
continue;
}
try {
$test = $this->decryptedAttribute($value, $base_encrypter);
continue;
} catch (Exception $e) {
// If the base encrypter fails then try to decrypt it with each
// other encrypter until one works or they all fail.
$new_value = '';
foreach ($old_encrypter as $cipher) {
try {
$test = $this->decryptedAttribute($value, $cipher);
// If that did not throw an exception then we have a match
// between the old encrypter and the encrypted value, so
// adjust the new value.
$new_value = $this->encryptedAttribute($test, $base_encrypter);
continue;
} catch (\Exception $e) {
// Do nothing, keep trying.
}
}
// If we got a match then empty($new_value) != true
if (empty($new_value)) {
Log::error(
__CLASS__.':'.__TRAIT__.':'.__FILE__.':'.__LINE__.':'.__FUNCTION__.':'.
'Unable to find encryption key for: '.$table_name->key.' #'.$datum->id
);
$table_stats['failed'] += 1;
continue;
}
// We got a match
$adjust[$key] = $new_value;
$table_stats['migrated'] += 1;
}
$table_stats['attributes'] += 1;
}
// If we have anything in $adjust, write that back to the database
if (count($adjust) == 0) {
continue;
}
DB::table($table_name)
->where('id', '=', $datum->id)
->update($adjust);
}
// Advance progress bar
if (! defined('LARAVEL_DATABASE_ENCRYPTION_TESTS')) {
$bar->advance($chunk);
}
});
// Finish progress bar
if (! defined('LARAVEL_DATABASE_ENCRYPTION_TESTS')) {
$bar->finish();
}
// And display stats
foreach ($table_stats as $key => $value) {
$stats[$key] += $value;
}
$this->writeln('');
$this->writeln('<fg=blue>Database encryption migration for table <fg=white>"</><fg=green>'.$table_name.'</><fg=white>"</> complete: '.self::buildStatsString($table_stats).'.</>');
}
$this->writeln('<fg=green>Database encryption migration for all <fg=blue>'.$stats['tables'].'</> table(s) complete: '.self::buildStatsString($stats).'.</>');
self::setStats($stats);
}
private function writeln(string $line): void
{
$output = $this->getOutput();
if (! is_null($output)) {
$output->writeln($line);
}
}
private static function buildStatsString(array $stats, string $stat = null, bool $stylize = true): string
{
$string = '';
foreach ($stats as $key => $value) {
if (! is_null($stat) && $key != $stat) {
continue;
}
$string .= self::stylizeStatsString($key, 'fg=white', $stylize).
self::stylizeStatsString(' = ', 'fg=yellow', $stylize).
self::stylizeStatsString(is_int($value) ? number_format($value, 0) : $value, 'fg=magenta',
$stylize).'; ';
}
return empty($string) ? '' : substr($string, 0, -2);
}
private static function stylizeStatsString(string $string, string $style, bool $stylize = true): string
{
return ! $stylize ? $string : '<'.$style.'>'.$string.'</'.(strpos($style,
'<fg') === 0 ? '' : $style).'>';
}
private static function setStats(array $stats): void
{
self::$stats = $stats;
}
public static function getStats(): array
{
throw_if(is_null(self::$stats), RuntimeException::class, 'Stats do not exist; command has not been executed.');
return self::$stats;
}
}