Completed
Pull Request — master (#4106)
by Blizzz
15:12 queued 15s
created
apps/encryption/templates/altmail.php 1 patch
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -4,8 +4,8 @@
 block discarded – undo
4 4
 
5 5
 print_unescaped($l->t("Hey there,\n\nthe admin enabled server-side-encryption. Your files were encrypted using the password '%s'.\n\nPlease login to the web interface, go to the section 'basic encryption module' of your personal settings and update your encryption password by entering this password into the 'old log-in password' field and your current login-password.\n\n", array($_['password'])));
6 6
 if ( isset($_['expiration']) ) {
7
-	print_unescaped($l->t("The share will expire on %s.", array($_['expiration'])));
8
-	print_unescaped("\n\n");
7
+    print_unescaped($l->t("The share will expire on %s.", array($_['expiration'])));
8
+    print_unescaped("\n\n");
9 9
 }
10 10
 // TRANSLATORS term at the end of a mail
11 11
 p($l->t("Cheers!"));
Please login to merge, or discard this patch.
apps/encryption/templates/settings-personal.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2
-	/** @var array $_ */
3
-	/** @var \OCP\IL10N $l */
2
+    /** @var array $_ */
3
+    /** @var \OCP\IL10N $l */
4 4
 script('encryption', 'settings-personal');
5 5
 script('core', 'multiselect');
6 6
 ?>
@@ -20,8 +20,8 @@  discard block
 block discarded – undo
20 20
 			<br />
21 21
 			<?php p( $l->t( "Set your old private key password to your current log-in password:" ) ); ?>
22 22
 			<?php if (  $_["recoveryEnabledForUser"] ):
23
-					p( $l->t( " If you don't remember your old password you can ask your administrator to recover your files." ) );
24
-			endif; ?>
23
+                    p( $l->t( " If you don't remember your old password you can ask your administrator to recover your files." ) );
24
+            endif; ?>
25 25
 			<br />
26 26
 			<input
27 27
 				type="password"
Please login to merge, or discard this patch.
apps/encryption/templates/mail.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -15,10 +15,10 @@
 block discarded – undo
15 15
 					<td width="20px">&nbsp;</td>
16 16
 					<td style="font-weight:normal; font-size:0.8em; line-height:1.2em; font-family:verdana,'arial',sans;">
17 17
 						<?php
18
-						print_unescaped($l->t('Hey there,<br><br>the admin enabled server-side-encryption. Your files were encrypted using the password <strong>%s</strong>.<br><br>Please login to the web interface, go to the section "basic encryption module" of your personal settings and update your encryption password by entering this password into the "old log-in password" field and your current login-password.<br><br>', array($_['password'])));
19
-						// TRANSLATORS term at the end of a mail
20
-						p($l->t('Cheers!'));
21
-						?>
18
+                        print_unescaped($l->t('Hey there,<br><br>the admin enabled server-side-encryption. Your files were encrypted using the password <strong>%s</strong>.<br><br>Please login to the web interface, go to the section "basic encryption module" of your personal settings and update your encryption password by entering this password into the "old log-in password" field and your current login-password.<br><br>', array($_['password'])));
19
+                        // TRANSLATORS term at the end of a mail
20
+                        p($l->t('Cheers!'));
21
+                        ?>
22 22
 					</td>
23 23
 				</tr>
24 24
 				<tr><td colspan="2">&nbsp;</td></tr>
Please login to merge, or discard this patch.
apps/encryption/lib/Migration.php 1 patch
Indentation   +355 added lines, -355 removed lines patch added patch discarded remove patch
@@ -32,359 +32,359 @@
 block discarded – undo
32 32
 
33 33
 class Migration {
34 34
 
35
-	private $moduleId;
36
-	/** @var \OC\Files\View */
37
-	private $view;
38
-	/** @var \OCP\IDBConnection */
39
-	private $connection;
40
-	/** @var IConfig */
41
-	private $config;
42
-	/** @var  ILogger */
43
-	private $logger;
44
-	/** @var string*/
45
-	protected $installedVersion;
46
-
47
-	/**
48
-	 * @param IConfig $config
49
-	 * @param View $view
50
-	 * @param IDBConnection $connection
51
-	 * @param ILogger $logger
52
-	 */
53
-	public function __construct(IConfig $config, View $view, IDBConnection $connection, ILogger $logger) {
54
-		$this->view = $view;
55
-		$this->view->disableCacheUpdate();
56
-		$this->connection = $connection;
57
-		$this->moduleId = \OCA\Encryption\Crypto\Encryption::ID;
58
-		$this->config = $config;
59
-		$this->logger = $logger;
60
-		$this->installedVersion = $this->config->getAppValue('files_encryption', 'installed_version', '-1');
61
-	}
62
-
63
-	public function finalCleanUp() {
64
-		$this->view->deleteAll('files_encryption/public_keys');
65
-		$this->updateFileCache();
66
-		$this->config->deleteAppValue('files_encryption', 'installed_version');
67
-	}
68
-
69
-	/**
70
-	 * update file cache, copy unencrypted_size to the 'size' column
71
-	 */
72
-	private function updateFileCache() {
73
-		// make sure that we don't update the file cache multiple times
74
-		// only update during the first run
75
-		if ($this->installedVersion !== '-1') {
76
-			$query = $this->connection->getQueryBuilder();
77
-			$query->update('filecache')
78
-				->set('size', 'unencrypted_size')
79
-				->where($query->expr()->eq('encrypted', $query->createParameter('encrypted')))
80
-				->setParameter('encrypted', 1);
81
-			$query->execute();
82
-		}
83
-	}
84
-
85
-	/**
86
-	 * iterate through users and reorganize the folder structure
87
-	 */
88
-	public function reorganizeFolderStructure() {
89
-		$this->reorganizeSystemFolderStructure();
90
-
91
-		$limit = 500;
92
-		$offset = 0;
93
-		do {
94
-			$users = \OCP\User::getUsers('', $limit, $offset);
95
-			foreach ($users as $user) {
96
-				$this->reorganizeFolderStructureForUser($user);
97
-			}
98
-			$offset += $limit;
99
-		} while (count($users) >= $limit);
100
-	}
101
-
102
-	/**
103
-	 * reorganize system wide folder structure
104
-	 */
105
-	public function reorganizeSystemFolderStructure() {
106
-
107
-		$this->createPathForKeys('/files_encryption');
108
-
109
-		// backup system wide folders
110
-		$this->backupSystemWideKeys();
111
-
112
-		// rename system wide mount point
113
-		$this->renameFileKeys('', '/files_encryption/keys');
114
-
115
-		// rename system private keys
116
-		$this->renameSystemPrivateKeys();
117
-
118
-		$storage = $this->view->getMount('')->getStorage();
119
-		$storage->getScanner()->scan('files_encryption');
120
-	}
121
-
122
-
123
-	/**
124
-	 * reorganize folder structure for user
125
-	 *
126
-	 * @param string $user
127
-	 */
128
-	public function reorganizeFolderStructureForUser($user) {
129
-		// backup all keys
130
-		\OC_Util::tearDownFS();
131
-		\OC_Util::setupFS($user);
132
-		if ($this->backupUserKeys($user)) {
133
-			// rename users private key
134
-			$this->renameUsersPrivateKey($user);
135
-			$this->renameUsersPublicKey($user);
136
-			// rename file keys
137
-			$path = '/files_encryption/keys';
138
-			$this->renameFileKeys($user, $path);
139
-			$trashPath = '/files_trashbin/keys';
140
-			if (\OC_App::isEnabled('files_trashbin') && $this->view->is_dir($user . '/' . $trashPath)) {
141
-				$this->renameFileKeys($user, $trashPath, true);
142
-				$this->view->deleteAll($trashPath);
143
-			}
144
-			// delete old folders
145
-			$this->deleteOldKeys($user);
146
-			$this->view->getMount('/' . $user)->getStorage()->getScanner()->scan('files_encryption');
147
-		}
148
-	}
149
-
150
-	/**
151
-	 * update database
152
-	 */
153
-	public function updateDB() {
154
-
155
-		// make sure that we don't update the file cache multiple times
156
-		// only update during the first run
157
-		if ($this->installedVersion === '-1') {
158
-			return;
159
-		}
160
-
161
-		// delete left-over from old encryption which is no longer needed
162
-		$this->config->deleteAppValue('files_encryption', 'ocsid');
163
-		$this->config->deleteAppValue('files_encryption', 'types');
164
-		$this->config->deleteAppValue('files_encryption', 'enabled');
165
-
166
-		$oldAppValues = $this->connection->getQueryBuilder();
167
-		$oldAppValues->select('*')
168
-			->from('appconfig')
169
-			->where($oldAppValues->expr()->eq('appid', $oldAppValues->createParameter('appid')))
170
-			->setParameter('appid', 'files_encryption');
171
-		$appSettings = $oldAppValues->execute();
172
-
173
-		while ($row = $appSettings->fetch()) {
174
-			// 'installed_version' gets deleted at the end of the migration process
175
-			if ($row['configkey'] !== 'installed_version' ) {
176
-				$this->config->setAppValue('encryption', $row['configkey'], $row['configvalue']);
177
-				$this->config->deleteAppValue('files_encryption', $row['configkey']);
178
-			}
179
-		}
180
-
181
-		$oldPreferences = $this->connection->getQueryBuilder();
182
-		$oldPreferences->select('*')
183
-			->from('preferences')
184
-			->where($oldPreferences->expr()->eq('appid', $oldPreferences->createParameter('appid')))
185
-			->setParameter('appid', 'files_encryption');
186
-		$preferenceSettings = $oldPreferences->execute();
187
-
188
-		while ($row = $preferenceSettings->fetch()) {
189
-			$this->config->setUserValue($row['userid'], 'encryption', $row['configkey'], $row['configvalue']);
190
-			$this->config->deleteUserValue($row['userid'], 'files_encryption', $row['configkey']);
191
-		}
192
-	}
193
-
194
-	/**
195
-	 * create backup of system-wide keys
196
-	 */
197
-	private function backupSystemWideKeys() {
198
-		$backupDir = 'encryption_migration_backup_' . date("Y-m-d_H-i-s");
199
-		$this->view->mkdir($backupDir);
200
-		$this->view->copy('files_encryption', $backupDir . '/files_encryption');
201
-	}
202
-
203
-	/**
204
-	 * create backup of user specific keys
205
-	 *
206
-	 * @param string $user
207
-	 * @return bool
208
-	 */
209
-	private function backupUserKeys($user) {
210
-		$encryptionDir = $user . '/files_encryption';
211
-		if ($this->view->is_dir($encryptionDir)) {
212
-			$backupDir = $user . '/encryption_migration_backup_' . date("Y-m-d_H-i-s");
213
-			$this->view->mkdir($backupDir);
214
-			$this->view->copy($encryptionDir, $backupDir);
215
-			return true;
216
-		}
217
-		return false;
218
-	}
219
-
220
-	/**
221
-	 * rename system-wide private keys
222
-	 */
223
-	private function renameSystemPrivateKeys() {
224
-		$dh = $this->view->opendir('files_encryption');
225
-		$this->createPathForKeys('/files_encryption/' . $this->moduleId );
226
-		if (is_resource($dh)) {
227
-			while (($privateKey = readdir($dh)) !== false) {
228
-				if (!\OC\Files\Filesystem::isIgnoredDir($privateKey) ) {
229
-					if (!$this->view->is_dir('/files_encryption/' . $privateKey)) {
230
-						$this->view->rename('files_encryption/' . $privateKey, 'files_encryption/' . $this->moduleId . '/' . $privateKey);
231
-						$this->renameSystemPublicKey($privateKey);
232
-					}
233
-				}
234
-			}
235
-			closedir($dh);
236
-		}
237
-	}
238
-
239
-	/**
240
-	 * rename system wide public key
241
-	 *
242
-	 * @param string $privateKey private key for which we want to rename the corresponding public key
243
-	 */
244
-	private function renameSystemPublicKey($privateKey) {
245
-		$publicKey = substr($privateKey,0 , strrpos($privateKey, '.privateKey')) . '.publicKey';
246
-		$this->view->rename('files_encryption/public_keys/' . $publicKey, 'files_encryption/' . $this->moduleId . '/' . $publicKey);
247
-	}
248
-
249
-	/**
250
-	 * rename user-specific private keys
251
-	 *
252
-	 * @param string $user
253
-	 */
254
-	private function renameUsersPrivateKey($user) {
255
-		$oldPrivateKey = $user . '/files_encryption/' . $user . '.privateKey';
256
-		$newPrivateKey = $user . '/files_encryption/' . $this->moduleId . '/' . $user . '.privateKey';
257
-		if ($this->view->file_exists($oldPrivateKey)) {
258
-			$this->createPathForKeys(dirname($newPrivateKey));
259
-			$this->view->rename($oldPrivateKey, $newPrivateKey);
260
-		}
261
-	}
262
-
263
-	/**
264
-	 * rename user-specific public keys
265
-	 *
266
-	 * @param string $user
267
-	 */
268
-	private function renameUsersPublicKey($user) {
269
-		$oldPublicKey = '/files_encryption/public_keys/' . $user . '.publicKey';
270
-		$newPublicKey = $user . '/files_encryption/' . $this->moduleId . '/' . $user . '.publicKey';
271
-		if ($this->view->file_exists($oldPublicKey)) {
272
-			$this->createPathForKeys(dirname($newPublicKey));
273
-			$this->view->rename($oldPublicKey, $newPublicKey);
274
-		}
275
-	}
276
-
277
-	/**
278
-	 * rename file keys
279
-	 *
280
-	 * @param string $user
281
-	 * @param string $path
282
-	 * @param bool $trash
283
-	 */
284
-	private function renameFileKeys($user, $path, $trash = false) {
285
-
286
-		if ($this->view->is_dir($user . '/' . $path) === false) {
287
-			$this->logger->info('Skip dir /' . $user . '/' . $path . ': does not exist');
288
-			return;
289
-		}
290
-
291
-		$dh = $this->view->opendir($user . '/' . $path);
292
-
293
-		if (is_resource($dh)) {
294
-			while (($file = readdir($dh)) !== false) {
295
-				if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
296
-					if ($this->view->is_dir($user . '/' . $path . '/' . $file)) {
297
-						$this->renameFileKeys($user, $path . '/' . $file, $trash);
298
-					} else {
299
-						$target = $this->getTargetDir($user, $path, $file, $trash);
300
-						if ($target !== false) {
301
-							$this->createPathForKeys(dirname($target));
302
-							$this->view->rename($user . '/' . $path . '/' . $file, $target);
303
-						} else {
304
-							$this->logger->warning(
305
-								'did not move key "' . $file
306
-								. '" could not find the corresponding file in /data/' . $user . '/files.'
307
-							. 'Most likely the key was already moved in a previous migration run and is already on the right place.');
308
-						}
309
-					}
310
-				}
311
-			}
312
-			closedir($dh);
313
-		}
314
-	}
315
-
316
-	/**
317
-	 * get system mount points
318
-	 * wrap static method so that it can be mocked for testing
319
-	 *
320
-	 * @internal
321
-	 * @return array
322
-	 */
323
-	protected function getSystemMountPoints() {
324
-		return \OC_Mount_Config::getSystemMountPoints();
325
-	}
326
-
327
-	/**
328
-	 * generate target directory
329
-	 *
330
-	 * @param string $user
331
-	 * @param string $keyPath
332
-	 * @param string $filename
333
-	 * @param bool $trash
334
-	 * @return string
335
-	 */
336
-	private function getTargetDir($user, $keyPath, $filename, $trash) {
337
-		if ($trash) {
338
-			$filePath = substr($keyPath, strlen('/files_trashbin/keys/'));
339
-			$targetDir = $user . '/files_encryption/keys/files_trashbin/' . $filePath . '/' . $this->moduleId . '/' . $filename;
340
-		} else {
341
-			$filePath = substr($keyPath, strlen('/files_encryption/keys/'));
342
-			$targetDir = $user . '/files_encryption/keys/files/' . $filePath . '/' . $this->moduleId . '/' . $filename;
343
-		}
344
-
345
-		if ($user === '') {
346
-			// for system wide mounts we need to check if the mount point really exists
347
-			$normalized = \OC\Files\Filesystem::normalizePath($filePath);
348
-			$systemMountPoints = $this->getSystemMountPoints();
349
-			foreach ($systemMountPoints as $mountPoint) {
350
-				$normalizedMountPoint = \OC\Files\Filesystem::normalizePath($mountPoint['mountpoint']) . '/';
351
-				if (strpos($normalized, $normalizedMountPoint) === 0)
352
-					return $targetDir;
353
-			}
354
-		} else if ($trash === false && $this->view->file_exists('/' . $user. '/files/' . $filePath)) {
355
-			return $targetDir;
356
-		} else if ($trash === true && $this->view->file_exists('/' . $user. '/files_trashbin/' . $filePath)) {
357
-				return $targetDir;
358
-			}
359
-
360
-		return false;
361
-	}
362
-
363
-	/**
364
-	 * delete old keys
365
-	 *
366
-	 * @param string $user
367
-	 */
368
-	private function deleteOldKeys($user) {
369
-		$this->view->deleteAll($user . '/files_encryption/keyfiles');
370
-		$this->view->deleteAll($user . '/files_encryption/share-keys');
371
-	}
372
-
373
-	/**
374
-	 * create directories for the keys recursively
375
-	 *
376
-	 * @param string $path
377
-	 */
378
-	private function createPathForKeys($path) {
379
-		if (!$this->view->file_exists($path)) {
380
-			$sub_dirs = explode('/', $path);
381
-			$dir = '';
382
-			foreach ($sub_dirs as $sub_dir) {
383
-				$dir .= '/' . $sub_dir;
384
-				if (!$this->view->is_dir($dir)) {
385
-					$this->view->mkdir($dir);
386
-				}
387
-			}
388
-		}
389
-	}
35
+    private $moduleId;
36
+    /** @var \OC\Files\View */
37
+    private $view;
38
+    /** @var \OCP\IDBConnection */
39
+    private $connection;
40
+    /** @var IConfig */
41
+    private $config;
42
+    /** @var  ILogger */
43
+    private $logger;
44
+    /** @var string*/
45
+    protected $installedVersion;
46
+
47
+    /**
48
+     * @param IConfig $config
49
+     * @param View $view
50
+     * @param IDBConnection $connection
51
+     * @param ILogger $logger
52
+     */
53
+    public function __construct(IConfig $config, View $view, IDBConnection $connection, ILogger $logger) {
54
+        $this->view = $view;
55
+        $this->view->disableCacheUpdate();
56
+        $this->connection = $connection;
57
+        $this->moduleId = \OCA\Encryption\Crypto\Encryption::ID;
58
+        $this->config = $config;
59
+        $this->logger = $logger;
60
+        $this->installedVersion = $this->config->getAppValue('files_encryption', 'installed_version', '-1');
61
+    }
62
+
63
+    public function finalCleanUp() {
64
+        $this->view->deleteAll('files_encryption/public_keys');
65
+        $this->updateFileCache();
66
+        $this->config->deleteAppValue('files_encryption', 'installed_version');
67
+    }
68
+
69
+    /**
70
+     * update file cache, copy unencrypted_size to the 'size' column
71
+     */
72
+    private function updateFileCache() {
73
+        // make sure that we don't update the file cache multiple times
74
+        // only update during the first run
75
+        if ($this->installedVersion !== '-1') {
76
+            $query = $this->connection->getQueryBuilder();
77
+            $query->update('filecache')
78
+                ->set('size', 'unencrypted_size')
79
+                ->where($query->expr()->eq('encrypted', $query->createParameter('encrypted')))
80
+                ->setParameter('encrypted', 1);
81
+            $query->execute();
82
+        }
83
+    }
84
+
85
+    /**
86
+     * iterate through users and reorganize the folder structure
87
+     */
88
+    public function reorganizeFolderStructure() {
89
+        $this->reorganizeSystemFolderStructure();
90
+
91
+        $limit = 500;
92
+        $offset = 0;
93
+        do {
94
+            $users = \OCP\User::getUsers('', $limit, $offset);
95
+            foreach ($users as $user) {
96
+                $this->reorganizeFolderStructureForUser($user);
97
+            }
98
+            $offset += $limit;
99
+        } while (count($users) >= $limit);
100
+    }
101
+
102
+    /**
103
+     * reorganize system wide folder structure
104
+     */
105
+    public function reorganizeSystemFolderStructure() {
106
+
107
+        $this->createPathForKeys('/files_encryption');
108
+
109
+        // backup system wide folders
110
+        $this->backupSystemWideKeys();
111
+
112
+        // rename system wide mount point
113
+        $this->renameFileKeys('', '/files_encryption/keys');
114
+
115
+        // rename system private keys
116
+        $this->renameSystemPrivateKeys();
117
+
118
+        $storage = $this->view->getMount('')->getStorage();
119
+        $storage->getScanner()->scan('files_encryption');
120
+    }
121
+
122
+
123
+    /**
124
+     * reorganize folder structure for user
125
+     *
126
+     * @param string $user
127
+     */
128
+    public function reorganizeFolderStructureForUser($user) {
129
+        // backup all keys
130
+        \OC_Util::tearDownFS();
131
+        \OC_Util::setupFS($user);
132
+        if ($this->backupUserKeys($user)) {
133
+            // rename users private key
134
+            $this->renameUsersPrivateKey($user);
135
+            $this->renameUsersPublicKey($user);
136
+            // rename file keys
137
+            $path = '/files_encryption/keys';
138
+            $this->renameFileKeys($user, $path);
139
+            $trashPath = '/files_trashbin/keys';
140
+            if (\OC_App::isEnabled('files_trashbin') && $this->view->is_dir($user . '/' . $trashPath)) {
141
+                $this->renameFileKeys($user, $trashPath, true);
142
+                $this->view->deleteAll($trashPath);
143
+            }
144
+            // delete old folders
145
+            $this->deleteOldKeys($user);
146
+            $this->view->getMount('/' . $user)->getStorage()->getScanner()->scan('files_encryption');
147
+        }
148
+    }
149
+
150
+    /**
151
+     * update database
152
+     */
153
+    public function updateDB() {
154
+
155
+        // make sure that we don't update the file cache multiple times
156
+        // only update during the first run
157
+        if ($this->installedVersion === '-1') {
158
+            return;
159
+        }
160
+
161
+        // delete left-over from old encryption which is no longer needed
162
+        $this->config->deleteAppValue('files_encryption', 'ocsid');
163
+        $this->config->deleteAppValue('files_encryption', 'types');
164
+        $this->config->deleteAppValue('files_encryption', 'enabled');
165
+
166
+        $oldAppValues = $this->connection->getQueryBuilder();
167
+        $oldAppValues->select('*')
168
+            ->from('appconfig')
169
+            ->where($oldAppValues->expr()->eq('appid', $oldAppValues->createParameter('appid')))
170
+            ->setParameter('appid', 'files_encryption');
171
+        $appSettings = $oldAppValues->execute();
172
+
173
+        while ($row = $appSettings->fetch()) {
174
+            // 'installed_version' gets deleted at the end of the migration process
175
+            if ($row['configkey'] !== 'installed_version' ) {
176
+                $this->config->setAppValue('encryption', $row['configkey'], $row['configvalue']);
177
+                $this->config->deleteAppValue('files_encryption', $row['configkey']);
178
+            }
179
+        }
180
+
181
+        $oldPreferences = $this->connection->getQueryBuilder();
182
+        $oldPreferences->select('*')
183
+            ->from('preferences')
184
+            ->where($oldPreferences->expr()->eq('appid', $oldPreferences->createParameter('appid')))
185
+            ->setParameter('appid', 'files_encryption');
186
+        $preferenceSettings = $oldPreferences->execute();
187
+
188
+        while ($row = $preferenceSettings->fetch()) {
189
+            $this->config->setUserValue($row['userid'], 'encryption', $row['configkey'], $row['configvalue']);
190
+            $this->config->deleteUserValue($row['userid'], 'files_encryption', $row['configkey']);
191
+        }
192
+    }
193
+
194
+    /**
195
+     * create backup of system-wide keys
196
+     */
197
+    private function backupSystemWideKeys() {
198
+        $backupDir = 'encryption_migration_backup_' . date("Y-m-d_H-i-s");
199
+        $this->view->mkdir($backupDir);
200
+        $this->view->copy('files_encryption', $backupDir . '/files_encryption');
201
+    }
202
+
203
+    /**
204
+     * create backup of user specific keys
205
+     *
206
+     * @param string $user
207
+     * @return bool
208
+     */
209
+    private function backupUserKeys($user) {
210
+        $encryptionDir = $user . '/files_encryption';
211
+        if ($this->view->is_dir($encryptionDir)) {
212
+            $backupDir = $user . '/encryption_migration_backup_' . date("Y-m-d_H-i-s");
213
+            $this->view->mkdir($backupDir);
214
+            $this->view->copy($encryptionDir, $backupDir);
215
+            return true;
216
+        }
217
+        return false;
218
+    }
219
+
220
+    /**
221
+     * rename system-wide private keys
222
+     */
223
+    private function renameSystemPrivateKeys() {
224
+        $dh = $this->view->opendir('files_encryption');
225
+        $this->createPathForKeys('/files_encryption/' . $this->moduleId );
226
+        if (is_resource($dh)) {
227
+            while (($privateKey = readdir($dh)) !== false) {
228
+                if (!\OC\Files\Filesystem::isIgnoredDir($privateKey) ) {
229
+                    if (!$this->view->is_dir('/files_encryption/' . $privateKey)) {
230
+                        $this->view->rename('files_encryption/' . $privateKey, 'files_encryption/' . $this->moduleId . '/' . $privateKey);
231
+                        $this->renameSystemPublicKey($privateKey);
232
+                    }
233
+                }
234
+            }
235
+            closedir($dh);
236
+        }
237
+    }
238
+
239
+    /**
240
+     * rename system wide public key
241
+     *
242
+     * @param string $privateKey private key for which we want to rename the corresponding public key
243
+     */
244
+    private function renameSystemPublicKey($privateKey) {
245
+        $publicKey = substr($privateKey,0 , strrpos($privateKey, '.privateKey')) . '.publicKey';
246
+        $this->view->rename('files_encryption/public_keys/' . $publicKey, 'files_encryption/' . $this->moduleId . '/' . $publicKey);
247
+    }
248
+
249
+    /**
250
+     * rename user-specific private keys
251
+     *
252
+     * @param string $user
253
+     */
254
+    private function renameUsersPrivateKey($user) {
255
+        $oldPrivateKey = $user . '/files_encryption/' . $user . '.privateKey';
256
+        $newPrivateKey = $user . '/files_encryption/' . $this->moduleId . '/' . $user . '.privateKey';
257
+        if ($this->view->file_exists($oldPrivateKey)) {
258
+            $this->createPathForKeys(dirname($newPrivateKey));
259
+            $this->view->rename($oldPrivateKey, $newPrivateKey);
260
+        }
261
+    }
262
+
263
+    /**
264
+     * rename user-specific public keys
265
+     *
266
+     * @param string $user
267
+     */
268
+    private function renameUsersPublicKey($user) {
269
+        $oldPublicKey = '/files_encryption/public_keys/' . $user . '.publicKey';
270
+        $newPublicKey = $user . '/files_encryption/' . $this->moduleId . '/' . $user . '.publicKey';
271
+        if ($this->view->file_exists($oldPublicKey)) {
272
+            $this->createPathForKeys(dirname($newPublicKey));
273
+            $this->view->rename($oldPublicKey, $newPublicKey);
274
+        }
275
+    }
276
+
277
+    /**
278
+     * rename file keys
279
+     *
280
+     * @param string $user
281
+     * @param string $path
282
+     * @param bool $trash
283
+     */
284
+    private function renameFileKeys($user, $path, $trash = false) {
285
+
286
+        if ($this->view->is_dir($user . '/' . $path) === false) {
287
+            $this->logger->info('Skip dir /' . $user . '/' . $path . ': does not exist');
288
+            return;
289
+        }
290
+
291
+        $dh = $this->view->opendir($user . '/' . $path);
292
+
293
+        if (is_resource($dh)) {
294
+            while (($file = readdir($dh)) !== false) {
295
+                if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
296
+                    if ($this->view->is_dir($user . '/' . $path . '/' . $file)) {
297
+                        $this->renameFileKeys($user, $path . '/' . $file, $trash);
298
+                    } else {
299
+                        $target = $this->getTargetDir($user, $path, $file, $trash);
300
+                        if ($target !== false) {
301
+                            $this->createPathForKeys(dirname($target));
302
+                            $this->view->rename($user . '/' . $path . '/' . $file, $target);
303
+                        } else {
304
+                            $this->logger->warning(
305
+                                'did not move key "' . $file
306
+                                . '" could not find the corresponding file in /data/' . $user . '/files.'
307
+                            . 'Most likely the key was already moved in a previous migration run and is already on the right place.');
308
+                        }
309
+                    }
310
+                }
311
+            }
312
+            closedir($dh);
313
+        }
314
+    }
315
+
316
+    /**
317
+     * get system mount points
318
+     * wrap static method so that it can be mocked for testing
319
+     *
320
+     * @internal
321
+     * @return array
322
+     */
323
+    protected function getSystemMountPoints() {
324
+        return \OC_Mount_Config::getSystemMountPoints();
325
+    }
326
+
327
+    /**
328
+     * generate target directory
329
+     *
330
+     * @param string $user
331
+     * @param string $keyPath
332
+     * @param string $filename
333
+     * @param bool $trash
334
+     * @return string
335
+     */
336
+    private function getTargetDir($user, $keyPath, $filename, $trash) {
337
+        if ($trash) {
338
+            $filePath = substr($keyPath, strlen('/files_trashbin/keys/'));
339
+            $targetDir = $user . '/files_encryption/keys/files_trashbin/' . $filePath . '/' . $this->moduleId . '/' . $filename;
340
+        } else {
341
+            $filePath = substr($keyPath, strlen('/files_encryption/keys/'));
342
+            $targetDir = $user . '/files_encryption/keys/files/' . $filePath . '/' . $this->moduleId . '/' . $filename;
343
+        }
344
+
345
+        if ($user === '') {
346
+            // for system wide mounts we need to check if the mount point really exists
347
+            $normalized = \OC\Files\Filesystem::normalizePath($filePath);
348
+            $systemMountPoints = $this->getSystemMountPoints();
349
+            foreach ($systemMountPoints as $mountPoint) {
350
+                $normalizedMountPoint = \OC\Files\Filesystem::normalizePath($mountPoint['mountpoint']) . '/';
351
+                if (strpos($normalized, $normalizedMountPoint) === 0)
352
+                    return $targetDir;
353
+            }
354
+        } else if ($trash === false && $this->view->file_exists('/' . $user. '/files/' . $filePath)) {
355
+            return $targetDir;
356
+        } else if ($trash === true && $this->view->file_exists('/' . $user. '/files_trashbin/' . $filePath)) {
357
+                return $targetDir;
358
+            }
359
+
360
+        return false;
361
+    }
362
+
363
+    /**
364
+     * delete old keys
365
+     *
366
+     * @param string $user
367
+     */
368
+    private function deleteOldKeys($user) {
369
+        $this->view->deleteAll($user . '/files_encryption/keyfiles');
370
+        $this->view->deleteAll($user . '/files_encryption/share-keys');
371
+    }
372
+
373
+    /**
374
+     * create directories for the keys recursively
375
+     *
376
+     * @param string $path
377
+     */
378
+    private function createPathForKeys($path) {
379
+        if (!$this->view->file_exists($path)) {
380
+            $sub_dirs = explode('/', $path);
381
+            $dir = '';
382
+            foreach ($sub_dirs as $sub_dir) {
383
+                $dir .= '/' . $sub_dir;
384
+                if (!$this->view->is_dir($dir)) {
385
+                    $this->view->mkdir($dir);
386
+                }
387
+            }
388
+        }
389
+    }
390 390
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Util.php 1 patch
Indentation   +162 added lines, -162 removed lines patch added patch discarded remove patch
@@ -36,167 +36,167 @@
 block discarded – undo
36 36
 use OCP\PreConditionNotMetException;
37 37
 
38 38
 class Util {
39
-	/**
40
-	 * @var View
41
-	 */
42
-	private $files;
43
-	/**
44
-	 * @var Crypt
45
-	 */
46
-	private $crypt;
47
-	/**
48
-	 * @var ILogger
49
-	 */
50
-	private $logger;
51
-	/**
52
-	 * @var bool|IUser
53
-	 */
54
-	private $user;
55
-	/**
56
-	 * @var IConfig
57
-	 */
58
-	private $config;
59
-	/**
60
-	 * @var IUserManager
61
-	 */
62
-	private $userManager;
63
-
64
-	/**
65
-	 * Util constructor.
66
-	 *
67
-	 * @param View $files
68
-	 * @param Crypt $crypt
69
-	 * @param ILogger $logger
70
-	 * @param IUserSession $userSession
71
-	 * @param IConfig $config
72
-	 * @param IUserManager $userManager
73
-	 */
74
-	public function __construct(View $files,
75
-								Crypt $crypt,
76
-								ILogger $logger,
77
-								IUserSession $userSession,
78
-								IConfig $config,
79
-								IUserManager $userManager
80
-	) {
81
-		$this->files = $files;
82
-		$this->crypt = $crypt;
83
-		$this->logger = $logger;
84
-		$this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser() : false;
85
-		$this->config = $config;
86
-		$this->userManager = $userManager;
87
-	}
88
-
89
-	/**
90
-	 * check if recovery key is enabled for user
91
-	 *
92
-	 * @param string $uid
93
-	 * @return bool
94
-	 */
95
-	public function isRecoveryEnabledForUser($uid) {
96
-		$recoveryMode = $this->config->getUserValue($uid,
97
-			'encryption',
98
-			'recoveryEnabled',
99
-			'0');
100
-
101
-		return ($recoveryMode === '1');
102
-	}
103
-
104
-	/**
105
-	 * check if the home storage should be encrypted
106
-	 *
107
-	 * @return bool
108
-	 */
109
-	public function shouldEncryptHomeStorage() {
110
-		$encryptHomeStorage = $this->config->getAppValue(
111
-			'encryption',
112
-			'encryptHomeStorage',
113
-			'1'
114
-		);
115
-
116
-		return ($encryptHomeStorage === '1');
117
-	}
118
-
119
-	/**
120
-	 * set the home storage encryption on/off
121
-	 *
122
-	 * @param bool $encryptHomeStorage
123
-	 */
124
-	public function setEncryptHomeStorage($encryptHomeStorage) {
125
-		$value = $encryptHomeStorage ? '1' : '0';
126
-		$this->config->setAppValue(
127
-			'encryption',
128
-			'encryptHomeStorage',
129
-			$value
130
-		);
131
-	}
132
-
133
-	/**
134
-	 * check if master key is enabled
135
-	 *
136
-	 * @return bool
137
-	 */
138
-	public function isMasterKeyEnabled() {
139
-		$userMasterKey = $this->config->getAppValue('encryption', 'useMasterKey', '0');
140
-		return ($userMasterKey === '1');
141
-	}
142
-
143
-	/**
144
-	 * @param $enabled
145
-	 * @return bool
146
-	 */
147
-	public function setRecoveryForUser($enabled) {
148
-		$value = $enabled ? '1' : '0';
149
-
150
-		try {
151
-			$this->config->setUserValue($this->user->getUID(),
152
-				'encryption',
153
-				'recoveryEnabled',
154
-				$value);
155
-			return true;
156
-		} catch (PreConditionNotMetException $e) {
157
-			return false;
158
-		}
159
-	}
160
-
161
-	/**
162
-	 * @param string $uid
163
-	 * @return bool
164
-	 */
165
-	public function userHasFiles($uid) {
166
-		return $this->files->file_exists($uid . '/files');
167
-	}
168
-
169
-	/**
170
-	 * get owner from give path, path relative to data/ expected
171
-	 *
172
-	 * @param string $path relative to data/
173
-	 * @return string
174
-	 * @throws \BadMethodCallException
175
-	 */
176
-	public function getOwner($path) {
177
-		$owner = '';
178
-		$parts = explode('/', $path, 3);
179
-		if (count($parts) > 1) {
180
-			$owner = $parts[1];
181
-			if ($this->userManager->userExists($owner) === false) {
182
-				throw new \BadMethodCallException('Unknown user: ' .
183
-				'method expects path to a user folder relative to the data folder');
184
-			}
185
-
186
-		}
187
-
188
-		return $owner;
189
-	}
190
-
191
-	/**
192
-	 * get storage of path
193
-	 *
194
-	 * @param string $path
195
-	 * @return \OC\Files\Storage\Storage
196
-	 */
197
-	public function getStorage($path) {
198
-		$storage = $this->files->getMount($path)->getStorage();
199
-		return $storage;
200
-	}
39
+    /**
40
+     * @var View
41
+     */
42
+    private $files;
43
+    /**
44
+     * @var Crypt
45
+     */
46
+    private $crypt;
47
+    /**
48
+     * @var ILogger
49
+     */
50
+    private $logger;
51
+    /**
52
+     * @var bool|IUser
53
+     */
54
+    private $user;
55
+    /**
56
+     * @var IConfig
57
+     */
58
+    private $config;
59
+    /**
60
+     * @var IUserManager
61
+     */
62
+    private $userManager;
63
+
64
+    /**
65
+     * Util constructor.
66
+     *
67
+     * @param View $files
68
+     * @param Crypt $crypt
69
+     * @param ILogger $logger
70
+     * @param IUserSession $userSession
71
+     * @param IConfig $config
72
+     * @param IUserManager $userManager
73
+     */
74
+    public function __construct(View $files,
75
+                                Crypt $crypt,
76
+                                ILogger $logger,
77
+                                IUserSession $userSession,
78
+                                IConfig $config,
79
+                                IUserManager $userManager
80
+    ) {
81
+        $this->files = $files;
82
+        $this->crypt = $crypt;
83
+        $this->logger = $logger;
84
+        $this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser() : false;
85
+        $this->config = $config;
86
+        $this->userManager = $userManager;
87
+    }
88
+
89
+    /**
90
+     * check if recovery key is enabled for user
91
+     *
92
+     * @param string $uid
93
+     * @return bool
94
+     */
95
+    public function isRecoveryEnabledForUser($uid) {
96
+        $recoveryMode = $this->config->getUserValue($uid,
97
+            'encryption',
98
+            'recoveryEnabled',
99
+            '0');
100
+
101
+        return ($recoveryMode === '1');
102
+    }
103
+
104
+    /**
105
+     * check if the home storage should be encrypted
106
+     *
107
+     * @return bool
108
+     */
109
+    public function shouldEncryptHomeStorage() {
110
+        $encryptHomeStorage = $this->config->getAppValue(
111
+            'encryption',
112
+            'encryptHomeStorage',
113
+            '1'
114
+        );
115
+
116
+        return ($encryptHomeStorage === '1');
117
+    }
118
+
119
+    /**
120
+     * set the home storage encryption on/off
121
+     *
122
+     * @param bool $encryptHomeStorage
123
+     */
124
+    public function setEncryptHomeStorage($encryptHomeStorage) {
125
+        $value = $encryptHomeStorage ? '1' : '0';
126
+        $this->config->setAppValue(
127
+            'encryption',
128
+            'encryptHomeStorage',
129
+            $value
130
+        );
131
+    }
132
+
133
+    /**
134
+     * check if master key is enabled
135
+     *
136
+     * @return bool
137
+     */
138
+    public function isMasterKeyEnabled() {
139
+        $userMasterKey = $this->config->getAppValue('encryption', 'useMasterKey', '0');
140
+        return ($userMasterKey === '1');
141
+    }
142
+
143
+    /**
144
+     * @param $enabled
145
+     * @return bool
146
+     */
147
+    public function setRecoveryForUser($enabled) {
148
+        $value = $enabled ? '1' : '0';
149
+
150
+        try {
151
+            $this->config->setUserValue($this->user->getUID(),
152
+                'encryption',
153
+                'recoveryEnabled',
154
+                $value);
155
+            return true;
156
+        } catch (PreConditionNotMetException $e) {
157
+            return false;
158
+        }
159
+    }
160
+
161
+    /**
162
+     * @param string $uid
163
+     * @return bool
164
+     */
165
+    public function userHasFiles($uid) {
166
+        return $this->files->file_exists($uid . '/files');
167
+    }
168
+
169
+    /**
170
+     * get owner from give path, path relative to data/ expected
171
+     *
172
+     * @param string $path relative to data/
173
+     * @return string
174
+     * @throws \BadMethodCallException
175
+     */
176
+    public function getOwner($path) {
177
+        $owner = '';
178
+        $parts = explode('/', $path, 3);
179
+        if (count($parts) > 1) {
180
+            $owner = $parts[1];
181
+            if ($this->userManager->userExists($owner) === false) {
182
+                throw new \BadMethodCallException('Unknown user: ' .
183
+                'method expects path to a user folder relative to the data folder');
184
+            }
185
+
186
+        }
187
+
188
+        return $owner;
189
+    }
190
+
191
+    /**
192
+     * get storage of path
193
+     *
194
+     * @param string $path
195
+     * @return \OC\Files\Storage\Storage
196
+     */
197
+    public function getStorage($path) {
198
+        $storage = $this->files->getMount($path)->getStorage();
199
+        return $storage;
200
+    }
201 201
 
202 202
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Users/Setup.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -32,58 +32,58 @@
 block discarded – undo
32 32
 use OCP\IUserSession;
33 33
 
34 34
 class Setup {
35
-	/**
36
-	 * @var Crypt
37
-	 */
38
-	private $crypt;
39
-	/**
40
-	 * @var KeyManager
41
-	 */
42
-	private $keyManager;
43
-	/**
44
-	 * @var ILogger
45
-	 */
46
-	private $logger;
47
-	/**
48
-	 * @var bool|string
49
-	 */
50
-	private $user;
35
+    /**
36
+     * @var Crypt
37
+     */
38
+    private $crypt;
39
+    /**
40
+     * @var KeyManager
41
+     */
42
+    private $keyManager;
43
+    /**
44
+     * @var ILogger
45
+     */
46
+    private $logger;
47
+    /**
48
+     * @var bool|string
49
+     */
50
+    private $user;
51 51
 
52 52
 
53
-	/**
54
-	 * @param ILogger $logger
55
-	 * @param IUserSession $userSession
56
-	 * @param Crypt $crypt
57
-	 * @param KeyManager $keyManager
58
-	 */
59
-	public function __construct(ILogger $logger,
60
-								IUserSession $userSession,
61
-								Crypt $crypt,
62
-								KeyManager $keyManager) {
63
-		$this->logger = $logger;
64
-		$this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false;
65
-		$this->crypt = $crypt;
66
-		$this->keyManager = $keyManager;
67
- 	}
53
+    /**
54
+     * @param ILogger $logger
55
+     * @param IUserSession $userSession
56
+     * @param Crypt $crypt
57
+     * @param KeyManager $keyManager
58
+     */
59
+    public function __construct(ILogger $logger,
60
+                                IUserSession $userSession,
61
+                                Crypt $crypt,
62
+                                KeyManager $keyManager) {
63
+        $this->logger = $logger;
64
+        $this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false;
65
+        $this->crypt = $crypt;
66
+        $this->keyManager = $keyManager;
67
+        }
68 68
 
69
-	/**
70
-	 * @param string $uid user id
71
-	 * @param string $password user password
72
-	 * @return bool
73
-	 */
74
-	public function setupUser($uid, $password) {
75
-		if (!$this->keyManager->userHasKeys($uid)) {
76
-			return $this->keyManager->storeKeyPair($uid, $password,
77
-				$this->crypt->createKeyPair());
78
-		}
79
-		return true;
80
-	}
69
+    /**
70
+     * @param string $uid user id
71
+     * @param string $password user password
72
+     * @return bool
73
+     */
74
+    public function setupUser($uid, $password) {
75
+        if (!$this->keyManager->userHasKeys($uid)) {
76
+            return $this->keyManager->storeKeyPair($uid, $password,
77
+                $this->crypt->createKeyPair());
78
+        }
79
+        return true;
80
+    }
81 81
 
82
-	/**
83
-	 * make sure that all system keys exists
84
-	 */
85
-	public function setupSystem() {
86
-		$this->keyManager->validateShareKey();
87
-		$this->keyManager->validateMasterKey();
88
-	}
82
+    /**
83
+     * make sure that all system keys exists
84
+     */
85
+    public function setupSystem() {
86
+        $this->keyManager->validateShareKey();
87
+        $this->keyManager->validateMasterKey();
88
+    }
89 89
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Controller/SettingsController.php 1 patch
Indentation   +124 added lines, -124 removed lines patch added patch discarded remove patch
@@ -38,129 +38,129 @@
 block discarded – undo
38 38
 
39 39
 class SettingsController extends Controller {
40 40
 
41
-	/** @var IL10N */
42
-	private $l;
43
-
44
-	/** @var IUserManager */
45
-	private $userManager;
46
-
47
-	/** @var IUserSession */
48
-	private $userSession;
49
-
50
-	/** @var KeyManager */
51
-	private $keyManager;
52
-
53
-	/** @var Crypt */
54
-	private $crypt;
55
-
56
-	/** @var Session */
57
-	private $session;
58
-
59
-	/** @var ISession  */
60
-	private $ocSession;
61
-
62
-	/** @var  Util */
63
-	private $util;
64
-
65
-	/**
66
-	 * @param string $AppName
67
-	 * @param IRequest $request
68
-	 * @param IL10N $l10n
69
-	 * @param IUserManager $userManager
70
-	 * @param IUserSession $userSession
71
-	 * @param KeyManager $keyManager
72
-	 * @param Crypt $crypt
73
-	 * @param Session $session
74
-	 * @param ISession $ocSession
75
-	 * @param Util $util
76
-	 */
77
-	public function __construct($AppName,
78
-								IRequest $request,
79
-								IL10N $l10n,
80
-								IUserManager $userManager,
81
-								IUserSession $userSession,
82
-								KeyManager $keyManager,
83
-								Crypt $crypt,
84
-								Session $session,
85
-								ISession $ocSession,
86
-								Util $util
41
+    /** @var IL10N */
42
+    private $l;
43
+
44
+    /** @var IUserManager */
45
+    private $userManager;
46
+
47
+    /** @var IUserSession */
48
+    private $userSession;
49
+
50
+    /** @var KeyManager */
51
+    private $keyManager;
52
+
53
+    /** @var Crypt */
54
+    private $crypt;
55
+
56
+    /** @var Session */
57
+    private $session;
58
+
59
+    /** @var ISession  */
60
+    private $ocSession;
61
+
62
+    /** @var  Util */
63
+    private $util;
64
+
65
+    /**
66
+     * @param string $AppName
67
+     * @param IRequest $request
68
+     * @param IL10N $l10n
69
+     * @param IUserManager $userManager
70
+     * @param IUserSession $userSession
71
+     * @param KeyManager $keyManager
72
+     * @param Crypt $crypt
73
+     * @param Session $session
74
+     * @param ISession $ocSession
75
+     * @param Util $util
76
+     */
77
+    public function __construct($AppName,
78
+                                IRequest $request,
79
+                                IL10N $l10n,
80
+                                IUserManager $userManager,
81
+                                IUserSession $userSession,
82
+                                KeyManager $keyManager,
83
+                                Crypt $crypt,
84
+                                Session $session,
85
+                                ISession $ocSession,
86
+                                Util $util
87 87
 ) {
88
-		parent::__construct($AppName, $request);
89
-		$this->l = $l10n;
90
-		$this->userSession = $userSession;
91
-		$this->userManager = $userManager;
92
-		$this->keyManager = $keyManager;
93
-		$this->crypt = $crypt;
94
-		$this->session = $session;
95
-		$this->ocSession = $ocSession;
96
-		$this->util = $util;
97
-	}
98
-
99
-
100
-	/**
101
-	 * @NoAdminRequired
102
-	 * @UseSession
103
-	 *
104
-	 * @param string $oldPassword
105
-	 * @param string $newPassword
106
-	 * @return DataResponse
107
-	 */
108
-	public function updatePrivateKeyPassword($oldPassword, $newPassword) {
109
-		$result = false;
110
-		$uid = $this->userSession->getUser()->getUID();
111
-		$errorMessage = $this->l->t('Could not update the private key password.');
112
-
113
-		//check if password is correct
114
-		$passwordCorrect = $this->userManager->checkPassword($uid, $newPassword);
115
-		if ($passwordCorrect === false) {
116
-			// if check with uid fails we need to check the password with the login name
117
-			// e.g. in the ldap case. For local user we need to check the password with
118
-			// the uid because in this case the login name is case insensitive
119
-			$loginName = $this->ocSession->get('loginname');
120
-			$passwordCorrect = $this->userManager->checkPassword($loginName, $newPassword);
121
-		}
122
-
123
-		if ($passwordCorrect !== false) {
124
-			$encryptedKey = $this->keyManager->getPrivateKey($uid);
125
-			$decryptedKey = $this->crypt->decryptPrivateKey($encryptedKey, $oldPassword, $uid);
126
-
127
-			if ($decryptedKey) {
128
-				$encryptedKey = $this->crypt->encryptPrivateKey($decryptedKey, $newPassword, $uid);
129
-				$header = $this->crypt->generateHeader();
130
-				if ($encryptedKey) {
131
-					$this->keyManager->setPrivateKey($uid, $header . $encryptedKey);
132
-					$this->session->setPrivateKey($decryptedKey);
133
-					$result = true;
134
-				}
135
-			} else {
136
-				$errorMessage = $this->l->t('The old password was not correct, please try again.');
137
-			}
138
-		} else {
139
-			$errorMessage = $this->l->t('The current log-in password was not correct, please try again.');
140
-		}
141
-
142
-		if ($result === true) {
143
-			$this->session->setStatus(Session::INIT_SUCCESSFUL);
144
-			return new DataResponse(
145
-				['message' => (string) $this->l->t('Private key password successfully updated.')]
146
-			);
147
-		} else {
148
-			return new DataResponse(
149
-				['message' => (string) $errorMessage],
150
-				Http::STATUS_BAD_REQUEST
151
-			);
152
-		}
153
-
154
-	}
155
-
156
-	/**
157
-	 * @UseSession
158
-	 *
159
-	 * @param bool $encryptHomeStorage
160
-	 * @return DataResponse
161
-	 */
162
-	public function setEncryptHomeStorage($encryptHomeStorage) {
163
-		$this->util->setEncryptHomeStorage($encryptHomeStorage);
164
-		return new DataResponse();
165
-	}
88
+        parent::__construct($AppName, $request);
89
+        $this->l = $l10n;
90
+        $this->userSession = $userSession;
91
+        $this->userManager = $userManager;
92
+        $this->keyManager = $keyManager;
93
+        $this->crypt = $crypt;
94
+        $this->session = $session;
95
+        $this->ocSession = $ocSession;
96
+        $this->util = $util;
97
+    }
98
+
99
+
100
+    /**
101
+     * @NoAdminRequired
102
+     * @UseSession
103
+     *
104
+     * @param string $oldPassword
105
+     * @param string $newPassword
106
+     * @return DataResponse
107
+     */
108
+    public function updatePrivateKeyPassword($oldPassword, $newPassword) {
109
+        $result = false;
110
+        $uid = $this->userSession->getUser()->getUID();
111
+        $errorMessage = $this->l->t('Could not update the private key password.');
112
+
113
+        //check if password is correct
114
+        $passwordCorrect = $this->userManager->checkPassword($uid, $newPassword);
115
+        if ($passwordCorrect === false) {
116
+            // if check with uid fails we need to check the password with the login name
117
+            // e.g. in the ldap case. For local user we need to check the password with
118
+            // the uid because in this case the login name is case insensitive
119
+            $loginName = $this->ocSession->get('loginname');
120
+            $passwordCorrect = $this->userManager->checkPassword($loginName, $newPassword);
121
+        }
122
+
123
+        if ($passwordCorrect !== false) {
124
+            $encryptedKey = $this->keyManager->getPrivateKey($uid);
125
+            $decryptedKey = $this->crypt->decryptPrivateKey($encryptedKey, $oldPassword, $uid);
126
+
127
+            if ($decryptedKey) {
128
+                $encryptedKey = $this->crypt->encryptPrivateKey($decryptedKey, $newPassword, $uid);
129
+                $header = $this->crypt->generateHeader();
130
+                if ($encryptedKey) {
131
+                    $this->keyManager->setPrivateKey($uid, $header . $encryptedKey);
132
+                    $this->session->setPrivateKey($decryptedKey);
133
+                    $result = true;
134
+                }
135
+            } else {
136
+                $errorMessage = $this->l->t('The old password was not correct, please try again.');
137
+            }
138
+        } else {
139
+            $errorMessage = $this->l->t('The current log-in password was not correct, please try again.');
140
+        }
141
+
142
+        if ($result === true) {
143
+            $this->session->setStatus(Session::INIT_SUCCESSFUL);
144
+            return new DataResponse(
145
+                ['message' => (string) $this->l->t('Private key password successfully updated.')]
146
+            );
147
+        } else {
148
+            return new DataResponse(
149
+                ['message' => (string) $errorMessage],
150
+                Http::STATUS_BAD_REQUEST
151
+            );
152
+        }
153
+
154
+    }
155
+
156
+    /**
157
+     * @UseSession
158
+     *
159
+     * @param bool $encryptHomeStorage
160
+     * @return DataResponse
161
+     */
162
+    public function setEncryptHomeStorage($encryptHomeStorage) {
163
+        $this->util->setEncryptHomeStorage($encryptHomeStorage);
164
+        return new DataResponse();
165
+    }
166 166
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Controller/RecoveryController.php 1 patch
Indentation   +155 added lines, -155 removed lines patch added patch discarded remove patch
@@ -34,160 +34,160 @@
 block discarded – undo
34 34
 use OCP\AppFramework\Http\DataResponse;
35 35
 
36 36
 class RecoveryController extends Controller {
37
-	/**
38
-	 * @var IConfig
39
-	 */
40
-	private $config;
41
-	/**
42
-	 * @var IL10N
43
-	 */
44
-	private $l;
45
-	/**
46
-	 * @var Recovery
47
-	 */
48
-	private $recovery;
49
-
50
-	/**
51
-	 * @param string $AppName
52
-	 * @param IRequest $request
53
-	 * @param IConfig $config
54
-	 * @param IL10N $l10n
55
-	 * @param Recovery $recovery
56
-	 */
57
-	public function __construct($AppName,
58
-								IRequest $request,
59
-								IConfig $config,
60
-								IL10N $l10n,
61
-								Recovery $recovery) {
62
-		parent::__construct($AppName, $request);
63
-		$this->config = $config;
64
-		$this->l = $l10n;
65
-		$this->recovery = $recovery;
66
-	}
67
-
68
-	/**
69
-	 * @param string $recoveryPassword
70
-	 * @param string $confirmPassword
71
-	 * @param string $adminEnableRecovery
72
-	 * @return DataResponse
73
-	 */
74
-	public function adminRecovery($recoveryPassword, $confirmPassword, $adminEnableRecovery) {
75
-		// Check if both passwords are the same
76
-		if (empty($recoveryPassword)) {
77
-			$errorMessage = (string)$this->l->t('Missing recovery key password');
78
-			return new DataResponse(['data' => ['message' => $errorMessage]],
79
-				Http::STATUS_BAD_REQUEST);
80
-		}
81
-
82
-		if (empty($confirmPassword)) {
83
-			$errorMessage = (string)$this->l->t('Please repeat the recovery key password');
84
-			return new DataResponse(['data' => ['message' => $errorMessage]],
85
-				Http::STATUS_BAD_REQUEST);
86
-		}
87
-
88
-		if ($recoveryPassword !== $confirmPassword) {
89
-			$errorMessage = (string)$this->l->t('Repeated recovery key password does not match the provided recovery key password');
90
-			return new DataResponse(['data' => ['message' => $errorMessage]],
91
-				Http::STATUS_BAD_REQUEST);
92
-		}
93
-
94
-		if (isset($adminEnableRecovery) && $adminEnableRecovery === '1') {
95
-			if ($this->recovery->enableAdminRecovery($recoveryPassword)) {
96
-				return new DataResponse(['data' => ['message' => (string)$this->l->t('Recovery key successfully enabled')]]);
97
-			}
98
-			return new DataResponse(['data' => ['message' => (string)$this->l->t('Could not enable recovery key. Please check your recovery key password!')]], Http::STATUS_BAD_REQUEST);
99
-		} elseif (isset($adminEnableRecovery) && $adminEnableRecovery === '0') {
100
-			if ($this->recovery->disableAdminRecovery($recoveryPassword)) {
101
-				return new DataResponse(['data' => ['message' => (string)$this->l->t('Recovery key successfully disabled')]]);
102
-			}
103
-			return new DataResponse(['data' => ['message' => (string)$this->l->t('Could not disable recovery key. Please check your recovery key password!')]], Http::STATUS_BAD_REQUEST);
104
-		}
105
-		// this response should never be sent but just in case.
106
-		return new DataResponse(['data' => ['message' => (string)$this->l->t('Missing parameters')]], Http::STATUS_BAD_REQUEST);
107
-	}
108
-
109
-	/**
110
-	 * @param string $newPassword
111
-	 * @param string $oldPassword
112
-	 * @param string $confirmPassword
113
-	 * @return DataResponse
114
-	 */
115
-	public function changeRecoveryPassword($newPassword, $oldPassword, $confirmPassword) {
116
-		//check if both passwords are the same
117
-		if (empty($oldPassword)) {
118
-			$errorMessage = (string)$this->l->t('Please provide the old recovery password');
119
-			return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
120
-		}
121
-
122
-		if (empty($newPassword)) {
123
-			$errorMessage = (string)$this->l->t('Please provide a new recovery password');
124
-			return new DataResponse (['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
125
-		}
126
-
127
-		if (empty($confirmPassword)) {
128
-			$errorMessage = (string)$this->l->t('Please repeat the new recovery password');
129
-			return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
130
-		}
131
-
132
-		if ($newPassword !== $confirmPassword) {
133
-			$errorMessage = (string)$this->l->t('Repeated recovery key password does not match the provided recovery key password');
134
-			return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
135
-		}
136
-
137
-		$result = $this->recovery->changeRecoveryKeyPassword($newPassword,
138
-			$oldPassword);
139
-
140
-		if ($result) {
141
-			return new DataResponse(
142
-				[
143
-					'data' => [
144
-						'message' => (string)$this->l->t('Password successfully changed.')]
145
-				]
146
-			);
147
-		}
148
-		return new DataResponse(
149
-			[
150
-				'data' => [
151
-					'message' => (string)$this->l->t('Could not change the password. Maybe the old password was not correct.')
152
-				]
153
-			], Http::STATUS_BAD_REQUEST);
154
-	}
155
-
156
-	/**
157
-	 * @NoAdminRequired
158
-	 *
159
-	 * @param string $userEnableRecovery
160
-	 * @return DataResponse
161
-	 */
162
-	public function userSetRecovery($userEnableRecovery) {
163
-		if ($userEnableRecovery === '0' || $userEnableRecovery === '1') {
164
-
165
-			$result = $this->recovery->setRecoveryForUser($userEnableRecovery);
166
-
167
-			if ($result) {
168
-				if ($userEnableRecovery === '0') {
169
-					return new DataResponse(
170
-						[
171
-							'data' => [
172
-								'message' => (string)$this->l->t('Recovery Key disabled')]
173
-						]
174
-					);
175
-				}
176
-				return new DataResponse(
177
-					[
178
-						'data' => [
179
-							'message' => (string)$this->l->t('Recovery Key enabled')]
180
-					]
181
-				);
182
-			}
183
-
184
-		}
185
-		return new DataResponse(
186
-			[
187
-				'data' => [
188
-					'message' => (string)$this->l->t('Could not enable the recovery key, please try again or contact your administrator')
189
-				]
190
-			], Http::STATUS_BAD_REQUEST);
191
-	}
37
+    /**
38
+     * @var IConfig
39
+     */
40
+    private $config;
41
+    /**
42
+     * @var IL10N
43
+     */
44
+    private $l;
45
+    /**
46
+     * @var Recovery
47
+     */
48
+    private $recovery;
49
+
50
+    /**
51
+     * @param string $AppName
52
+     * @param IRequest $request
53
+     * @param IConfig $config
54
+     * @param IL10N $l10n
55
+     * @param Recovery $recovery
56
+     */
57
+    public function __construct($AppName,
58
+                                IRequest $request,
59
+                                IConfig $config,
60
+                                IL10N $l10n,
61
+                                Recovery $recovery) {
62
+        parent::__construct($AppName, $request);
63
+        $this->config = $config;
64
+        $this->l = $l10n;
65
+        $this->recovery = $recovery;
66
+    }
67
+
68
+    /**
69
+     * @param string $recoveryPassword
70
+     * @param string $confirmPassword
71
+     * @param string $adminEnableRecovery
72
+     * @return DataResponse
73
+     */
74
+    public function adminRecovery($recoveryPassword, $confirmPassword, $adminEnableRecovery) {
75
+        // Check if both passwords are the same
76
+        if (empty($recoveryPassword)) {
77
+            $errorMessage = (string)$this->l->t('Missing recovery key password');
78
+            return new DataResponse(['data' => ['message' => $errorMessage]],
79
+                Http::STATUS_BAD_REQUEST);
80
+        }
81
+
82
+        if (empty($confirmPassword)) {
83
+            $errorMessage = (string)$this->l->t('Please repeat the recovery key password');
84
+            return new DataResponse(['data' => ['message' => $errorMessage]],
85
+                Http::STATUS_BAD_REQUEST);
86
+        }
87
+
88
+        if ($recoveryPassword !== $confirmPassword) {
89
+            $errorMessage = (string)$this->l->t('Repeated recovery key password does not match the provided recovery key password');
90
+            return new DataResponse(['data' => ['message' => $errorMessage]],
91
+                Http::STATUS_BAD_REQUEST);
92
+        }
93
+
94
+        if (isset($adminEnableRecovery) && $adminEnableRecovery === '1') {
95
+            if ($this->recovery->enableAdminRecovery($recoveryPassword)) {
96
+                return new DataResponse(['data' => ['message' => (string)$this->l->t('Recovery key successfully enabled')]]);
97
+            }
98
+            return new DataResponse(['data' => ['message' => (string)$this->l->t('Could not enable recovery key. Please check your recovery key password!')]], Http::STATUS_BAD_REQUEST);
99
+        } elseif (isset($adminEnableRecovery) && $adminEnableRecovery === '0') {
100
+            if ($this->recovery->disableAdminRecovery($recoveryPassword)) {
101
+                return new DataResponse(['data' => ['message' => (string)$this->l->t('Recovery key successfully disabled')]]);
102
+            }
103
+            return new DataResponse(['data' => ['message' => (string)$this->l->t('Could not disable recovery key. Please check your recovery key password!')]], Http::STATUS_BAD_REQUEST);
104
+        }
105
+        // this response should never be sent but just in case.
106
+        return new DataResponse(['data' => ['message' => (string)$this->l->t('Missing parameters')]], Http::STATUS_BAD_REQUEST);
107
+    }
108
+
109
+    /**
110
+     * @param string $newPassword
111
+     * @param string $oldPassword
112
+     * @param string $confirmPassword
113
+     * @return DataResponse
114
+     */
115
+    public function changeRecoveryPassword($newPassword, $oldPassword, $confirmPassword) {
116
+        //check if both passwords are the same
117
+        if (empty($oldPassword)) {
118
+            $errorMessage = (string)$this->l->t('Please provide the old recovery password');
119
+            return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
120
+        }
121
+
122
+        if (empty($newPassword)) {
123
+            $errorMessage = (string)$this->l->t('Please provide a new recovery password');
124
+            return new DataResponse (['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
125
+        }
126
+
127
+        if (empty($confirmPassword)) {
128
+            $errorMessage = (string)$this->l->t('Please repeat the new recovery password');
129
+            return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
130
+        }
131
+
132
+        if ($newPassword !== $confirmPassword) {
133
+            $errorMessage = (string)$this->l->t('Repeated recovery key password does not match the provided recovery key password');
134
+            return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
135
+        }
136
+
137
+        $result = $this->recovery->changeRecoveryKeyPassword($newPassword,
138
+            $oldPassword);
139
+
140
+        if ($result) {
141
+            return new DataResponse(
142
+                [
143
+                    'data' => [
144
+                        'message' => (string)$this->l->t('Password successfully changed.')]
145
+                ]
146
+            );
147
+        }
148
+        return new DataResponse(
149
+            [
150
+                'data' => [
151
+                    'message' => (string)$this->l->t('Could not change the password. Maybe the old password was not correct.')
152
+                ]
153
+            ], Http::STATUS_BAD_REQUEST);
154
+    }
155
+
156
+    /**
157
+     * @NoAdminRequired
158
+     *
159
+     * @param string $userEnableRecovery
160
+     * @return DataResponse
161
+     */
162
+    public function userSetRecovery($userEnableRecovery) {
163
+        if ($userEnableRecovery === '0' || $userEnableRecovery === '1') {
164
+
165
+            $result = $this->recovery->setRecoveryForUser($userEnableRecovery);
166
+
167
+            if ($result) {
168
+                if ($userEnableRecovery === '0') {
169
+                    return new DataResponse(
170
+                        [
171
+                            'data' => [
172
+                                'message' => (string)$this->l->t('Recovery Key disabled')]
173
+                        ]
174
+                    );
175
+                }
176
+                return new DataResponse(
177
+                    [
178
+                        'data' => [
179
+                            'message' => (string)$this->l->t('Recovery Key enabled')]
180
+                    ]
181
+                );
182
+            }
183
+
184
+        }
185
+        return new DataResponse(
186
+            [
187
+                'data' => [
188
+                    'message' => (string)$this->l->t('Could not enable the recovery key, please try again or contact your administrator')
189
+                ]
190
+            ], Http::STATUS_BAD_REQUEST);
191
+    }
192 192
 
193 193
 }
Please login to merge, or discard this patch.
apps/encryption/lib/KeyManager.php 1 patch
Indentation   +661 added lines, -661 removed lines patch added patch discarded remove patch
@@ -38,665 +38,665 @@
 block discarded – undo
38 38
 
39 39
 class KeyManager {
40 40
 
41
-	/**
42
-	 * @var Session
43
-	 */
44
-	protected $session;
45
-	/**
46
-	 * @var IStorage
47
-	 */
48
-	private $keyStorage;
49
-	/**
50
-	 * @var Crypt
51
-	 */
52
-	private $crypt;
53
-	/**
54
-	 * @var string
55
-	 */
56
-	private $recoveryKeyId;
57
-	/**
58
-	 * @var string
59
-	 */
60
-	private $publicShareKeyId;
61
-	/**
62
-	 * @var string
63
-	 */
64
-	private $masterKeyId;
65
-	/**
66
-	 * @var string UserID
67
-	 */
68
-	private $keyId;
69
-	/**
70
-	 * @var string
71
-	 */
72
-	private $publicKeyId = 'publicKey';
73
-	/**
74
-	 * @var string
75
-	 */
76
-	private $privateKeyId = 'privateKey';
77
-
78
-	/**
79
-	 * @var string
80
-	 */
81
-	private $shareKeyId = 'shareKey';
82
-
83
-	/**
84
-	 * @var string
85
-	 */
86
-	private $fileKeyId = 'fileKey';
87
-	/**
88
-	 * @var IConfig
89
-	 */
90
-	private $config;
91
-	/**
92
-	 * @var ILogger
93
-	 */
94
-	private $log;
95
-	/**
96
-	 * @var Util
97
-	 */
98
-	private $util;
99
-
100
-	/**
101
-	 * @param IStorage $keyStorage
102
-	 * @param Crypt $crypt
103
-	 * @param IConfig $config
104
-	 * @param IUserSession $userSession
105
-	 * @param Session $session
106
-	 * @param ILogger $log
107
-	 * @param Util $util
108
-	 */
109
-	public function __construct(
110
-		IStorage $keyStorage,
111
-		Crypt $crypt,
112
-		IConfig $config,
113
-		IUserSession $userSession,
114
-		Session $session,
115
-		ILogger $log,
116
-		Util $util
117
-	) {
118
-
119
-		$this->util = $util;
120
-		$this->session = $session;
121
-		$this->keyStorage = $keyStorage;
122
-		$this->crypt = $crypt;
123
-		$this->config = $config;
124
-		$this->log = $log;
125
-
126
-		$this->recoveryKeyId = $this->config->getAppValue('encryption',
127
-			'recoveryKeyId');
128
-		if (empty($this->recoveryKeyId)) {
129
-			$this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8);
130
-			$this->config->setAppValue('encryption',
131
-				'recoveryKeyId',
132
-				$this->recoveryKeyId);
133
-		}
134
-
135
-		$this->publicShareKeyId = $this->config->getAppValue('encryption',
136
-			'publicShareKeyId');
137
-		if (empty($this->publicShareKeyId)) {
138
-			$this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8);
139
-			$this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId);
140
-		}
141
-
142
-		$this->masterKeyId = $this->config->getAppValue('encryption',
143
-			'masterKeyId');
144
-		if (empty($this->masterKeyId)) {
145
-			$this->masterKeyId = 'master_' . substr(md5(time()), 0, 8);
146
-			$this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId);
147
-		}
148
-
149
-		$this->keyId = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false;
150
-		$this->log = $log;
151
-	}
152
-
153
-	/**
154
-	 * check if key pair for public link shares exists, if not we create one
155
-	 */
156
-	public function validateShareKey() {
157
-		$shareKey = $this->getPublicShareKey();
158
-		if (empty($shareKey)) {
159
-			$keyPair = $this->crypt->createKeyPair();
160
-
161
-			// Save public key
162
-			$this->keyStorage->setSystemUserKey(
163
-				$this->publicShareKeyId . '.publicKey', $keyPair['publicKey'],
164
-				Encryption::ID);
165
-
166
-			// Encrypt private key empty passphrase
167
-			$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], '');
168
-			$header = $this->crypt->generateHeader();
169
-			$this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey);
170
-		}
171
-	}
172
-
173
-	/**
174
-	 * check if a key pair for the master key exists, if not we create one
175
-	 */
176
-	public function validateMasterKey() {
177
-
178
-		if ($this->util->isMasterKeyEnabled() === false) {
179
-			return;
180
-		}
181
-
182
-		$masterKey = $this->getPublicMasterKey();
183
-		if (empty($masterKey)) {
184
-			$keyPair = $this->crypt->createKeyPair();
185
-
186
-			// Save public key
187
-			$this->keyStorage->setSystemUserKey(
188
-				$this->masterKeyId . '.publicKey', $keyPair['publicKey'],
189
-				Encryption::ID);
190
-
191
-			// Encrypt private key with system password
192
-			$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId);
193
-			$header = $this->crypt->generateHeader();
194
-			$this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey);
195
-		}
196
-	}
197
-
198
-	/**
199
-	 * @return bool
200
-	 */
201
-	public function recoveryKeyExists() {
202
-		$key = $this->getRecoveryKey();
203
-		return (!empty($key));
204
-	}
205
-
206
-	/**
207
-	 * get recovery key
208
-	 *
209
-	 * @return string
210
-	 */
211
-	public function getRecoveryKey() {
212
-		return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID);
213
-	}
214
-
215
-	/**
216
-	 * get recovery key ID
217
-	 *
218
-	 * @return string
219
-	 */
220
-	public function getRecoveryKeyId() {
221
-		return $this->recoveryKeyId;
222
-	}
223
-
224
-	/**
225
-	 * @param string $password
226
-	 * @return bool
227
-	 */
228
-	public function checkRecoveryPassword($password) {
229
-		$recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID);
230
-		$decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
231
-
232
-		if ($decryptedRecoveryKey) {
233
-			return true;
234
-		}
235
-		return false;
236
-	}
237
-
238
-	/**
239
-	 * @param string $uid
240
-	 * @param string $password
241
-	 * @param string $keyPair
242
-	 * @return bool
243
-	 */
244
-	public function storeKeyPair($uid, $password, $keyPair) {
245
-		// Save Public Key
246
-		$this->setPublicKey($uid, $keyPair['publicKey']);
247
-
248
-		$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid);
249
-
250
-		$header = $this->crypt->generateHeader();
251
-
252
-		if ($encryptedKey) {
253
-			$this->setPrivateKey($uid, $header . $encryptedKey);
254
-			return true;
255
-		}
256
-		return false;
257
-	}
258
-
259
-	/**
260
-	 * @param string $password
261
-	 * @param array $keyPair
262
-	 * @return bool
263
-	 */
264
-	public function setRecoveryKey($password, $keyPair) {
265
-		// Save Public Key
266
-		$this->keyStorage->setSystemUserKey($this->getRecoveryKeyId().
267
-			'.publicKey',
268
-			$keyPair['publicKey'],
269
-			Encryption::ID);
270
-
271
-		$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password);
272
-		$header = $this->crypt->generateHeader();
273
-
274
-		if ($encryptedKey) {
275
-			$this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey);
276
-			return true;
277
-		}
278
-		return false;
279
-	}
280
-
281
-	/**
282
-	 * @param $userId
283
-	 * @param $key
284
-	 * @return bool
285
-	 */
286
-	public function setPublicKey($userId, $key) {
287
-		return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID);
288
-	}
289
-
290
-	/**
291
-	 * @param $userId
292
-	 * @param string $key
293
-	 * @return bool
294
-	 */
295
-	public function setPrivateKey($userId, $key) {
296
-		return $this->keyStorage->setUserKey($userId,
297
-			$this->privateKeyId,
298
-			$key,
299
-			Encryption::ID);
300
-	}
301
-
302
-	/**
303
-	 * write file key to key storage
304
-	 *
305
-	 * @param string $path
306
-	 * @param string $key
307
-	 * @return boolean
308
-	 */
309
-	public function setFileKey($path, $key) {
310
-		return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID);
311
-	}
312
-
313
-	/**
314
-	 * set all file keys (the file key and the corresponding share keys)
315
-	 *
316
-	 * @param string $path
317
-	 * @param array $keys
318
-	 */
319
-	public function setAllFileKeys($path, $keys) {
320
-		$this->setFileKey($path, $keys['data']);
321
-		foreach ($keys['keys'] as $uid => $keyFile) {
322
-			$this->setShareKey($path, $uid, $keyFile);
323
-		}
324
-	}
325
-
326
-	/**
327
-	 * write share key to the key storage
328
-	 *
329
-	 * @param string $path
330
-	 * @param string $uid
331
-	 * @param string $key
332
-	 * @return boolean
333
-	 */
334
-	public function setShareKey($path, $uid, $key) {
335
-		$keyId = $uid . '.' . $this->shareKeyId;
336
-		return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID);
337
-	}
338
-
339
-	/**
340
-	 * Decrypt private key and store it
341
-	 *
342
-	 * @param string $uid user id
343
-	 * @param string $passPhrase users password
344
-	 * @return boolean
345
-	 */
346
-	public function init($uid, $passPhrase) {
347
-
348
-		$this->session->setStatus(Session::INIT_EXECUTED);
349
-
350
-		try {
351
-			if($this->util->isMasterKeyEnabled()) {
352
-				$uid = $this->getMasterKeyId();
353
-				$passPhrase = $this->getMasterKeyPassword();
354
-				$privateKey = $this->getSystemPrivateKey($uid);
355
-			} else {
356
-				$privateKey = $this->getPrivateKey($uid);
357
-			}
358
-			$privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid);
359
-		} catch (PrivateKeyMissingException $e) {
360
-			return false;
361
-		} catch (DecryptionFailedException $e) {
362
-			return false;
363
-		} catch (\Exception $e) {
364
-			$this->log->warning(
365
-				'Could not decrypt the private key from user "' . $uid . '"" during login. ' .
366
-				'Assume password change on the user back-end. Error message: '
367
-				. $e->getMessage()
368
-			);
369
-			return false;
370
-		}
371
-
372
-		if ($privateKey) {
373
-			$this->session->setPrivateKey($privateKey);
374
-			$this->session->setStatus(Session::INIT_SUCCESSFUL);
375
-			return true;
376
-		}
377
-
378
-		return false;
379
-	}
380
-
381
-	/**
382
-	 * @param $userId
383
-	 * @return string
384
-	 * @throws PrivateKeyMissingException
385
-	 */
386
-	public function getPrivateKey($userId) {
387
-		$privateKey = $this->keyStorage->getUserKey($userId,
388
-			$this->privateKeyId, Encryption::ID);
389
-
390
-		if (strlen($privateKey) !== 0) {
391
-			return $privateKey;
392
-		}
393
-		throw new PrivateKeyMissingException($userId);
394
-	}
395
-
396
-	/**
397
-	 * @param string $path
398
-	 * @param $uid
399
-	 * @return string
400
-	 */
401
-	public function getFileKey($path, $uid) {
402
-		$encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID);
403
-
404
-		if (empty($encryptedFileKey)) {
405
-			return '';
406
-		}
407
-
408
-		if ($this->util->isMasterKeyEnabled()) {
409
-			$uid = $this->getMasterKeyId();
410
-		}
411
-
412
-		if (is_null($uid)) {
413
-			$uid = $this->getPublicShareKeyId();
414
-			$shareKey = $this->getShareKey($path, $uid);
415
-			$privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID);
416
-			$privateKey = $this->crypt->decryptPrivateKey($privateKey);
417
-		} else {
418
-			$shareKey = $this->getShareKey($path, $uid);
419
-			$privateKey = $this->session->getPrivateKey();
420
-		}
421
-
422
-		if ($encryptedFileKey && $shareKey && $privateKey) {
423
-			return $this->crypt->multiKeyDecrypt($encryptedFileKey,
424
-				$shareKey,
425
-				$privateKey);
426
-		}
427
-
428
-		return '';
429
-	}
430
-
431
-	/**
432
-	 * Get the current version of a file
433
-	 *
434
-	 * @param string $path
435
-	 * @param View $view
436
-	 * @return int
437
-	 */
438
-	public function getVersion($path, View $view) {
439
-		$fileInfo = $view->getFileInfo($path);
440
-		if($fileInfo === false) {
441
-			return 0;
442
-		}
443
-		return $fileInfo->getEncryptedVersion();
444
-	}
445
-
446
-	/**
447
-	 * Set the current version of a file
448
-	 *
449
-	 * @param string $path
450
-	 * @param int $version
451
-	 * @param View $view
452
-	 */
453
-	public function setVersion($path, $version, View $view) {
454
-		$fileInfo= $view->getFileInfo($path);
455
-
456
-		if($fileInfo !== false) {
457
-			$cache = $fileInfo->getStorage()->getCache();
458
-			$cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
459
-		}
460
-	}
461
-
462
-	/**
463
-	 * get the encrypted file key
464
-	 *
465
-	 * @param string $path
466
-	 * @return string
467
-	 */
468
-	public function getEncryptedFileKey($path) {
469
-		$encryptedFileKey = $this->keyStorage->getFileKey($path,
470
-			$this->fileKeyId, Encryption::ID);
471
-
472
-		return $encryptedFileKey;
473
-	}
474
-
475
-	/**
476
-	 * delete share key
477
-	 *
478
-	 * @param string $path
479
-	 * @param string $keyId
480
-	 * @return boolean
481
-	 */
482
-	public function deleteShareKey($path, $keyId) {
483
-		return $this->keyStorage->deleteFileKey(
484
-			$path,
485
-			$keyId . '.' . $this->shareKeyId,
486
-			Encryption::ID);
487
-	}
488
-
489
-
490
-	/**
491
-	 * @param $path
492
-	 * @param $uid
493
-	 * @return mixed
494
-	 */
495
-	public function getShareKey($path, $uid) {
496
-		$keyId = $uid . '.' . $this->shareKeyId;
497
-		return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID);
498
-	}
499
-
500
-	/**
501
-	 * check if user has a private and a public key
502
-	 *
503
-	 * @param string $userId
504
-	 * @return bool
505
-	 * @throws PrivateKeyMissingException
506
-	 * @throws PublicKeyMissingException
507
-	 */
508
-	public function userHasKeys($userId) {
509
-		$privateKey = $publicKey = true;
510
-		$exception = null;
511
-
512
-		try {
513
-			$this->getPrivateKey($userId);
514
-		} catch (PrivateKeyMissingException $e) {
515
-			$privateKey = false;
516
-			$exception = $e;
517
-		}
518
-		try {
519
-			$this->getPublicKey($userId);
520
-		} catch (PublicKeyMissingException $e) {
521
-			$publicKey = false;
522
-			$exception = $e;
523
-		}
524
-
525
-		if ($privateKey && $publicKey) {
526
-			return true;
527
-		} elseif (!$privateKey && !$publicKey) {
528
-			return false;
529
-		} else {
530
-			throw $exception;
531
-		}
532
-	}
533
-
534
-	/**
535
-	 * @param $userId
536
-	 * @return mixed
537
-	 * @throws PublicKeyMissingException
538
-	 */
539
-	public function getPublicKey($userId) {
540
-		$publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID);
541
-
542
-		if (strlen($publicKey) !== 0) {
543
-			return $publicKey;
544
-		}
545
-		throw new PublicKeyMissingException($userId);
546
-	}
547
-
548
-	public function getPublicShareKeyId() {
549
-		return $this->publicShareKeyId;
550
-	}
551
-
552
-	/**
553
-	 * get public key for public link shares
554
-	 *
555
-	 * @return string
556
-	 */
557
-	public function getPublicShareKey() {
558
-		return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID);
559
-	}
560
-
561
-	/**
562
-	 * @param string $purpose
563
-	 * @param string $uid
564
-	 */
565
-	public function backupUserKeys($purpose, $uid) {
566
-		$this->keyStorage->backupUserKeys(Encryption::ID, $purpose, $uid);
567
-	}
568
-
569
-	/**
570
-	 * creat a backup of the users private and public key and then  delete it
571
-	 *
572
-	 * @param string $uid
573
-	 */
574
-	public function deleteUserKeys($uid) {
575
-		$this->deletePublicKey($uid);
576
-		$this->deletePrivateKey($uid);
577
-	}
578
-
579
-	/**
580
-	 * @param $uid
581
-	 * @return bool
582
-	 */
583
-	public function deletePublicKey($uid) {
584
-		return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID);
585
-	}
586
-
587
-	/**
588
-	 * @param string $uid
589
-	 * @return bool
590
-	 */
591
-	private function deletePrivateKey($uid) {
592
-		return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID);
593
-	}
594
-
595
-	/**
596
-	 * @param string $path
597
-	 * @return bool
598
-	 */
599
-	public function deleteAllFileKeys($path) {
600
-		return $this->keyStorage->deleteAllFileKeys($path);
601
-	}
602
-
603
-	/**
604
-	 * @param array $userIds
605
-	 * @return array
606
-	 * @throws PublicKeyMissingException
607
-	 */
608
-	public function getPublicKeys(array $userIds) {
609
-		$keys = [];
610
-
611
-		foreach ($userIds as $userId) {
612
-			try {
613
-				$keys[$userId] = $this->getPublicKey($userId);
614
-			} catch (PublicKeyMissingException $e) {
615
-				continue;
616
-			}
617
-		}
618
-
619
-		return $keys;
620
-
621
-	}
622
-
623
-	/**
624
-	 * @param string $keyId
625
-	 * @return string returns openssl key
626
-	 */
627
-	public function getSystemPrivateKey($keyId) {
628
-		return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID);
629
-	}
630
-
631
-	/**
632
-	 * @param string $keyId
633
-	 * @param string $key
634
-	 * @return string returns openssl key
635
-	 */
636
-	public function setSystemPrivateKey($keyId, $key) {
637
-		return $this->keyStorage->setSystemUserKey(
638
-			$keyId . '.' . $this->privateKeyId,
639
-			$key,
640
-			Encryption::ID);
641
-	}
642
-
643
-	/**
644
-	 * add system keys such as the public share key and the recovery key
645
-	 *
646
-	 * @param array $accessList
647
-	 * @param array $publicKeys
648
-	 * @param string $uid
649
-	 * @return array
650
-	 * @throws PublicKeyMissingException
651
-	 */
652
-	public function addSystemKeys(array $accessList, array $publicKeys, $uid) {
653
-		if (!empty($accessList['public'])) {
654
-			$publicShareKey = $this->getPublicShareKey();
655
-			if (empty($publicShareKey)) {
656
-				throw new PublicKeyMissingException($this->getPublicShareKeyId());
657
-			}
658
-			$publicKeys[$this->getPublicShareKeyId()] = $publicShareKey;
659
-		}
660
-
661
-		if ($this->recoveryKeyExists() &&
662
-			$this->util->isRecoveryEnabledForUser($uid)) {
663
-
664
-			$publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey();
665
-		}
666
-
667
-		return $publicKeys;
668
-	}
669
-
670
-	/**
671
-	 * get master key password
672
-	 *
673
-	 * @return string
674
-	 * @throws \Exception
675
-	 */
676
-	public function getMasterKeyPassword() {
677
-		$password = $this->config->getSystemValue('secret');
678
-		if (empty($password)){
679
-			throw new \Exception('Can not get secret from ownCloud instance');
680
-		}
681
-
682
-		return $password;
683
-	}
684
-
685
-	/**
686
-	 * return master key id
687
-	 *
688
-	 * @return string
689
-	 */
690
-	public function getMasterKeyId() {
691
-		return $this->masterKeyId;
692
-	}
693
-
694
-	/**
695
-	 * get public master key
696
-	 *
697
-	 * @return string
698
-	 */
699
-	public function getPublicMasterKey() {
700
-		return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID);
701
-	}
41
+    /**
42
+     * @var Session
43
+     */
44
+    protected $session;
45
+    /**
46
+     * @var IStorage
47
+     */
48
+    private $keyStorage;
49
+    /**
50
+     * @var Crypt
51
+     */
52
+    private $crypt;
53
+    /**
54
+     * @var string
55
+     */
56
+    private $recoveryKeyId;
57
+    /**
58
+     * @var string
59
+     */
60
+    private $publicShareKeyId;
61
+    /**
62
+     * @var string
63
+     */
64
+    private $masterKeyId;
65
+    /**
66
+     * @var string UserID
67
+     */
68
+    private $keyId;
69
+    /**
70
+     * @var string
71
+     */
72
+    private $publicKeyId = 'publicKey';
73
+    /**
74
+     * @var string
75
+     */
76
+    private $privateKeyId = 'privateKey';
77
+
78
+    /**
79
+     * @var string
80
+     */
81
+    private $shareKeyId = 'shareKey';
82
+
83
+    /**
84
+     * @var string
85
+     */
86
+    private $fileKeyId = 'fileKey';
87
+    /**
88
+     * @var IConfig
89
+     */
90
+    private $config;
91
+    /**
92
+     * @var ILogger
93
+     */
94
+    private $log;
95
+    /**
96
+     * @var Util
97
+     */
98
+    private $util;
99
+
100
+    /**
101
+     * @param IStorage $keyStorage
102
+     * @param Crypt $crypt
103
+     * @param IConfig $config
104
+     * @param IUserSession $userSession
105
+     * @param Session $session
106
+     * @param ILogger $log
107
+     * @param Util $util
108
+     */
109
+    public function __construct(
110
+        IStorage $keyStorage,
111
+        Crypt $crypt,
112
+        IConfig $config,
113
+        IUserSession $userSession,
114
+        Session $session,
115
+        ILogger $log,
116
+        Util $util
117
+    ) {
118
+
119
+        $this->util = $util;
120
+        $this->session = $session;
121
+        $this->keyStorage = $keyStorage;
122
+        $this->crypt = $crypt;
123
+        $this->config = $config;
124
+        $this->log = $log;
125
+
126
+        $this->recoveryKeyId = $this->config->getAppValue('encryption',
127
+            'recoveryKeyId');
128
+        if (empty($this->recoveryKeyId)) {
129
+            $this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8);
130
+            $this->config->setAppValue('encryption',
131
+                'recoveryKeyId',
132
+                $this->recoveryKeyId);
133
+        }
134
+
135
+        $this->publicShareKeyId = $this->config->getAppValue('encryption',
136
+            'publicShareKeyId');
137
+        if (empty($this->publicShareKeyId)) {
138
+            $this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8);
139
+            $this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId);
140
+        }
141
+
142
+        $this->masterKeyId = $this->config->getAppValue('encryption',
143
+            'masterKeyId');
144
+        if (empty($this->masterKeyId)) {
145
+            $this->masterKeyId = 'master_' . substr(md5(time()), 0, 8);
146
+            $this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId);
147
+        }
148
+
149
+        $this->keyId = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false;
150
+        $this->log = $log;
151
+    }
152
+
153
+    /**
154
+     * check if key pair for public link shares exists, if not we create one
155
+     */
156
+    public function validateShareKey() {
157
+        $shareKey = $this->getPublicShareKey();
158
+        if (empty($shareKey)) {
159
+            $keyPair = $this->crypt->createKeyPair();
160
+
161
+            // Save public key
162
+            $this->keyStorage->setSystemUserKey(
163
+                $this->publicShareKeyId . '.publicKey', $keyPair['publicKey'],
164
+                Encryption::ID);
165
+
166
+            // Encrypt private key empty passphrase
167
+            $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], '');
168
+            $header = $this->crypt->generateHeader();
169
+            $this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey);
170
+        }
171
+    }
172
+
173
+    /**
174
+     * check if a key pair for the master key exists, if not we create one
175
+     */
176
+    public function validateMasterKey() {
177
+
178
+        if ($this->util->isMasterKeyEnabled() === false) {
179
+            return;
180
+        }
181
+
182
+        $masterKey = $this->getPublicMasterKey();
183
+        if (empty($masterKey)) {
184
+            $keyPair = $this->crypt->createKeyPair();
185
+
186
+            // Save public key
187
+            $this->keyStorage->setSystemUserKey(
188
+                $this->masterKeyId . '.publicKey', $keyPair['publicKey'],
189
+                Encryption::ID);
190
+
191
+            // Encrypt private key with system password
192
+            $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId);
193
+            $header = $this->crypt->generateHeader();
194
+            $this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey);
195
+        }
196
+    }
197
+
198
+    /**
199
+     * @return bool
200
+     */
201
+    public function recoveryKeyExists() {
202
+        $key = $this->getRecoveryKey();
203
+        return (!empty($key));
204
+    }
205
+
206
+    /**
207
+     * get recovery key
208
+     *
209
+     * @return string
210
+     */
211
+    public function getRecoveryKey() {
212
+        return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID);
213
+    }
214
+
215
+    /**
216
+     * get recovery key ID
217
+     *
218
+     * @return string
219
+     */
220
+    public function getRecoveryKeyId() {
221
+        return $this->recoveryKeyId;
222
+    }
223
+
224
+    /**
225
+     * @param string $password
226
+     * @return bool
227
+     */
228
+    public function checkRecoveryPassword($password) {
229
+        $recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID);
230
+        $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
231
+
232
+        if ($decryptedRecoveryKey) {
233
+            return true;
234
+        }
235
+        return false;
236
+    }
237
+
238
+    /**
239
+     * @param string $uid
240
+     * @param string $password
241
+     * @param string $keyPair
242
+     * @return bool
243
+     */
244
+    public function storeKeyPair($uid, $password, $keyPair) {
245
+        // Save Public Key
246
+        $this->setPublicKey($uid, $keyPair['publicKey']);
247
+
248
+        $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid);
249
+
250
+        $header = $this->crypt->generateHeader();
251
+
252
+        if ($encryptedKey) {
253
+            $this->setPrivateKey($uid, $header . $encryptedKey);
254
+            return true;
255
+        }
256
+        return false;
257
+    }
258
+
259
+    /**
260
+     * @param string $password
261
+     * @param array $keyPair
262
+     * @return bool
263
+     */
264
+    public function setRecoveryKey($password, $keyPair) {
265
+        // Save Public Key
266
+        $this->keyStorage->setSystemUserKey($this->getRecoveryKeyId().
267
+            '.publicKey',
268
+            $keyPair['publicKey'],
269
+            Encryption::ID);
270
+
271
+        $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password);
272
+        $header = $this->crypt->generateHeader();
273
+
274
+        if ($encryptedKey) {
275
+            $this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey);
276
+            return true;
277
+        }
278
+        return false;
279
+    }
280
+
281
+    /**
282
+     * @param $userId
283
+     * @param $key
284
+     * @return bool
285
+     */
286
+    public function setPublicKey($userId, $key) {
287
+        return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID);
288
+    }
289
+
290
+    /**
291
+     * @param $userId
292
+     * @param string $key
293
+     * @return bool
294
+     */
295
+    public function setPrivateKey($userId, $key) {
296
+        return $this->keyStorage->setUserKey($userId,
297
+            $this->privateKeyId,
298
+            $key,
299
+            Encryption::ID);
300
+    }
301
+
302
+    /**
303
+     * write file key to key storage
304
+     *
305
+     * @param string $path
306
+     * @param string $key
307
+     * @return boolean
308
+     */
309
+    public function setFileKey($path, $key) {
310
+        return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID);
311
+    }
312
+
313
+    /**
314
+     * set all file keys (the file key and the corresponding share keys)
315
+     *
316
+     * @param string $path
317
+     * @param array $keys
318
+     */
319
+    public function setAllFileKeys($path, $keys) {
320
+        $this->setFileKey($path, $keys['data']);
321
+        foreach ($keys['keys'] as $uid => $keyFile) {
322
+            $this->setShareKey($path, $uid, $keyFile);
323
+        }
324
+    }
325
+
326
+    /**
327
+     * write share key to the key storage
328
+     *
329
+     * @param string $path
330
+     * @param string $uid
331
+     * @param string $key
332
+     * @return boolean
333
+     */
334
+    public function setShareKey($path, $uid, $key) {
335
+        $keyId = $uid . '.' . $this->shareKeyId;
336
+        return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID);
337
+    }
338
+
339
+    /**
340
+     * Decrypt private key and store it
341
+     *
342
+     * @param string $uid user id
343
+     * @param string $passPhrase users password
344
+     * @return boolean
345
+     */
346
+    public function init($uid, $passPhrase) {
347
+
348
+        $this->session->setStatus(Session::INIT_EXECUTED);
349
+
350
+        try {
351
+            if($this->util->isMasterKeyEnabled()) {
352
+                $uid = $this->getMasterKeyId();
353
+                $passPhrase = $this->getMasterKeyPassword();
354
+                $privateKey = $this->getSystemPrivateKey($uid);
355
+            } else {
356
+                $privateKey = $this->getPrivateKey($uid);
357
+            }
358
+            $privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid);
359
+        } catch (PrivateKeyMissingException $e) {
360
+            return false;
361
+        } catch (DecryptionFailedException $e) {
362
+            return false;
363
+        } catch (\Exception $e) {
364
+            $this->log->warning(
365
+                'Could not decrypt the private key from user "' . $uid . '"" during login. ' .
366
+                'Assume password change on the user back-end. Error message: '
367
+                . $e->getMessage()
368
+            );
369
+            return false;
370
+        }
371
+
372
+        if ($privateKey) {
373
+            $this->session->setPrivateKey($privateKey);
374
+            $this->session->setStatus(Session::INIT_SUCCESSFUL);
375
+            return true;
376
+        }
377
+
378
+        return false;
379
+    }
380
+
381
+    /**
382
+     * @param $userId
383
+     * @return string
384
+     * @throws PrivateKeyMissingException
385
+     */
386
+    public function getPrivateKey($userId) {
387
+        $privateKey = $this->keyStorage->getUserKey($userId,
388
+            $this->privateKeyId, Encryption::ID);
389
+
390
+        if (strlen($privateKey) !== 0) {
391
+            return $privateKey;
392
+        }
393
+        throw new PrivateKeyMissingException($userId);
394
+    }
395
+
396
+    /**
397
+     * @param string $path
398
+     * @param $uid
399
+     * @return string
400
+     */
401
+    public function getFileKey($path, $uid) {
402
+        $encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID);
403
+
404
+        if (empty($encryptedFileKey)) {
405
+            return '';
406
+        }
407
+
408
+        if ($this->util->isMasterKeyEnabled()) {
409
+            $uid = $this->getMasterKeyId();
410
+        }
411
+
412
+        if (is_null($uid)) {
413
+            $uid = $this->getPublicShareKeyId();
414
+            $shareKey = $this->getShareKey($path, $uid);
415
+            $privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID);
416
+            $privateKey = $this->crypt->decryptPrivateKey($privateKey);
417
+        } else {
418
+            $shareKey = $this->getShareKey($path, $uid);
419
+            $privateKey = $this->session->getPrivateKey();
420
+        }
421
+
422
+        if ($encryptedFileKey && $shareKey && $privateKey) {
423
+            return $this->crypt->multiKeyDecrypt($encryptedFileKey,
424
+                $shareKey,
425
+                $privateKey);
426
+        }
427
+
428
+        return '';
429
+    }
430
+
431
+    /**
432
+     * Get the current version of a file
433
+     *
434
+     * @param string $path
435
+     * @param View $view
436
+     * @return int
437
+     */
438
+    public function getVersion($path, View $view) {
439
+        $fileInfo = $view->getFileInfo($path);
440
+        if($fileInfo === false) {
441
+            return 0;
442
+        }
443
+        return $fileInfo->getEncryptedVersion();
444
+    }
445
+
446
+    /**
447
+     * Set the current version of a file
448
+     *
449
+     * @param string $path
450
+     * @param int $version
451
+     * @param View $view
452
+     */
453
+    public function setVersion($path, $version, View $view) {
454
+        $fileInfo= $view->getFileInfo($path);
455
+
456
+        if($fileInfo !== false) {
457
+            $cache = $fileInfo->getStorage()->getCache();
458
+            $cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
459
+        }
460
+    }
461
+
462
+    /**
463
+     * get the encrypted file key
464
+     *
465
+     * @param string $path
466
+     * @return string
467
+     */
468
+    public function getEncryptedFileKey($path) {
469
+        $encryptedFileKey = $this->keyStorage->getFileKey($path,
470
+            $this->fileKeyId, Encryption::ID);
471
+
472
+        return $encryptedFileKey;
473
+    }
474
+
475
+    /**
476
+     * delete share key
477
+     *
478
+     * @param string $path
479
+     * @param string $keyId
480
+     * @return boolean
481
+     */
482
+    public function deleteShareKey($path, $keyId) {
483
+        return $this->keyStorage->deleteFileKey(
484
+            $path,
485
+            $keyId . '.' . $this->shareKeyId,
486
+            Encryption::ID);
487
+    }
488
+
489
+
490
+    /**
491
+     * @param $path
492
+     * @param $uid
493
+     * @return mixed
494
+     */
495
+    public function getShareKey($path, $uid) {
496
+        $keyId = $uid . '.' . $this->shareKeyId;
497
+        return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID);
498
+    }
499
+
500
+    /**
501
+     * check if user has a private and a public key
502
+     *
503
+     * @param string $userId
504
+     * @return bool
505
+     * @throws PrivateKeyMissingException
506
+     * @throws PublicKeyMissingException
507
+     */
508
+    public function userHasKeys($userId) {
509
+        $privateKey = $publicKey = true;
510
+        $exception = null;
511
+
512
+        try {
513
+            $this->getPrivateKey($userId);
514
+        } catch (PrivateKeyMissingException $e) {
515
+            $privateKey = false;
516
+            $exception = $e;
517
+        }
518
+        try {
519
+            $this->getPublicKey($userId);
520
+        } catch (PublicKeyMissingException $e) {
521
+            $publicKey = false;
522
+            $exception = $e;
523
+        }
524
+
525
+        if ($privateKey && $publicKey) {
526
+            return true;
527
+        } elseif (!$privateKey && !$publicKey) {
528
+            return false;
529
+        } else {
530
+            throw $exception;
531
+        }
532
+    }
533
+
534
+    /**
535
+     * @param $userId
536
+     * @return mixed
537
+     * @throws PublicKeyMissingException
538
+     */
539
+    public function getPublicKey($userId) {
540
+        $publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID);
541
+
542
+        if (strlen($publicKey) !== 0) {
543
+            return $publicKey;
544
+        }
545
+        throw new PublicKeyMissingException($userId);
546
+    }
547
+
548
+    public function getPublicShareKeyId() {
549
+        return $this->publicShareKeyId;
550
+    }
551
+
552
+    /**
553
+     * get public key for public link shares
554
+     *
555
+     * @return string
556
+     */
557
+    public function getPublicShareKey() {
558
+        return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID);
559
+    }
560
+
561
+    /**
562
+     * @param string $purpose
563
+     * @param string $uid
564
+     */
565
+    public function backupUserKeys($purpose, $uid) {
566
+        $this->keyStorage->backupUserKeys(Encryption::ID, $purpose, $uid);
567
+    }
568
+
569
+    /**
570
+     * creat a backup of the users private and public key and then  delete it
571
+     *
572
+     * @param string $uid
573
+     */
574
+    public function deleteUserKeys($uid) {
575
+        $this->deletePublicKey($uid);
576
+        $this->deletePrivateKey($uid);
577
+    }
578
+
579
+    /**
580
+     * @param $uid
581
+     * @return bool
582
+     */
583
+    public function deletePublicKey($uid) {
584
+        return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID);
585
+    }
586
+
587
+    /**
588
+     * @param string $uid
589
+     * @return bool
590
+     */
591
+    private function deletePrivateKey($uid) {
592
+        return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID);
593
+    }
594
+
595
+    /**
596
+     * @param string $path
597
+     * @return bool
598
+     */
599
+    public function deleteAllFileKeys($path) {
600
+        return $this->keyStorage->deleteAllFileKeys($path);
601
+    }
602
+
603
+    /**
604
+     * @param array $userIds
605
+     * @return array
606
+     * @throws PublicKeyMissingException
607
+     */
608
+    public function getPublicKeys(array $userIds) {
609
+        $keys = [];
610
+
611
+        foreach ($userIds as $userId) {
612
+            try {
613
+                $keys[$userId] = $this->getPublicKey($userId);
614
+            } catch (PublicKeyMissingException $e) {
615
+                continue;
616
+            }
617
+        }
618
+
619
+        return $keys;
620
+
621
+    }
622
+
623
+    /**
624
+     * @param string $keyId
625
+     * @return string returns openssl key
626
+     */
627
+    public function getSystemPrivateKey($keyId) {
628
+        return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID);
629
+    }
630
+
631
+    /**
632
+     * @param string $keyId
633
+     * @param string $key
634
+     * @return string returns openssl key
635
+     */
636
+    public function setSystemPrivateKey($keyId, $key) {
637
+        return $this->keyStorage->setSystemUserKey(
638
+            $keyId . '.' . $this->privateKeyId,
639
+            $key,
640
+            Encryption::ID);
641
+    }
642
+
643
+    /**
644
+     * add system keys such as the public share key and the recovery key
645
+     *
646
+     * @param array $accessList
647
+     * @param array $publicKeys
648
+     * @param string $uid
649
+     * @return array
650
+     * @throws PublicKeyMissingException
651
+     */
652
+    public function addSystemKeys(array $accessList, array $publicKeys, $uid) {
653
+        if (!empty($accessList['public'])) {
654
+            $publicShareKey = $this->getPublicShareKey();
655
+            if (empty($publicShareKey)) {
656
+                throw new PublicKeyMissingException($this->getPublicShareKeyId());
657
+            }
658
+            $publicKeys[$this->getPublicShareKeyId()] = $publicShareKey;
659
+        }
660
+
661
+        if ($this->recoveryKeyExists() &&
662
+            $this->util->isRecoveryEnabledForUser($uid)) {
663
+
664
+            $publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey();
665
+        }
666
+
667
+        return $publicKeys;
668
+    }
669
+
670
+    /**
671
+     * get master key password
672
+     *
673
+     * @return string
674
+     * @throws \Exception
675
+     */
676
+    public function getMasterKeyPassword() {
677
+        $password = $this->config->getSystemValue('secret');
678
+        if (empty($password)){
679
+            throw new \Exception('Can not get secret from ownCloud instance');
680
+        }
681
+
682
+        return $password;
683
+    }
684
+
685
+    /**
686
+     * return master key id
687
+     *
688
+     * @return string
689
+     */
690
+    public function getMasterKeyId() {
691
+        return $this->masterKeyId;
692
+    }
693
+
694
+    /**
695
+     * get public master key
696
+     *
697
+     * @return string
698
+     */
699
+    public function getPublicMasterKey() {
700
+        return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID);
701
+    }
702 702
 }
Please login to merge, or discard this patch.