Passed
Push — master ( 13fa2f...7b8c95 )
by Thomas
12:41
created

EncryptedDBField::getBlindIndexField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace LeKoala\Encrypt;
4
5
use Exception;
6
use SilverStripe\ORM\DataList;
7
use SilverStripe\ORM\DataObject;
8
use SilverStripe\Forms\FormField;
9
use SilverStripe\Forms\TextField;
10
use ParagonIE\CipherSweet\BlindIndex;
11
use ParagonIE\CipherSweet\CipherSweet;
12
use SilverStripe\ORM\Queries\SQLSelect;
13
use ParagonIE\CipherSweet\EncryptedField;
14
use SilverStripe\ORM\FieldType\DBComposite;
15
16
/**
17
 * Value will be set on parent record through built in getField
18
 * mechanisms for composite fields
19
 */
20
class EncryptedDBField extends DBComposite
21
{
22
    use HasBaseEncryption;
23
24
    const LARGE_INDEX_SIZE = 32;
25
    const SMALL_INDEX_SIZE = 16;
26
    const VALUE_SUFFIX = "Value";
27
    const INDEX_SUFFIX = "BlindIndex";
28
29
    /**
30
     * @config
31
     * @var int
32
     */
33
    private static $output_size = 15;
0 ignored issues
show
introduced by
The private property $output_size is not used, and could be removed.
Loading history...
34
35
    /**
36
     * @config
37
     * @var int
38
     */
39
    private static $domain_size = 127;
0 ignored issues
show
introduced by
The private property $domain_size is not used, and could be removed.
Loading history...
40
41
    /**
42
     * @var array<string,string>
43
     */
44
    private static $composite_db = array(
0 ignored issues
show
introduced by
The private property $composite_db is not used, and could be removed.
Loading history...
45
        "Value" => "Varchar(191)",
46
        "BlindIndex" => 'Varchar(32)',
47
    );
48
49
    /**
50
     * Output size is the number of bits (not bytes) of a blind index.
51
     * Eg: 4 for a 4 digits year
52
     * Note: the larger the output size, the smaller the index should be
53
     * @return int
54
     */
55
    public function getOutputSize()
56
    {
57
        if (array_key_exists('output_size', $this->options)) {
58
            $outputSize = $this->options['output_size'];
59
        } else {
60
            $outputSize = static::config()->get('output_size');
61
        }
62
        return $outputSize;
63
    }
64
65
    /**
66
     * Input domain is the set of all possible distinct inputs.
67
     * Eg : 4 digits have 10,000 possible values (10^4). The log (base 2) of 10,000 is 13.2877; you would want to always round up (so 14).
68
     * @return int
69
     */
70
    public function getDomainSize()
71
    {
72
        if (array_key_exists('domain_size', $this->options)) {
73
            $domainSize = $this->options['domain_size'];
74
        } else {
75
            $domainSize = static::config()->get('domain_size');
76
        }
77
        return $domainSize;
78
    }
79
80
    /**
81
     * @param int $default
82
     * @return int
83
     */
84
    public function getIndexSize($default = null)
85
    {
86
        if (array_key_exists('index_size', $this->options)) {
87
            return $this->options['index_size'];
88
        }
89
        if ($default !== null) {
90
            return $default;
91
        }
92
        return self::LARGE_INDEX_SIZE;
93
    }
94
95
    /**
96
     * @return string
97
     */
98
    public function getValueField()
99
    {
100
        return $this->getField(self::VALUE_SUFFIX);
101
    }
102
103
    /**
104
     * @param mixed $value
105
     * @param bool $markChanged
106
     * @return $this
107
     */
108
    public function setValueField($value, $markChanged = true)
109
    {
110
        return $this->setField(self::VALUE_SUFFIX, $value, $markChanged);
111
    }
112
113
    /**
114
     * @return string
115
     */
116
    public function getBlindIndexField()
117
    {
118
        return $this->getField(self::INDEX_SUFFIX);
119
    }
120
121
    /**
122
     * @param mixed $value
123
     * @param bool $markChanged
124
     * @return $this
125
     */
126
    public function setBlindIndexField($value, $markChanged = true)
127
    {
128
        return $this->setField(self::INDEX_SUFFIX, $value, $markChanged);
129
    }
130
131
    /**
132
     * @param CipherSweet $engine
133
     * @param bool $fashHash
134
     * @return EncryptedField
135
     */
136
    public function getEncryptedField($engine = null, $fashHash = null)
137
    {
138
        if ($engine === null) {
139
            $engine = EncryptHelper::getCipherSweet();
140
        }
141
        if ($fashHash === null) {
142
            $fashHash = EncryptHelper::getFashHash();
143
        }
144
        $indexSize = $this->getIndexSize(self::LARGE_INDEX_SIZE);
145
146
        //TODO: review how naming is done (see: getEncryptedRow)
147
        // fieldName needs to match exact db name for row rotator to work properly
148
        $fieldName = $this->name . self::VALUE_SUFFIX;
149
        $indexName = $this->name . self::INDEX_SUFFIX;
150
151
        $encryptedField = (new EncryptedField($engine, $this->tableName, $fieldName))
152
            ->addBlindIndex(new BlindIndex($indexName, [], $indexSize, $fashHash));
153
        return $encryptedField;
154
    }
155
156
    /**
157
     * This is not called anymore, we rely on saveInto for now
158
     * @link https://github.com/silverstripe/silverstripe-framework/issues/8800
159
     * @link https://github.com/silverstripe/silverstripe-framework/pull/10913
160
     * @param array<string,mixed> $manipulation
161
     * @return void
162
     */
163
    public function writeToManipulation(&$manipulation)
164
    {
165
        $encryptedField = $this->getEncryptedField();
166
        $aad = $this->encryptionAad;
167
        if ($this->value) {
168
            $dataForStorage = $encryptedField->prepareForStorage($this->value, $aad);
169
            $encryptedValue = $this->prepValueForDB($dataForStorage[0]);
170
            /** @var array<string,string> $blindIndexes */
171
            $blindIndexes = $dataForStorage[1];
172
        } else {
173
            $encryptedValue = null;
174
            $blindIndexes = [];
175
        }
176
177
        $manipulation['fields'][$this->name . self::VALUE_SUFFIX] = $encryptedValue;
178
        foreach ($blindIndexes as $blindIndexName => $blindIndexValue) {
179
            $manipulation['fields'][$blindIndexName] = $blindIndexValue;
180
        }
181
    }
182
183
    /**
184
     * @param SQLSelect $query
185
     * @return void
186
     */
187
    // public function addToQuery(&$query)
188
    // {
189
    //     parent::addToQuery($query);
190
    //     $query->selectField(sprintf('"%s' . self::VALUE_SUFFIX . '"', $this->name));
191
    //     $query->selectField(sprintf('"%s' . self::INDEX_SUFFIX . '"', $this->name));
192
    // }
193
194
    /**
195
     * Return the blind index value to search in the database
196
     *
197
     * @param string $val The unencrypted value
198
     * @param string $indexSuffix The blind index. Defaults to full index
199
     * @return string
200
     */
201
    public function getSearchValue($val, $indexSuffix = null)
202
    {
203
        if (!$this->tableName && $this->record && is_object($this->record)) {
204
            $this->tableName = DataObject::getSchema()->tableName(get_class($this->record));
205
        }
206
        if (!$this->tableName) {
207
            throw new Exception("Table name not set for search value. Please set a dataobject.");
208
        }
209
        if (!$this->name) {
210
            throw new Exception("Name not set for search value");
211
        }
212
        if (!$val) {
213
            throw new Exception("Cannot search an empty value");
214
        }
215
        if ($indexSuffix === null) {
216
            $indexSuffix = self::INDEX_SUFFIX;
217
        }
218
        $field = $this->getEncryptedField();
219
        $index = $field->getBlindIndex($val, $this->name . $indexSuffix);
220
        if (is_array($index)) {
221
            return $index['value'];
222
        }
223
        return $index;
224
    }
225
226
    /**
227
     * Return a ready to use array params for a where clause
228
     *
229
     * @param string $val The unencrypted value
230
     * @param string $indexSuffix The blind index. Defaults to full index
231
     * @return array<string,string>
232
     */
233
    public function getSearchParams($val, $indexSuffix = null)
234
    {
235
        if (!$indexSuffix) {
236
            $indexSuffix = self::INDEX_SUFFIX;
237
        }
238
        $searchValue = $this->getSearchValue($val, $indexSuffix);
239
        $blindIndexField = $this->name . $indexSuffix;
240
        return array($blindIndexField . ' = ?' => $searchValue);
241
    }
242
243
    /**
244
     * @param string $val The unencrypted value
245
     * @param string $indexSuffix The blind index. Defaults to full index
246
     * @return DataList
247
     */
248
    public function fetchDataList($val, $indexSuffix = null)
249
    {
250
        if (!$this->record || !is_object($this->record)) {
251
            throw new Exception("No record set for this field");
252
        }
253
        if (!$indexSuffix) {
254
            $indexSuffix = self::INDEX_SUFFIX;
255
        }
256
        $class = get_class($this->record);
257
258
        // A blind index can return false positives, use fetch record to make sure you get the record baased on value
259
        $params = $this->getSearchParams($val, $indexSuffix);
260
261
        /** @var DataList $list */
262
        $list = $class::get();
263
        $list = $list->where($params);
264
        return $list;
265
    }
266
267
    /**
268
     * @param string $val The unencrypted value
269
     * @param string $indexSuffix The blind index. Defaults to full index
270
     * @param string|array|null $ignoreID Allows to ignore one id or a list of ids
271
     * @return DataObject|false
272
     */
273
    public function fetchRecord($val, $indexSuffix = null, $ignoreID = null)
274
    {
275
        if (!$indexSuffix) {
276
            $indexSuffix = self::INDEX_SUFFIX;
277
        }
278
        $list = $this->fetchDataList($val, $indexSuffix);
279
        $blindIndexes = $this->getEncryptedField()->getBlindIndexObjects();
280
        $blindIndex = $blindIndexes[$this->name . $indexSuffix];
281
282
        // We will refetch the db object based on the field name for each record
283
        $name = $this->name;
284
        /** @var DataObject $record  */
285
        foreach ($list as $record) {
286
            if ($ignoreID) {
287
                if (is_array($ignoreID) && in_array($record->ID, $ignoreID)) {
288
                    continue;
289
                }
290
                if ($record->ID == $ignoreID) {
291
                    continue;
292
                }
293
            }
294
295
            /** @var EncryptedDBField $obj */
296
            $obj = $record->dbObject($name);
297
            $objValue = $obj->getValue() ?? '';
298
            // Value might be transformed
299
            if ($blindIndex->getTransformed($objValue) == $val) {
300
                return $record;
301
            }
302
        }
303
        // throw exception if there where matches but none with the right value
304
        if ($list->count()) {
305
            throw new Exception($list->count() . " records were found but none matched the right value");
306
        }
307
        return false;
308
    }
309
310
    public function setValue($value, $record = null, $markChanged = true)
311
    {
312
        $this->setEncryptionAad($record);
313
314
        // Return early if we keep encrypted value in memory
315
        if (!EncryptHelper::getAutomaticDecryption()) {
316
            parent::setValue($value, $record, $markChanged);
317
            return $this;
318
        }
319
320
        if ($markChanged) {
321
            $this->isChanged = true;
322
        }
323
324
        // When given a dataobject, bind this field to that
325
        if ($record instanceof DataObject) {
326
            $this->bindTo($record);
327
        }
328
329
        // Convert an object to an array
330
        if ($record && $record instanceof DataObject) {
331
            $record = $record->getQueriedDatabaseFields();
332
            if (!$record) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $record of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
333
                throw new Exception("Could not convert record to array");
334
            }
335
        }
336
337
        // Set the table name if it was not set earlier
338
        if (!$this->tableName && $record) {
339
            $class = is_array($record) && isset($record['ClassName']) ? $record['ClassName'] : get_class($record);
340
            $this->tableName = DataObject::getSchema()->tableName($class);
341
            if (!$this->tableName) {
342
                throw new Exception("Could not get table name from record from " . gettype($record));
343
            }
344
        }
345
346
        // Value will store the decrypted value
347
        if ($value instanceof EncryptedDBField) {
348
            $this->value = $value->getValue();
349
        } elseif ($record && isset($record[$this->name . self::VALUE_SUFFIX])) {
350
            // In that case, the value come from the database and might be encrypted
351
            $encryptedValue = $record[$this->name . self::VALUE_SUFFIX];
352
            $this->value = $this->decryptValue($encryptedValue);
353
        } elseif (is_array($value)) {
354
            if (array_key_exists(self::VALUE_SUFFIX, $value)) {
355
                $this->value = $value;
356
            }
357
        } elseif (is_string($value) || !$value) {
358
            $this->value = $value;
359
        } else {
360
            throw new Exception("Unexcepted value of type " . gettype($value));
361
        }
362
363
        // Forward changes since writeToManipulation are not called
364
        // $this->setValueField($value, $markChanged);
365
366
        return $this;
367
    }
368
369
    /**
370
     * @param array<string,mixed> $options
371
     * @return string
372
     */
373
    public function Nice($options = array())
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

373
    public function Nice(/** @scrutinizer ignore-unused */ $options = array())

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
374
    {
375
        return $this->getValue();
376
    }
377
378
    /**
379
     * @return boolean
380
     */
381
    public function exists()
382
    {
383
        return strlen($this->value ?? '') > 0;
384
    }
385
386
    /**
387
     * This is called by getChangedFields() to check if a field is changed
388
     *
389
     * @return boolean
390
     */
391
    public function isChanged()
392
    {
393
        return $this->isChanged;
394
    }
395
396
    /**
397
     * If we pass a DBField to the setField method, it will
398
     * trigger this method
399
     *
400
     * We save encrypted value on sub fields. They will be collected
401
     * by write() operation by prepareManipulationTable
402
     *
403
     * Currently prepareManipulationTable ignores composite fields
404
     * so we rely on the sub field mechanisms
405
     *
406
     * @param DataObject $dataObject
407
     * @return void
408
     */
409
    public function saveInto($dataObject)
410
    {
411
        $encryptedField = $this->getEncryptedField();
412
        $aad = $this->encryptionAad;
413
        if ($this->value) {
414
            $dataForStorage = $encryptedField->prepareForStorage($this->value, $aad);
415
            $encryptedValue = $this->prepValueForDB($dataForStorage[0]);
416
            /** @var array<string,string> $blindIndexes */
417
            $blindIndexes = $dataForStorage[1];
418
        } else {
419
            $encryptedValue = null;
420
            $blindIndexes = [];
421
        }
422
423
        // This cause infinite loops
424
        // $dataObject->setField($this->getName(), $this->value);
425
426
        // Encrypt value
427
        $key = $this->getName() . self::VALUE_SUFFIX;
428
        $dataObject->setField($key, $encryptedValue);
429
430
        // Build blind indexes
431
        foreach ($blindIndexes as $blindIndexName => $blindIndexValue) {
432
            $dataObject->setField($blindIndexName, $blindIndexValue);
433
        }
434
    }
435
436
    /**
437
     * @param string $title Optional. Localized title of the generated instance
438
     * @param array<mixed> $params
439
     * @return FormField
440
     */
441
    public function scaffoldFormField($title = null, $params = null)
442
    {
443
        $field = TextField::create($this->getName());
444
        return $field;
445
    }
446
447
    /**
448
     * Returns the string value
449
     */
450
    public function __toString()
451
    {
452
        return (string) $this->getValue();
453
    }
454
455
    public function scalarValueOnly()
456
    {
457
        return false;
458
    }
459
}
460