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
|
<?php
/**
* @author Clark Tomlinson <clark@owncloud.com>
* @since 2/19/15, 1:42 PM
* @copyright Copyright (c) 2015, ownCloud, Inc.
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Encryption\Crypto;
use OC\Encryption\Exceptions\DecryptionFailedException;
use OC\Encryption\Exceptions\EncryptionFailedException;
use OC\Encryption\Exceptions\GenericEncryptionException;
use OCP\IConfig;
use OCP\ILogger;
use OCP\IUser;
use OCP\IUserSession;
class Crypt {
const ENCRYPTION_UKNOWN_ERROR = -1;
const ENCRYPTION_NOT_INIALIZED_ERROR = 1;
const ENCRYPTIION_PRIVATE_KEY_NOT_VALID_ERROR = 2;
const ENCRYPTION_NO_SHARE_KEY_FOUND = 3;
const BLOCKSIZE = 8192;
const DEFAULT_CIPHER = 'AES-256-CFB';
const HEADERSTART = 'HBEGIN';
const HEADEREND = 'HEND';
/**
* @var ILogger
*/
private $logger;
/**
* @var IUser
*/
private $user;
/**
* @var IConfig
*/
private $config;
/**
* @param ILogger $logger
* @param IUserSession $userSession
* @param IConfig $config
*/
public function __construct(ILogger $logger, IUserSession $userSession, IConfig $config) {
$this->logger = $logger;
$this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser() : false;
$this->config = $config;
}
/**
* @param null $user
* @return string
*/
public function mode($user = null) {
return 'server';
}
/**
*
*/
public function createKeyPair() {
$log = $this->logger;
$res = $this->getOpenSSLPKey();
if (!$res) {
$log->error("Encryption Library could'nt generate users key-pair for {$this->user->getUID()}", ['app' => 'encryption']);
if (openssl_error_string()) {
$log->error('Encryption library openssl_pkey_new() fails: ' . openssl_error_string(), ['app' => 'encryption']);
}
} elseif (openssl_pkey_export($res, $privateKey, null, $this->getOpenSSLConfig())) {
$keyDetails = openssl_pkey_get_details($res);
$publicKey = $keyDetails['key'];
return [
'publicKey' => $publicKey,
'privateKey' => $privateKey
];
}
$log->error('Encryption library couldn\'t export users private key, please check your servers openSSL configuration.' . $user->getUID(), ['app' => 'encryption']);
if (openssl_error_string()) {
$log->error('Encryption Library:' . openssl_error_string(), ['app' => 'encryption']);
}
return false;
}
/**
* @return resource
*/
public function getOpenSSLPKey() {
$config = $this->getOpenSSLConfig();
return openssl_pkey_new($config);
}
/**
* @return array
*/
private function getOpenSSLConfig() {
$config = ['private_key_bits' => 4096];
$config = array_merge(\OC::$server->getConfig()->getSystemValue('openssl', []), $config);
return $config;
}
/**
* @param $plainContent
* @param $passphrase
* @return bool|string
* @throws GenericEncryptionException
*/
public function symmetricEncryptFileContent($plainContent, $passphrase) {
if (!$plainContent) {
$this->logger->error('Encryption Library, symmetrical encryption failed no content given', ['app' => 'encryption']);
return false;
}
$iv = $this->generateIv();
try {
$encryptedContent = $this->encrypt($plainContent, $iv, $passphrase, $this->getCipher());
// combine content to encrypt the IV identifier and actual IV
$catFile = $this->concatIV($encryptedContent, $iv);
$padded = $this->addPadding($catFile);
return $padded;
} catch (EncryptionFailedException $e) {
$message = 'Could not encrypt file content (code: ' . $e->getCode() . '): ';
$this->logger->error('files_encryption' . $message . $e->getMessage(), ['app' => 'encryption']);
return false;
}
}
/**
* @param $plainContent
* @param $iv
* @param string $passphrase
* @param string $cipher
* @return string
* @throws EncryptionFailedException
*/
private function encrypt($plainContent, $iv, $passphrase = '', $cipher = self::DEFAULT_CIPHER) {
$encryptedContent = openssl_encrypt($plainContent, $cipher, $passphrase, false, $iv);
if (!$encryptedContent) {
$error = 'Encryption (symmetric) of content failed';
$this->logger->error($error . openssl_error_string(), ['app' => 'encryption']);
throw new EncryptionFailedException($error);
}
return $encryptedContent;
}
/**
* @return mixed|string
*/
public function getCipher() {
$cipher = $this->config->getSystemValue('cipher', self::DEFAULT_CIPHER);
if ($cipher !== 'AES-256-CFB' || $cipher !== 'AES-128-CFB') {
$this->logger->warning('Wrong cipher defined in config.php only AES-128-CFB and AES-256-CFB are supported. Fall back' . self::DEFAULT_CIPHER, ['app' => 'encryption']);
$cipher = self::DEFAULT_CIPHER;
}
return $cipher;
}
/**
* @param $encryptedContent
* @param $iv
* @return string
*/
private function concatIV($encryptedContent, $iv) {
return $encryptedContent . '00iv00' . $iv;
}
/**
* @param $data
* @return string
*/
private function addPadding($data) {
return $data . 'xx';
}
/**
* @param $recoveryKey
* @param $password
* @return bool|string
*/
public function decryptPrivateKey($recoveryKey, $password) {
$header = $this->parseHeader($recoveryKey);
$cipher = $this->getCipher($header);
// If we found a header we need to remove it from the key we want to decrypt
if (!empty($header)) {
$recoveryKey = substr($recoveryKey, strpos($recoveryKey, self::HEADEREND) + strlen(self::HEADERSTART));
}
$plainKey = $this->symmetricDecryptFileContent($recoveryKey, $password, $cipher);
// Check if this is a valid private key
$res = openssl_get_privatekey($plainKey);
if (is_resource($res)) {
$sslInfo = openssl_pkey_get_details($res);
if (!isset($sslInfo['key'])) {
return false;
}
} else {
return false;
}
return $plainKey;
}
/**
* @param $keyFileContents
* @param string $passphrase
* @param string $cipher
* @return bool|string
* @throws DecryptionFailedException
*/
public function symmetricDecryptFileContent($keyFileContents, $passphrase = '', $cipher = self::DEFAULT_CIPHER) {
// Remove Padding
$noPadding = $this->removePadding($keyFileContents);
$catFile = $this->splitIv($noPadding);
$plainContent = $this->decrypt($catFile['encrypted'], $catFile['iv'], $passphrase, $cipher);
if ($plainContent) {
return $plainContent;
}
return false;
}
/**
* @param $padded
* @return bool|string
*/
private function removePadding($padded) {
if (substr($padded, -2) === 'xx') {
return substr($padded, 0, -2);
}
return false;
}
/**
* @param $catFile
* @return array
*/
private function splitIv($catFile) {
// Fetch encryption metadata from end of file
$meta = substr($catFile, -22);
// Fetch IV from end of file
$iv = substr($meta, -16);
// Remove IV and IV Identifier text to expose encrypted content
$encrypted = substr($catFile, 0, -22);
return [
'encrypted' => $encrypted,
'iv' => $iv
];
}
/**
* @param $encryptedContent
* @param $iv
* @param string $passphrase
* @param string $cipher
* @return string
* @throws DecryptionFailedException
*/
private function decrypt($encryptedContent, $iv, $passphrase = '', $cipher = self::DEFAULT_CIPHER) {
$plainContent = openssl_decrypt($encryptedContent, $cipher, $passphrase, false, $iv);
if ($plainContent) {
return $plainContent;
} else {
throw new DecryptionFailedException('Encryption library: Decryption (symmetric) of content failed');
}
}
/**
* @param $data
* @return array
*/
private function parseHeader($data) {
$result = [];
if (substr($data, 0, strlen(self::HEADERSTART)) === self::HEADERSTART) {
$endAt = strpos($data, self::HEADEREND);
$header = substr($data, 0, $endAt + strlen(self::HEADEREND));
// +1 not to start with an ':' which would result in empty element at the beginning
$exploded = explode(':', substr($header, strlen(self::HEADERSTART) + 1));
$element = array_shift($exploded);
while ($element != self::HEADEREND) {
$result[$element] = array_shift($exploded);
$element = array_shift($exploded);
}
}
return $result;
}
/**
* @return string
* @throws GenericEncryptionException
*/
private function generateIv() {
$random = openssl_random_pseudo_bytes(12, $strong);
if ($random) {
if (!$strong) {
// If OpenSSL indicates randomness is insecure log error
$this->logger->error('Encryption Library: Insecure symmetric key was generated using openssl_random_psudo_bytes()', ['app' => 'encryption']);
}
/*
* We encode the iv purely for string manipulation
* purposes -it gets decoded before use
*/
return base64_encode($random);
}
// If we ever get here we've failed anyway no need for an else
throw new GenericEncryptionException('Generating IV Failed');
}
}
|