Passed
Push — master ( c00d6f...a085a8 )
by Morris
09:54 queued 11s
created
apps/encryption/lib/Exceptions/PublicKeyMissingException.php 2 patches
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -25,14 +25,14 @@
 block discarded – undo
25 25
 
26 26
 class PublicKeyMissingException extends GenericEncryptionException {
27 27
 
28
-	/**
29
-	 * @param string $userId
30
-	 */
31
-	public function __construct($userId) {
32
-		if(empty($userId)) {
33
-			$userId = "<no-user-id-given>";
34
-		}
35
-		parent::__construct("Public Key missing for user: $userId");
36
-	}
28
+    /**
29
+     * @param string $userId
30
+     */
31
+    public function __construct($userId) {
32
+        if(empty($userId)) {
33
+            $userId = "<no-user-id-given>";
34
+        }
35
+        parent::__construct("Public Key missing for user: $userId");
36
+    }
37 37
 
38 38
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@
 block discarded – undo
29 29
 	 * @param string $userId
30 30
 	 */
31 31
 	public function __construct($userId) {
32
-		if(empty($userId)) {
32
+		if (empty($userId)) {
33 33
 			$userId = "<no-user-id-given>";
34 34
 		}
35 35
 		parent::__construct("Public Key missing for user: $userId");
Please login to merge, or discard this patch.
apps/encryption/lib/Exceptions/PrivateKeyMissingException.php 2 patches
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -28,14 +28,14 @@
 block discarded – undo
28 28
 
29 29
 class PrivateKeyMissingException extends GenericEncryptionException {
30 30
 
31
-	/**
32
-	 * @param string $userId
33
-	 */
34
-	public function __construct($userId) {
35
-		if(empty($userId)) {
36
-			$userId = "<no-user-id-given>";
37
-		}
38
-		parent::__construct("Private Key missing for user: $userId");
39
-	}
31
+    /**
32
+     * @param string $userId
33
+     */
34
+    public function __construct($userId) {
35
+        if(empty($userId)) {
36
+            $userId = "<no-user-id-given>";
37
+        }
38
+        parent::__construct("Private Key missing for user: $userId");
39
+    }
40 40
 
41 41
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@
 block discarded – undo
32 32
 	 * @param string $userId
33 33
 	 */
34 34
 	public function __construct($userId) {
35
-		if(empty($userId)) {
35
+		if (empty($userId)) {
36 36
 			$userId = "<no-user-id-given>";
37 37
 		}
38 38
 		parent::__construct("Private Key missing for user: $userId");
Please login to merge, or discard this patch.
apps/encryption/lib/Recovery.php 2 patches
Indentation   +287 added lines, -287 removed lines patch added patch discarded remove patch
@@ -38,293 +38,293 @@
 block discarded – undo
38 38
 class Recovery {
39 39
 
40 40
 
41
-	/**
42
-	 * @var null|IUser
43
-	 */
44
-	protected $user;
45
-	/**
46
-	 * @var Crypt
47
-	 */
48
-	protected $crypt;
49
-	/**
50
-	 * @var ISecureRandom
51
-	 */
52
-	private $random;
53
-	/**
54
-	 * @var KeyManager
55
-	 */
56
-	private $keyManager;
57
-	/**
58
-	 * @var IConfig
59
-	 */
60
-	private $config;
61
-	/**
62
-	 * @var IStorage
63
-	 */
64
-	private $keyStorage;
65
-	/**
66
-	 * @var View
67
-	 */
68
-	private $view;
69
-	/**
70
-	 * @var IFile
71
-	 */
72
-	private $file;
73
-
74
-	/**
75
-	 * @param IUserSession $user
76
-	 * @param Crypt $crypt
77
-	 * @param ISecureRandom $random
78
-	 * @param KeyManager $keyManager
79
-	 * @param IConfig $config
80
-	 * @param IStorage $keyStorage
81
-	 * @param IFile $file
82
-	 * @param View $view
83
-	 */
84
-	public function __construct(IUserSession $user,
85
-								Crypt $crypt,
86
-								ISecureRandom $random,
87
-								KeyManager $keyManager,
88
-								IConfig $config,
89
-								IStorage $keyStorage,
90
-								IFile $file,
91
-								View $view) {
92
-		$this->user = ($user && $user->isLoggedIn()) ? $user->getUser() : false;
93
-		$this->crypt = $crypt;
94
-		$this->random = $random;
95
-		$this->keyManager = $keyManager;
96
-		$this->config = $config;
97
-		$this->keyStorage = $keyStorage;
98
-		$this->view = $view;
99
-		$this->file = $file;
100
-	}
101
-
102
-	/**
103
-	 * @param string $password
104
-	 * @return bool
105
-	 */
106
-	public function enableAdminRecovery($password) {
107
-		$appConfig = $this->config;
108
-		$keyManager = $this->keyManager;
109
-
110
-		if (!$keyManager->recoveryKeyExists()) {
111
-			$keyPair = $this->crypt->createKeyPair();
112
-			if(!is_array($keyPair)) {
113
-				return false;
114
-			}
115
-
116
-			$this->keyManager->setRecoveryKey($password, $keyPair);
117
-		}
118
-
119
-		if ($keyManager->checkRecoveryPassword($password)) {
120
-			$appConfig->setAppValue('encryption', 'recoveryAdminEnabled', 1);
121
-			return true;
122
-		}
123
-
124
-		return false;
125
-	}
126
-
127
-	/**
128
-	 * change recovery key id
129
-	 *
130
-	 * @param string $newPassword
131
-	 * @param string $oldPassword
132
-	 * @return bool
133
-	 */
134
-	public function changeRecoveryKeyPassword($newPassword, $oldPassword) {
135
-		$recoveryKey = $this->keyManager->getSystemPrivateKey($this->keyManager->getRecoveryKeyId());
136
-		$decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $oldPassword);
137
-		if($decryptedRecoveryKey === false) {
138
-			return false;
139
-		}
140
-		$encryptedRecoveryKey = $this->crypt->encryptPrivateKey($decryptedRecoveryKey, $newPassword);
141
-		$header = $this->crypt->generateHeader();
142
-		if ($encryptedRecoveryKey) {
143
-			$this->keyManager->setSystemPrivateKey($this->keyManager->getRecoveryKeyId(), $header . $encryptedRecoveryKey);
144
-			return true;
145
-		}
146
-		return false;
147
-	}
148
-
149
-	/**
150
-	 * @param string $recoveryPassword
151
-	 * @return bool
152
-	 */
153
-	public function disableAdminRecovery($recoveryPassword) {
154
-		$keyManager = $this->keyManager;
155
-
156
-		if ($keyManager->checkRecoveryPassword($recoveryPassword)) {
157
-			// Set recoveryAdmin as disabled
158
-			$this->config->setAppValue('encryption', 'recoveryAdminEnabled', 0);
159
-			return true;
160
-		}
161
-		return false;
162
-	}
163
-
164
-	/**
165
-	 * check if recovery is enabled for user
166
-	 *
167
-	 * @param string $user if no user is given we check the current logged-in user
168
-	 *
169
-	 * @return bool
170
-	 */
171
-	public function isRecoveryEnabledForUser($user = '') {
172
-		$uid = empty($user) ? $this->user->getUID() : $user;
173
-		$recoveryMode = $this->config->getUserValue($uid,
174
-			'encryption',
175
-			'recoveryEnabled',
176
-			0);
177
-
178
-		return ($recoveryMode === '1');
179
-	}
180
-
181
-	/**
182
-	 * check if recovery is key is enabled by the administrator
183
-	 *
184
-	 * @return bool
185
-	 */
186
-	public function isRecoveryKeyEnabled() {
187
-		$enabled = $this->config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
188
-
189
-		return ($enabled === '1');
190
-	}
191
-
192
-	/**
193
-	 * @param string $value
194
-	 * @return bool
195
-	 */
196
-	public function setRecoveryForUser($value) {
197
-
198
-		try {
199
-			$this->config->setUserValue($this->user->getUID(),
200
-				'encryption',
201
-				'recoveryEnabled',
202
-				$value);
203
-
204
-			if ($value === '1') {
205
-				$this->addRecoveryKeys('/' . $this->user->getUID() . '/files/');
206
-			} else {
207
-				$this->removeRecoveryKeys('/' . $this->user->getUID() . '/files/');
208
-			}
209
-
210
-			return true;
211
-		} catch (PreConditionNotMetException $e) {
212
-			return false;
213
-		}
214
-	}
215
-
216
-	/**
217
-	 * add recovery key to all encrypted files
218
-	 * @param string $path
219
-	 */
220
-	private function addRecoveryKeys($path) {
221
-		$dirContent = $this->view->getDirectoryContent($path);
222
-		foreach ($dirContent as $item) {
223
-			$filePath = $item->getPath();
224
-			if ($item['type'] === 'dir') {
225
-				$this->addRecoveryKeys($filePath . '/');
226
-			} else {
227
-				$fileKey = $this->keyManager->getFileKey($filePath, $this->user->getUID());
228
-				if (!empty($fileKey)) {
229
-					$accessList = $this->file->getAccessList($filePath);
230
-					$publicKeys = array();
231
-					foreach ($accessList['users'] as $uid) {
232
-						$publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
233
-					}
234
-
235
-					$publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->user->getUID());
236
-
237
-					$encryptedKeyfiles = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
238
-					$this->keyManager->setAllFileKeys($filePath, $encryptedKeyfiles);
239
-				}
240
-			}
241
-		}
242
-	}
243
-
244
-	/**
245
-	 * remove recovery key to all encrypted files
246
-	 * @param string $path
247
-	 */
248
-	private function removeRecoveryKeys($path) {
249
-		$dirContent = $this->view->getDirectoryContent($path);
250
-		foreach ($dirContent as $item) {
251
-			$filePath = $item->getPath();
252
-			if ($item['type'] === 'dir') {
253
-				$this->removeRecoveryKeys($filePath . '/');
254
-			} else {
255
-				$this->keyManager->deleteShareKey($filePath, $this->keyManager->getRecoveryKeyId());
256
-			}
257
-		}
258
-	}
259
-
260
-	/**
261
-	 * recover users files with the recovery key
262
-	 *
263
-	 * @param string $recoveryPassword
264
-	 * @param string $user
265
-	 */
266
-	public function recoverUsersFiles($recoveryPassword, $user) {
267
-		$encryptedKey = $this->keyManager->getSystemPrivateKey($this->keyManager->getRecoveryKeyId());
268
-
269
-		$privateKey = $this->crypt->decryptPrivateKey($encryptedKey, $recoveryPassword);
270
-		if($privateKey !== false) {
271
-			$this->recoverAllFiles('/' . $user . '/files/', $privateKey, $user);
272
-		}
273
-	}
274
-
275
-	/**
276
-	 * recover users files
277
-	 *
278
-	 * @param string $path
279
-	 * @param string $privateKey
280
-	 * @param string $uid
281
-	 */
282
-	private function recoverAllFiles($path, $privateKey, $uid) {
283
-		$dirContent = $this->view->getDirectoryContent($path);
284
-
285
-		foreach ($dirContent as $item) {
286
-			// Get relative path from encryption/keyfiles
287
-			$filePath = $item->getPath();
288
-			if ($this->view->is_dir($filePath)) {
289
-				$this->recoverAllFiles($filePath . '/', $privateKey, $uid);
290
-			} else {
291
-				$this->recoverFile($filePath, $privateKey, $uid);
292
-			}
293
-		}
294
-
295
-	}
296
-
297
-	/**
298
-	 * recover file
299
-	 *
300
-	 * @param string $path
301
-	 * @param string $privateKey
302
-	 * @param string $uid
303
-	 */
304
-	private function recoverFile($path, $privateKey, $uid) {
305
-		$encryptedFileKey = $this->keyManager->getEncryptedFileKey($path);
306
-		$shareKey = $this->keyManager->getShareKey($path, $this->keyManager->getRecoveryKeyId());
307
-
308
-		if ($encryptedFileKey && $shareKey && $privateKey) {
309
-			$fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
310
-				$shareKey,
311
-				$privateKey);
312
-		}
313
-
314
-		if (!empty($fileKey)) {
315
-			$accessList = $this->file->getAccessList($path);
316
-			$publicKeys = array();
317
-			foreach ($accessList['users'] as $user) {
318
-				$publicKeys[$user] = $this->keyManager->getPublicKey($user);
319
-			}
320
-
321
-			$publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid);
322
-
323
-			$encryptedKeyfiles = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
324
-			$this->keyManager->setAllFileKeys($path, $encryptedKeyfiles);
325
-		}
326
-
327
-	}
41
+    /**
42
+     * @var null|IUser
43
+     */
44
+    protected $user;
45
+    /**
46
+     * @var Crypt
47
+     */
48
+    protected $crypt;
49
+    /**
50
+     * @var ISecureRandom
51
+     */
52
+    private $random;
53
+    /**
54
+     * @var KeyManager
55
+     */
56
+    private $keyManager;
57
+    /**
58
+     * @var IConfig
59
+     */
60
+    private $config;
61
+    /**
62
+     * @var IStorage
63
+     */
64
+    private $keyStorage;
65
+    /**
66
+     * @var View
67
+     */
68
+    private $view;
69
+    /**
70
+     * @var IFile
71
+     */
72
+    private $file;
73
+
74
+    /**
75
+     * @param IUserSession $user
76
+     * @param Crypt $crypt
77
+     * @param ISecureRandom $random
78
+     * @param KeyManager $keyManager
79
+     * @param IConfig $config
80
+     * @param IStorage $keyStorage
81
+     * @param IFile $file
82
+     * @param View $view
83
+     */
84
+    public function __construct(IUserSession $user,
85
+                                Crypt $crypt,
86
+                                ISecureRandom $random,
87
+                                KeyManager $keyManager,
88
+                                IConfig $config,
89
+                                IStorage $keyStorage,
90
+                                IFile $file,
91
+                                View $view) {
92
+        $this->user = ($user && $user->isLoggedIn()) ? $user->getUser() : false;
93
+        $this->crypt = $crypt;
94
+        $this->random = $random;
95
+        $this->keyManager = $keyManager;
96
+        $this->config = $config;
97
+        $this->keyStorage = $keyStorage;
98
+        $this->view = $view;
99
+        $this->file = $file;
100
+    }
101
+
102
+    /**
103
+     * @param string $password
104
+     * @return bool
105
+     */
106
+    public function enableAdminRecovery($password) {
107
+        $appConfig = $this->config;
108
+        $keyManager = $this->keyManager;
109
+
110
+        if (!$keyManager->recoveryKeyExists()) {
111
+            $keyPair = $this->crypt->createKeyPair();
112
+            if(!is_array($keyPair)) {
113
+                return false;
114
+            }
115
+
116
+            $this->keyManager->setRecoveryKey($password, $keyPair);
117
+        }
118
+
119
+        if ($keyManager->checkRecoveryPassword($password)) {
120
+            $appConfig->setAppValue('encryption', 'recoveryAdminEnabled', 1);
121
+            return true;
122
+        }
123
+
124
+        return false;
125
+    }
126
+
127
+    /**
128
+     * change recovery key id
129
+     *
130
+     * @param string $newPassword
131
+     * @param string $oldPassword
132
+     * @return bool
133
+     */
134
+    public function changeRecoveryKeyPassword($newPassword, $oldPassword) {
135
+        $recoveryKey = $this->keyManager->getSystemPrivateKey($this->keyManager->getRecoveryKeyId());
136
+        $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $oldPassword);
137
+        if($decryptedRecoveryKey === false) {
138
+            return false;
139
+        }
140
+        $encryptedRecoveryKey = $this->crypt->encryptPrivateKey($decryptedRecoveryKey, $newPassword);
141
+        $header = $this->crypt->generateHeader();
142
+        if ($encryptedRecoveryKey) {
143
+            $this->keyManager->setSystemPrivateKey($this->keyManager->getRecoveryKeyId(), $header . $encryptedRecoveryKey);
144
+            return true;
145
+        }
146
+        return false;
147
+    }
148
+
149
+    /**
150
+     * @param string $recoveryPassword
151
+     * @return bool
152
+     */
153
+    public function disableAdminRecovery($recoveryPassword) {
154
+        $keyManager = $this->keyManager;
155
+
156
+        if ($keyManager->checkRecoveryPassword($recoveryPassword)) {
157
+            // Set recoveryAdmin as disabled
158
+            $this->config->setAppValue('encryption', 'recoveryAdminEnabled', 0);
159
+            return true;
160
+        }
161
+        return false;
162
+    }
163
+
164
+    /**
165
+     * check if recovery is enabled for user
166
+     *
167
+     * @param string $user if no user is given we check the current logged-in user
168
+     *
169
+     * @return bool
170
+     */
171
+    public function isRecoveryEnabledForUser($user = '') {
172
+        $uid = empty($user) ? $this->user->getUID() : $user;
173
+        $recoveryMode = $this->config->getUserValue($uid,
174
+            'encryption',
175
+            'recoveryEnabled',
176
+            0);
177
+
178
+        return ($recoveryMode === '1');
179
+    }
180
+
181
+    /**
182
+     * check if recovery is key is enabled by the administrator
183
+     *
184
+     * @return bool
185
+     */
186
+    public function isRecoveryKeyEnabled() {
187
+        $enabled = $this->config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
188
+
189
+        return ($enabled === '1');
190
+    }
191
+
192
+    /**
193
+     * @param string $value
194
+     * @return bool
195
+     */
196
+    public function setRecoveryForUser($value) {
197
+
198
+        try {
199
+            $this->config->setUserValue($this->user->getUID(),
200
+                'encryption',
201
+                'recoveryEnabled',
202
+                $value);
203
+
204
+            if ($value === '1') {
205
+                $this->addRecoveryKeys('/' . $this->user->getUID() . '/files/');
206
+            } else {
207
+                $this->removeRecoveryKeys('/' . $this->user->getUID() . '/files/');
208
+            }
209
+
210
+            return true;
211
+        } catch (PreConditionNotMetException $e) {
212
+            return false;
213
+        }
214
+    }
215
+
216
+    /**
217
+     * add recovery key to all encrypted files
218
+     * @param string $path
219
+     */
220
+    private function addRecoveryKeys($path) {
221
+        $dirContent = $this->view->getDirectoryContent($path);
222
+        foreach ($dirContent as $item) {
223
+            $filePath = $item->getPath();
224
+            if ($item['type'] === 'dir') {
225
+                $this->addRecoveryKeys($filePath . '/');
226
+            } else {
227
+                $fileKey = $this->keyManager->getFileKey($filePath, $this->user->getUID());
228
+                if (!empty($fileKey)) {
229
+                    $accessList = $this->file->getAccessList($filePath);
230
+                    $publicKeys = array();
231
+                    foreach ($accessList['users'] as $uid) {
232
+                        $publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
233
+                    }
234
+
235
+                    $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->user->getUID());
236
+
237
+                    $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
238
+                    $this->keyManager->setAllFileKeys($filePath, $encryptedKeyfiles);
239
+                }
240
+            }
241
+        }
242
+    }
243
+
244
+    /**
245
+     * remove recovery key to all encrypted files
246
+     * @param string $path
247
+     */
248
+    private function removeRecoveryKeys($path) {
249
+        $dirContent = $this->view->getDirectoryContent($path);
250
+        foreach ($dirContent as $item) {
251
+            $filePath = $item->getPath();
252
+            if ($item['type'] === 'dir') {
253
+                $this->removeRecoveryKeys($filePath . '/');
254
+            } else {
255
+                $this->keyManager->deleteShareKey($filePath, $this->keyManager->getRecoveryKeyId());
256
+            }
257
+        }
258
+    }
259
+
260
+    /**
261
+     * recover users files with the recovery key
262
+     *
263
+     * @param string $recoveryPassword
264
+     * @param string $user
265
+     */
266
+    public function recoverUsersFiles($recoveryPassword, $user) {
267
+        $encryptedKey = $this->keyManager->getSystemPrivateKey($this->keyManager->getRecoveryKeyId());
268
+
269
+        $privateKey = $this->crypt->decryptPrivateKey($encryptedKey, $recoveryPassword);
270
+        if($privateKey !== false) {
271
+            $this->recoverAllFiles('/' . $user . '/files/', $privateKey, $user);
272
+        }
273
+    }
274
+
275
+    /**
276
+     * recover users files
277
+     *
278
+     * @param string $path
279
+     * @param string $privateKey
280
+     * @param string $uid
281
+     */
282
+    private function recoverAllFiles($path, $privateKey, $uid) {
283
+        $dirContent = $this->view->getDirectoryContent($path);
284
+
285
+        foreach ($dirContent as $item) {
286
+            // Get relative path from encryption/keyfiles
287
+            $filePath = $item->getPath();
288
+            if ($this->view->is_dir($filePath)) {
289
+                $this->recoverAllFiles($filePath . '/', $privateKey, $uid);
290
+            } else {
291
+                $this->recoverFile($filePath, $privateKey, $uid);
292
+            }
293
+        }
294
+
295
+    }
296
+
297
+    /**
298
+     * recover file
299
+     *
300
+     * @param string $path
301
+     * @param string $privateKey
302
+     * @param string $uid
303
+     */
304
+    private function recoverFile($path, $privateKey, $uid) {
305
+        $encryptedFileKey = $this->keyManager->getEncryptedFileKey($path);
306
+        $shareKey = $this->keyManager->getShareKey($path, $this->keyManager->getRecoveryKeyId());
307
+
308
+        if ($encryptedFileKey && $shareKey && $privateKey) {
309
+            $fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
310
+                $shareKey,
311
+                $privateKey);
312
+        }
313
+
314
+        if (!empty($fileKey)) {
315
+            $accessList = $this->file->getAccessList($path);
316
+            $publicKeys = array();
317
+            foreach ($accessList['users'] as $user) {
318
+                $publicKeys[$user] = $this->keyManager->getPublicKey($user);
319
+            }
320
+
321
+            $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid);
322
+
323
+            $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
324
+            $this->keyManager->setAllFileKeys($path, $encryptedKeyfiles);
325
+        }
326
+
327
+    }
328 328
 
329 329
 
330 330
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 
110 110
 		if (!$keyManager->recoveryKeyExists()) {
111 111
 			$keyPair = $this->crypt->createKeyPair();
112
-			if(!is_array($keyPair)) {
112
+			if (!is_array($keyPair)) {
113 113
 				return false;
114 114
 			}
115 115
 
@@ -134,13 +134,13 @@  discard block
 block discarded – undo
134 134
 	public function changeRecoveryKeyPassword($newPassword, $oldPassword) {
135 135
 		$recoveryKey = $this->keyManager->getSystemPrivateKey($this->keyManager->getRecoveryKeyId());
136 136
 		$decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $oldPassword);
137
-		if($decryptedRecoveryKey === false) {
137
+		if ($decryptedRecoveryKey === false) {
138 138
 			return false;
139 139
 		}
140 140
 		$encryptedRecoveryKey = $this->crypt->encryptPrivateKey($decryptedRecoveryKey, $newPassword);
141 141
 		$header = $this->crypt->generateHeader();
142 142
 		if ($encryptedRecoveryKey) {
143
-			$this->keyManager->setSystemPrivateKey($this->keyManager->getRecoveryKeyId(), $header . $encryptedRecoveryKey);
143
+			$this->keyManager->setSystemPrivateKey($this->keyManager->getRecoveryKeyId(), $header.$encryptedRecoveryKey);
144 144
 			return true;
145 145
 		}
146 146
 		return false;
@@ -202,9 +202,9 @@  discard block
 block discarded – undo
202 202
 				$value);
203 203
 
204 204
 			if ($value === '1') {
205
-				$this->addRecoveryKeys('/' . $this->user->getUID() . '/files/');
205
+				$this->addRecoveryKeys('/'.$this->user->getUID().'/files/');
206 206
 			} else {
207
-				$this->removeRecoveryKeys('/' . $this->user->getUID() . '/files/');
207
+				$this->removeRecoveryKeys('/'.$this->user->getUID().'/files/');
208 208
 			}
209 209
 
210 210
 			return true;
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 		foreach ($dirContent as $item) {
223 223
 			$filePath = $item->getPath();
224 224
 			if ($item['type'] === 'dir') {
225
-				$this->addRecoveryKeys($filePath . '/');
225
+				$this->addRecoveryKeys($filePath.'/');
226 226
 			} else {
227 227
 				$fileKey = $this->keyManager->getFileKey($filePath, $this->user->getUID());
228 228
 				if (!empty($fileKey)) {
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
 		foreach ($dirContent as $item) {
251 251
 			$filePath = $item->getPath();
252 252
 			if ($item['type'] === 'dir') {
253
-				$this->removeRecoveryKeys($filePath . '/');
253
+				$this->removeRecoveryKeys($filePath.'/');
254 254
 			} else {
255 255
 				$this->keyManager->deleteShareKey($filePath, $this->keyManager->getRecoveryKeyId());
256 256
 			}
@@ -267,8 +267,8 @@  discard block
 block discarded – undo
267 267
 		$encryptedKey = $this->keyManager->getSystemPrivateKey($this->keyManager->getRecoveryKeyId());
268 268
 
269 269
 		$privateKey = $this->crypt->decryptPrivateKey($encryptedKey, $recoveryPassword);
270
-		if($privateKey !== false) {
271
-			$this->recoverAllFiles('/' . $user . '/files/', $privateKey, $user);
270
+		if ($privateKey !== false) {
271
+			$this->recoverAllFiles('/'.$user.'/files/', $privateKey, $user);
272 272
 		}
273 273
 	}
274 274
 
@@ -286,7 +286,7 @@  discard block
 block discarded – undo
286 286
 			// Get relative path from encryption/keyfiles
287 287
 			$filePath = $item->getPath();
288 288
 			if ($this->view->is_dir($filePath)) {
289
-				$this->recoverAllFiles($filePath . '/', $privateKey, $uid);
289
+				$this->recoverAllFiles($filePath.'/', $privateKey, $uid);
290 290
 			} else {
291 291
 				$this->recoverFile($filePath, $privateKey, $uid);
292 292
 			}
Please login to merge, or discard this patch.
apps/encryption/lib/Command/EnableMasterKey.php 2 patches
Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -34,54 +34,54 @@
 block discarded – undo
34 34
 
35 35
 class EnableMasterKey extends Command {
36 36
 
37
-	/** @var Util */
38
-	protected $util;
39
-
40
-	/** @var IConfig */
41
-	protected $config;
42
-
43
-	/** @var  QuestionHelper */
44
-	protected $questionHelper;
45
-
46
-	/**
47
-	 * @param Util $util
48
-	 * @param IConfig $config
49
-	 * @param QuestionHelper $questionHelper
50
-	 */
51
-	public function __construct(Util $util,
52
-								IConfig $config,
53
-								QuestionHelper $questionHelper) {
54
-
55
-		$this->util = $util;
56
-		$this->config = $config;
57
-		$this->questionHelper = $questionHelper;
58
-		parent::__construct();
59
-	}
60
-
61
-	protected function configure() {
62
-		$this
63
-			->setName('encryption:enable-master-key')
64
-			->setDescription('Enable the master key. Only available for fresh installations with no existing encrypted data! There is also no way to disable it again.');
65
-	}
66
-
67
-	protected function execute(InputInterface $input, OutputInterface $output) {
68
-
69
-		$isAlreadyEnabled = $this->util->isMasterKeyEnabled();
70
-
71
-		if($isAlreadyEnabled) {
72
-			$output->writeln('Master key already enabled');
73
-		} else {
74
-			$question = new ConfirmationQuestion(
75
-				'Warning: Only available for fresh installations with no existing encrypted data! '
76
-			. 'There is also no way to disable it again. Do you want to continue? (y/n) ', false);
77
-			if ($this->questionHelper->ask($input, $output, $question)) {
78
-				$this->config->setAppValue('encryption', 'useMasterKey', '1');
79
-				$output->writeln('Master key successfully enabled.');
80
-			} else {
81
-				$output->writeln('aborted.');
82
-			}
83
-		}
84
-
85
-	}
37
+    /** @var Util */
38
+    protected $util;
39
+
40
+    /** @var IConfig */
41
+    protected $config;
42
+
43
+    /** @var  QuestionHelper */
44
+    protected $questionHelper;
45
+
46
+    /**
47
+     * @param Util $util
48
+     * @param IConfig $config
49
+     * @param QuestionHelper $questionHelper
50
+     */
51
+    public function __construct(Util $util,
52
+                                IConfig $config,
53
+                                QuestionHelper $questionHelper) {
54
+
55
+        $this->util = $util;
56
+        $this->config = $config;
57
+        $this->questionHelper = $questionHelper;
58
+        parent::__construct();
59
+    }
60
+
61
+    protected function configure() {
62
+        $this
63
+            ->setName('encryption:enable-master-key')
64
+            ->setDescription('Enable the master key. Only available for fresh installations with no existing encrypted data! There is also no way to disable it again.');
65
+    }
66
+
67
+    protected function execute(InputInterface $input, OutputInterface $output) {
68
+
69
+        $isAlreadyEnabled = $this->util->isMasterKeyEnabled();
70
+
71
+        if($isAlreadyEnabled) {
72
+            $output->writeln('Master key already enabled');
73
+        } else {
74
+            $question = new ConfirmationQuestion(
75
+                'Warning: Only available for fresh installations with no existing encrypted data! '
76
+            . 'There is also no way to disable it again. Do you want to continue? (y/n) ', false);
77
+            if ($this->questionHelper->ask($input, $output, $question)) {
78
+                $this->config->setAppValue('encryption', 'useMasterKey', '1');
79
+                $output->writeln('Master key successfully enabled.');
80
+            } else {
81
+                $output->writeln('aborted.');
82
+            }
83
+        }
84
+
85
+    }
86 86
 
87 87
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@
 block discarded – undo
68 68
 
69 69
 		$isAlreadyEnabled = $this->util->isMasterKeyEnabled();
70 70
 
71
-		if($isAlreadyEnabled) {
71
+		if ($isAlreadyEnabled) {
72 72
 			$output->writeln('Master key already enabled');
73 73
 		} else {
74 74
 			$question = new ConfirmationQuestion(
Please login to merge, or discard this patch.
apps/encryption/lib/Hooks/UserHooks.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
 			// Save private key
277 277
 			if ($encryptedPrivateKey) {
278 278
 				$this->keyManager->setPrivateKey($this->user->getUser()->getUID(),
279
-					$this->crypt->generateHeader() . $encryptedPrivateKey);
279
+					$this->crypt->generateHeader().$encryptedPrivateKey);
280 280
 			} else {
281 281
 				$this->logger->error('Encryption could not update users encryption password');
282 282
 			}
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
 				$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $newUserPassword, $user);
314 314
 
315 315
 				if ($encryptedKey) {
316
-					$this->keyManager->setPrivateKey($user, $this->crypt->generateHeader() . $encryptedKey);
316
+					$this->keyManager->setPrivateKey($user, $this->crypt->generateHeader().$encryptedKey);
317 317
 
318 318
 					if ($recoveryPassword) { // if recovery key is set we can re-encrypt the key files
319 319
 						$this->recovery->recoverUsersFiles($recoveryPassword, $user);
Please login to merge, or discard this patch.
Indentation   +302 added lines, -302 removed lines patch added patch discarded remove patch
@@ -43,306 +43,306 @@
 block discarded – undo
43 43
 
44 44
 class UserHooks implements IHook {
45 45
 
46
-	/**
47
-	 * list of user for which we perform a password reset
48
-	 * @var array
49
-	 */
50
-	protected static $passwordResetUsers = [];
51
-
52
-	/**
53
-	 * @var KeyManager
54
-	 */
55
-	private $keyManager;
56
-	/**
57
-	 * @var IUserManager
58
-	 */
59
-	private $userManager;
60
-	/**
61
-	 * @var ILogger
62
-	 */
63
-	private $logger;
64
-	/**
65
-	 * @var Setup
66
-	 */
67
-	private $userSetup;
68
-	/**
69
-	 * @var IUserSession
70
-	 */
71
-	private $user;
72
-	/**
73
-	 * @var Util
74
-	 */
75
-	private $util;
76
-	/**
77
-	 * @var Session
78
-	 */
79
-	private $session;
80
-	/**
81
-	 * @var Recovery
82
-	 */
83
-	private $recovery;
84
-	/**
85
-	 * @var Crypt
86
-	 */
87
-	private $crypt;
88
-
89
-	/**
90
-	 * UserHooks constructor.
91
-	 *
92
-	 * @param KeyManager $keyManager
93
-	 * @param IUserManager $userManager
94
-	 * @param ILogger $logger
95
-	 * @param Setup $userSetup
96
-	 * @param IUserSession $user
97
-	 * @param Util $util
98
-	 * @param Session $session
99
-	 * @param Crypt $crypt
100
-	 * @param Recovery $recovery
101
-	 */
102
-	public function __construct(KeyManager $keyManager,
103
-								IUserManager $userManager,
104
-								ILogger $logger,
105
-								Setup $userSetup,
106
-								IUserSession $user,
107
-								Util $util,
108
-								Session $session,
109
-								Crypt $crypt,
110
-								Recovery $recovery) {
111
-
112
-		$this->keyManager = $keyManager;
113
-		$this->userManager = $userManager;
114
-		$this->logger = $logger;
115
-		$this->userSetup = $userSetup;
116
-		$this->user = $user;
117
-		$this->util = $util;
118
-		$this->session = $session;
119
-		$this->recovery = $recovery;
120
-		$this->crypt = $crypt;
121
-	}
122
-
123
-	/**
124
-	 * Connects Hooks
125
-	 *
126
-	 * @return null
127
-	 */
128
-	public function addHooks() {
129
-		OCUtil::connectHook('OC_User', 'post_login', $this, 'login');
130
-		OCUtil::connectHook('OC_User', 'logout', $this, 'logout');
131
-
132
-		// this hooks only make sense if no master key is used
133
-		if ($this->util->isMasterKeyEnabled() === false) {
134
-			OCUtil::connectHook('OC_User',
135
-				'post_setPassword',
136
-				$this,
137
-				'setPassphrase');
138
-
139
-			OCUtil::connectHook('OC_User',
140
-				'pre_setPassword',
141
-				$this,
142
-				'preSetPassphrase');
143
-
144
-			OCUtil::connectHook('\OC\Core\LostPassword\Controller\LostController',
145
-				'post_passwordReset',
146
-				$this,
147
-				'postPasswordReset');
148
-
149
-			OCUtil::connectHook('\OC\Core\LostPassword\Controller\LostController',
150
-				'pre_passwordReset',
151
-				$this,
152
-				'prePasswordReset');
153
-
154
-			OCUtil::connectHook('OC_User',
155
-				'post_createUser',
156
-				$this,
157
-				'postCreateUser');
158
-
159
-			OCUtil::connectHook('OC_User',
160
-				'post_deleteUser',
161
-				$this,
162
-				'postDeleteUser');
163
-		}
164
-	}
165
-
166
-
167
-	/**
168
-	 * Startup encryption backend upon user login
169
-	 *
170
-	 * @note This method should never be called for users using client side encryption
171
-	 * @param array $params
172
-	 * @return boolean|null
173
-	 */
174
-	public function login($params) {
175
-		// ensure filesystem is loaded
176
-		if (!\OC\Files\Filesystem::$loaded) {
177
-			$this->setupFS($params['uid']);
178
-		}
179
-		if ($this->util->isMasterKeyEnabled() === false) {
180
-			$this->userSetup->setupUser($params['uid'], $params['password']);
181
-		}
182
-
183
-		$this->keyManager->init($params['uid'], $params['password']);
184
-	}
185
-
186
-	/**
187
-	 * remove keys from session during logout
188
-	 */
189
-	public function logout() {
190
-		$this->session->clear();
191
-	}
192
-
193
-	/**
194
-	 * setup encryption backend upon user created
195
-	 *
196
-	 * @note This method should never be called for users using client side encryption
197
-	 * @param array $params
198
-	 */
199
-	public function postCreateUser($params) {
200
-		$this->userSetup->setupUser($params['uid'], $params['password']);
201
-	}
202
-
203
-	/**
204
-	 * cleanup encryption backend upon user deleted
205
-	 *
206
-	 * @param array $params : uid, password
207
-	 * @note This method should never be called for users using client side encryption
208
-	 */
209
-	public function postDeleteUser($params) {
210
-		$this->keyManager->deletePublicKey($params['uid']);
211
-	}
212
-
213
-	public function prePasswordReset($params) {
214
-		$user = $params['uid'];
215
-		self::$passwordResetUsers[$user] = true;
216
-	}
217
-
218
-	public function postPasswordReset($params) {
219
-		$uid = $params['uid'];
220
-		$password = $params['password'];
221
-		$this->keyManager->backupUserKeys('passwordReset', $uid);
222
-		$this->keyManager->deleteUserKeys($uid);
223
-		$this->userSetup->setupUser($uid, $password);
224
-		unset(self::$passwordResetUsers[$uid]);
225
-	}
226
-
227
-	/**
228
-	 * If the password can't be changed within Nextcloud, than update the key password in advance.
229
-	 *
230
-	 * @param array $params : uid, password
231
-	 * @return boolean|null
232
-	 */
233
-	public function preSetPassphrase($params) {
234
-		$user = $this->userManager->get($params['uid']);
235
-
236
-		if ($user && !$user->canChangePassword()) {
237
-			$this->setPassphrase($params);
238
-		}
239
-	}
240
-
241
-	/**
242
-	 * Change a user's encryption passphrase
243
-	 *
244
-	 * @param array $params keys: uid, password
245
-	 * @return boolean|null
246
-	 */
247
-	public function setPassphrase($params) {
248
-
249
-		// if we are in the process to resetting a user password, we have nothing
250
-		// to do here
251
-		if (isset(self::$passwordResetUsers[$params['uid']])) {
252
-			return true;
253
-		}
254
-
255
-		// Get existing decrypted private key
256
-		$user = $this->user->getUser();
257
-
258
-		// current logged in user changes his own password
259
-		if ($user && $params['uid'] === $user->getUID()) {
260
-
261
-			$privateKey = $this->session->getPrivateKey();
262
-
263
-			// Encrypt private key with new user pwd as passphrase
264
-			$encryptedPrivateKey = $this->crypt->encryptPrivateKey($privateKey, $params['password'], $params['uid']);
265
-
266
-			// Save private key
267
-			if ($encryptedPrivateKey) {
268
-				$this->keyManager->setPrivateKey($this->user->getUser()->getUID(),
269
-					$this->crypt->generateHeader() . $encryptedPrivateKey);
270
-			} else {
271
-				$this->logger->error('Encryption could not update users encryption password');
272
-			}
273
-
274
-			// NOTE: Session does not need to be updated as the
275
-			// private key has not changed, only the passphrase
276
-			// used to decrypt it has changed
277
-		} else { // admin changed the password for a different user, create new keys and re-encrypt file keys
278
-			$user = $params['uid'];
279
-			$this->initMountPoints($user);
280
-			$recoveryPassword = isset($params['recoveryPassword']) ? $params['recoveryPassword'] : null;
281
-
282
-			$recoveryKeyId = $this->keyManager->getRecoveryKeyId();
283
-			$recoveryKey = $this->keyManager->getSystemPrivateKey($recoveryKeyId);
284
-			try {
285
-				$decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $recoveryPassword);
286
-			} catch (\Exception $e) {
287
-				$decryptedRecoveryKey = false;
288
-			}
289
-			if ($decryptedRecoveryKey === false) {
290
-				$message = 'Can not decrypt the recovery key. Maybe you provided the wrong password. Try again.';
291
-				throw new GenericEncryptionException($message, $message);
292
-			}
293
-
294
-			// we generate new keys if...
295
-			// ...we have a recovery password and the user enabled the recovery key
296
-			// ...encryption was activated for the first time (no keys exists)
297
-			// ...the user doesn't have any files
298
-			if (
299
-				($this->recovery->isRecoveryEnabledForUser($user) && $recoveryPassword)
300
-				|| !$this->keyManager->userHasKeys($user)
301
-				|| !$this->util->userHasFiles($user)
302
-			) {
303
-
304
-				// backup old keys
305
-				//$this->backupAllKeys('recovery');
306
-
307
-				$newUserPassword = $params['password'];
308
-
309
-				$keyPair = $this->crypt->createKeyPair();
310
-
311
-				// Save public key
312
-				$this->keyManager->setPublicKey($user, $keyPair['publicKey']);
313
-
314
-				// Encrypt private key with new password
315
-				$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $newUserPassword, $user);
316
-
317
-				if ($encryptedKey) {
318
-					$this->keyManager->setPrivateKey($user, $this->crypt->generateHeader() . $encryptedKey);
319
-
320
-					if ($recoveryPassword) { // if recovery key is set we can re-encrypt the key files
321
-						$this->recovery->recoverUsersFiles($recoveryPassword, $user);
322
-					}
323
-				} else {
324
-					$this->logger->error('Encryption Could not update users encryption password');
325
-				}
326
-			}
327
-		}
328
-	}
329
-
330
-	/**
331
-	 * init mount points for given user
332
-	 *
333
-	 * @param string $user
334
-	 * @throws \OC\User\NoUserException
335
-	 */
336
-	protected function initMountPoints($user) {
337
-		Filesystem::initMountPoints($user);
338
-	}
339
-
340
-	/**
341
-	 * setup file system for user
342
-	 *
343
-	 * @param string $uid user id
344
-	 */
345
-	protected function setupFS($uid) {
346
-		\OC_Util::setupFS($uid);
347
-	}
46
+    /**
47
+     * list of user for which we perform a password reset
48
+     * @var array
49
+     */
50
+    protected static $passwordResetUsers = [];
51
+
52
+    /**
53
+     * @var KeyManager
54
+     */
55
+    private $keyManager;
56
+    /**
57
+     * @var IUserManager
58
+     */
59
+    private $userManager;
60
+    /**
61
+     * @var ILogger
62
+     */
63
+    private $logger;
64
+    /**
65
+     * @var Setup
66
+     */
67
+    private $userSetup;
68
+    /**
69
+     * @var IUserSession
70
+     */
71
+    private $user;
72
+    /**
73
+     * @var Util
74
+     */
75
+    private $util;
76
+    /**
77
+     * @var Session
78
+     */
79
+    private $session;
80
+    /**
81
+     * @var Recovery
82
+     */
83
+    private $recovery;
84
+    /**
85
+     * @var Crypt
86
+     */
87
+    private $crypt;
88
+
89
+    /**
90
+     * UserHooks constructor.
91
+     *
92
+     * @param KeyManager $keyManager
93
+     * @param IUserManager $userManager
94
+     * @param ILogger $logger
95
+     * @param Setup $userSetup
96
+     * @param IUserSession $user
97
+     * @param Util $util
98
+     * @param Session $session
99
+     * @param Crypt $crypt
100
+     * @param Recovery $recovery
101
+     */
102
+    public function __construct(KeyManager $keyManager,
103
+                                IUserManager $userManager,
104
+                                ILogger $logger,
105
+                                Setup $userSetup,
106
+                                IUserSession $user,
107
+                                Util $util,
108
+                                Session $session,
109
+                                Crypt $crypt,
110
+                                Recovery $recovery) {
111
+
112
+        $this->keyManager = $keyManager;
113
+        $this->userManager = $userManager;
114
+        $this->logger = $logger;
115
+        $this->userSetup = $userSetup;
116
+        $this->user = $user;
117
+        $this->util = $util;
118
+        $this->session = $session;
119
+        $this->recovery = $recovery;
120
+        $this->crypt = $crypt;
121
+    }
122
+
123
+    /**
124
+     * Connects Hooks
125
+     *
126
+     * @return null
127
+     */
128
+    public function addHooks() {
129
+        OCUtil::connectHook('OC_User', 'post_login', $this, 'login');
130
+        OCUtil::connectHook('OC_User', 'logout', $this, 'logout');
131
+
132
+        // this hooks only make sense if no master key is used
133
+        if ($this->util->isMasterKeyEnabled() === false) {
134
+            OCUtil::connectHook('OC_User',
135
+                'post_setPassword',
136
+                $this,
137
+                'setPassphrase');
138
+
139
+            OCUtil::connectHook('OC_User',
140
+                'pre_setPassword',
141
+                $this,
142
+                'preSetPassphrase');
143
+
144
+            OCUtil::connectHook('\OC\Core\LostPassword\Controller\LostController',
145
+                'post_passwordReset',
146
+                $this,
147
+                'postPasswordReset');
148
+
149
+            OCUtil::connectHook('\OC\Core\LostPassword\Controller\LostController',
150
+                'pre_passwordReset',
151
+                $this,
152
+                'prePasswordReset');
153
+
154
+            OCUtil::connectHook('OC_User',
155
+                'post_createUser',
156
+                $this,
157
+                'postCreateUser');
158
+
159
+            OCUtil::connectHook('OC_User',
160
+                'post_deleteUser',
161
+                $this,
162
+                'postDeleteUser');
163
+        }
164
+    }
165
+
166
+
167
+    /**
168
+     * Startup encryption backend upon user login
169
+     *
170
+     * @note This method should never be called for users using client side encryption
171
+     * @param array $params
172
+     * @return boolean|null
173
+     */
174
+    public function login($params) {
175
+        // ensure filesystem is loaded
176
+        if (!\OC\Files\Filesystem::$loaded) {
177
+            $this->setupFS($params['uid']);
178
+        }
179
+        if ($this->util->isMasterKeyEnabled() === false) {
180
+            $this->userSetup->setupUser($params['uid'], $params['password']);
181
+        }
182
+
183
+        $this->keyManager->init($params['uid'], $params['password']);
184
+    }
185
+
186
+    /**
187
+     * remove keys from session during logout
188
+     */
189
+    public function logout() {
190
+        $this->session->clear();
191
+    }
192
+
193
+    /**
194
+     * setup encryption backend upon user created
195
+     *
196
+     * @note This method should never be called for users using client side encryption
197
+     * @param array $params
198
+     */
199
+    public function postCreateUser($params) {
200
+        $this->userSetup->setupUser($params['uid'], $params['password']);
201
+    }
202
+
203
+    /**
204
+     * cleanup encryption backend upon user deleted
205
+     *
206
+     * @param array $params : uid, password
207
+     * @note This method should never be called for users using client side encryption
208
+     */
209
+    public function postDeleteUser($params) {
210
+        $this->keyManager->deletePublicKey($params['uid']);
211
+    }
212
+
213
+    public function prePasswordReset($params) {
214
+        $user = $params['uid'];
215
+        self::$passwordResetUsers[$user] = true;
216
+    }
217
+
218
+    public function postPasswordReset($params) {
219
+        $uid = $params['uid'];
220
+        $password = $params['password'];
221
+        $this->keyManager->backupUserKeys('passwordReset', $uid);
222
+        $this->keyManager->deleteUserKeys($uid);
223
+        $this->userSetup->setupUser($uid, $password);
224
+        unset(self::$passwordResetUsers[$uid]);
225
+    }
226
+
227
+    /**
228
+     * If the password can't be changed within Nextcloud, than update the key password in advance.
229
+     *
230
+     * @param array $params : uid, password
231
+     * @return boolean|null
232
+     */
233
+    public function preSetPassphrase($params) {
234
+        $user = $this->userManager->get($params['uid']);
235
+
236
+        if ($user && !$user->canChangePassword()) {
237
+            $this->setPassphrase($params);
238
+        }
239
+    }
240
+
241
+    /**
242
+     * Change a user's encryption passphrase
243
+     *
244
+     * @param array $params keys: uid, password
245
+     * @return boolean|null
246
+     */
247
+    public function setPassphrase($params) {
248
+
249
+        // if we are in the process to resetting a user password, we have nothing
250
+        // to do here
251
+        if (isset(self::$passwordResetUsers[$params['uid']])) {
252
+            return true;
253
+        }
254
+
255
+        // Get existing decrypted private key
256
+        $user = $this->user->getUser();
257
+
258
+        // current logged in user changes his own password
259
+        if ($user && $params['uid'] === $user->getUID()) {
260
+
261
+            $privateKey = $this->session->getPrivateKey();
262
+
263
+            // Encrypt private key with new user pwd as passphrase
264
+            $encryptedPrivateKey = $this->crypt->encryptPrivateKey($privateKey, $params['password'], $params['uid']);
265
+
266
+            // Save private key
267
+            if ($encryptedPrivateKey) {
268
+                $this->keyManager->setPrivateKey($this->user->getUser()->getUID(),
269
+                    $this->crypt->generateHeader() . $encryptedPrivateKey);
270
+            } else {
271
+                $this->logger->error('Encryption could not update users encryption password');
272
+            }
273
+
274
+            // NOTE: Session does not need to be updated as the
275
+            // private key has not changed, only the passphrase
276
+            // used to decrypt it has changed
277
+        } else { // admin changed the password for a different user, create new keys and re-encrypt file keys
278
+            $user = $params['uid'];
279
+            $this->initMountPoints($user);
280
+            $recoveryPassword = isset($params['recoveryPassword']) ? $params['recoveryPassword'] : null;
281
+
282
+            $recoveryKeyId = $this->keyManager->getRecoveryKeyId();
283
+            $recoveryKey = $this->keyManager->getSystemPrivateKey($recoveryKeyId);
284
+            try {
285
+                $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $recoveryPassword);
286
+            } catch (\Exception $e) {
287
+                $decryptedRecoveryKey = false;
288
+            }
289
+            if ($decryptedRecoveryKey === false) {
290
+                $message = 'Can not decrypt the recovery key. Maybe you provided the wrong password. Try again.';
291
+                throw new GenericEncryptionException($message, $message);
292
+            }
293
+
294
+            // we generate new keys if...
295
+            // ...we have a recovery password and the user enabled the recovery key
296
+            // ...encryption was activated for the first time (no keys exists)
297
+            // ...the user doesn't have any files
298
+            if (
299
+                ($this->recovery->isRecoveryEnabledForUser($user) && $recoveryPassword)
300
+                || !$this->keyManager->userHasKeys($user)
301
+                || !$this->util->userHasFiles($user)
302
+            ) {
303
+
304
+                // backup old keys
305
+                //$this->backupAllKeys('recovery');
306
+
307
+                $newUserPassword = $params['password'];
308
+
309
+                $keyPair = $this->crypt->createKeyPair();
310
+
311
+                // Save public key
312
+                $this->keyManager->setPublicKey($user, $keyPair['publicKey']);
313
+
314
+                // Encrypt private key with new password
315
+                $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $newUserPassword, $user);
316
+
317
+                if ($encryptedKey) {
318
+                    $this->keyManager->setPrivateKey($user, $this->crypt->generateHeader() . $encryptedKey);
319
+
320
+                    if ($recoveryPassword) { // if recovery key is set we can re-encrypt the key files
321
+                        $this->recovery->recoverUsersFiles($recoveryPassword, $user);
322
+                    }
323
+                } else {
324
+                    $this->logger->error('Encryption Could not update users encryption password');
325
+                }
326
+            }
327
+        }
328
+    }
329
+
330
+    /**
331
+     * init mount points for given user
332
+     *
333
+     * @param string $user
334
+     * @throws \OC\User\NoUserException
335
+     */
336
+    protected function initMountPoints($user) {
337
+        Filesystem::initMountPoints($user);
338
+    }
339
+
340
+    /**
341
+     * setup file system for user
342
+     *
343
+     * @param string $uid user id
344
+     */
345
+    protected function setupFS($uid) {
346
+        \OC_Util::setupFS($uid);
347
+    }
348 348
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Hooks/Contracts/IHook.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -24,10 +24,10 @@
 block discarded – undo
24 24
 
25 25
 
26 26
 interface IHook {
27
-	/**
28
-	 * Connects Hooks
29
-	 *
30
-	 * @return null
31
-	 */
32
-	public function addHooks();
27
+    /**
28
+     * Connects Hooks
29
+     *
30
+     * @return null
31
+     */
32
+    public function addHooks();
33 33
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Crypto/Encryption.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 		$this->isWriteOperation = false;
178 178
 		$this->writeCache = '';
179 179
 
180
-		if($this->session->isReady() === false) {
180
+		if ($this->session->isReady() === false) {
181 181
 			// if the master key is enabled we can initialize encryption
182 182
 			// with a empty password and user name
183 183
 			if ($this->util->isMasterKeyEnabled()) {
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 		// always use the version from the original file, also part files
199 199
 		// need to have a correct version number if they get moved over to the
200 200
 		// final location
201
-		$this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
201
+		$this->version = (int) $this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
202 202
 
203 203
 		if (
204 204
 			$mode === 'w'
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 			// if we read a part file we need to increase the version by 1
215 215
 			// because the version number was also increased by writing
216 216
 			// the part file
217
-			if(Scanner::isPartialFile($path)) {
217
+			if (Scanner::isPartialFile($path)) {
218 218
 				$this->version = $this->version + 1;
219 219
 			}
220 220
 		}
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 		if ($this->writeCache) {
301 301
 
302 302
 			// Concat writeCache to start of $data
303
-			$data = $this->writeCache . $data;
303
+			$data = $this->writeCache.$data;
304 304
 
305 305
 			// Clear the write cache, ready for reuse - it has been
306 306
 			// flushed and its old contents processed
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
 					try {
403 403
 						$publicKeys[$user] = $this->keyManager->getPublicKey($user);
404 404
 					} catch (PublicKeyMissingException $e) {
405
-						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
405
+						$this->logger->warning('Could not encrypt file for '.$user.': '.$e->getMessage());
406 406
 					}
407 407
 				}
408 408
 			}
@@ -489,8 +489,8 @@  discard block
 block discarded – undo
489 489
 				// error message because in this case it means that the file was
490 490
 				// shared with the user at a point where the user didn't had a
491 491
 				// valid private/public key
492
-				$msg = 'Encryption module "' . $this->getDisplayName() .
493
-					'" is not able to read ' . $path;
492
+				$msg = 'Encryption module "'.$this->getDisplayName().
493
+					'" is not able to read '.$path;
494 494
 				$hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
495 495
 				$this->logger->warning($msg);
496 496
 				throw new DecryptionFailedException($msg, $hint);
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
 		$realPath = $path;
533 533
 		$parts = explode('/', $path);
534 534
 		if ($parts[2] === 'files_versions') {
535
-			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
535
+			$realPath = '/'.$parts[1].'/files/'.implode('/', array_slice($parts, 3));
536 536
 			$length = strrpos($realPath, '.');
537 537
 			$realPath = substr($realPath, 0, $length);
538 538
 		}
Please login to merge, or discard this patch.
Indentation   +553 added lines, -553 removed lines patch added patch discarded remove patch
@@ -45,557 +45,557 @@
 block discarded – undo
45 45
 
46 46
 class Encryption implements IEncryptionModule {
47 47
 
48
-	const ID = 'OC_DEFAULT_MODULE';
49
-	const DISPLAY_NAME = 'Default encryption module';
50
-
51
-	/**
52
-	 * @var Crypt
53
-	 */
54
-	private $crypt;
55
-
56
-	/** @var string */
57
-	private $cipher;
58
-
59
-	/** @var string */
60
-	private $path;
61
-
62
-	/** @var string */
63
-	private $user;
64
-
65
-	/** @var  array */
66
-	private $owner;
67
-
68
-	/** @var string */
69
-	private $fileKey;
70
-
71
-	/** @var string */
72
-	private $writeCache;
73
-
74
-	/** @var KeyManager */
75
-	private $keyManager;
76
-
77
-	/** @var array */
78
-	private $accessList;
79
-
80
-	/** @var boolean */
81
-	private $isWriteOperation;
82
-
83
-	/** @var Util */
84
-	private $util;
85
-
86
-	/** @var  Session */
87
-	private $session;
88
-
89
-	/** @var  ILogger */
90
-	private $logger;
91
-
92
-	/** @var IL10N */
93
-	private $l;
94
-
95
-	/** @var EncryptAll */
96
-	private $encryptAll;
97
-
98
-	/** @var  bool */
99
-	private $useMasterPassword;
100
-
101
-	/** @var DecryptAll  */
102
-	private $decryptAll;
103
-
104
-	/** @var int unencrypted block size if block contains signature */
105
-	private $unencryptedBlockSizeSigned = 6072;
106
-
107
-	/** @var int unencrypted block size */
108
-	private $unencryptedBlockSize = 6126;
109
-
110
-	/** @var int Current version of the file */
111
-	private $version = 0;
112
-
113
-	/** @var array remember encryption signature version */
114
-	private static $rememberVersion = [];
115
-
116
-
117
-	/**
118
-	 *
119
-	 * @param Crypt $crypt
120
-	 * @param KeyManager $keyManager
121
-	 * @param Util $util
122
-	 * @param Session $session
123
-	 * @param EncryptAll $encryptAll
124
-	 * @param DecryptAll $decryptAll
125
-	 * @param ILogger $logger
126
-	 * @param IL10N $il10n
127
-	 */
128
-	public function __construct(Crypt $crypt,
129
-								KeyManager $keyManager,
130
-								Util $util,
131
-								Session $session,
132
-								EncryptAll $encryptAll,
133
-								DecryptAll $decryptAll,
134
-								ILogger $logger,
135
-								IL10N $il10n) {
136
-		$this->crypt = $crypt;
137
-		$this->keyManager = $keyManager;
138
-		$this->util = $util;
139
-		$this->session = $session;
140
-		$this->encryptAll = $encryptAll;
141
-		$this->decryptAll = $decryptAll;
142
-		$this->logger = $logger;
143
-		$this->l = $il10n;
144
-		$this->owner = [];
145
-		$this->useMasterPassword = $util->isMasterKeyEnabled();
146
-	}
147
-
148
-	/**
149
-	 * @return string defining the technical unique id
150
-	 */
151
-	public function getId() {
152
-		return self::ID;
153
-	}
154
-
155
-	/**
156
-	 * In comparison to getKey() this function returns a human readable (maybe translated) name
157
-	 *
158
-	 * @return string
159
-	 */
160
-	public function getDisplayName() {
161
-		return self::DISPLAY_NAME;
162
-	}
163
-
164
-	/**
165
-	 * start receiving chunks from a file. This is the place where you can
166
-	 * perform some initial step before starting encrypting/decrypting the
167
-	 * chunks
168
-	 *
169
-	 * @param string $path to the file
170
-	 * @param string $user who read/write the file
171
-	 * @param string $mode php stream open mode
172
-	 * @param array $header contains the header data read from the file
173
-	 * @param array $accessList who has access to the file contains the key 'users' and 'public'
174
-	 *
175
-	 * @return array $header contain data as key-value pairs which should be
176
-	 *                       written to the header, in case of a write operation
177
-	 *                       or if no additional data is needed return a empty array
178
-	 */
179
-	public function begin($path, $user, $mode, array $header, array $accessList) {
180
-		$this->path = $this->getPathToRealFile($path);
181
-		$this->accessList = $accessList;
182
-		$this->user = $user;
183
-		$this->isWriteOperation = false;
184
-		$this->writeCache = '';
185
-
186
-		if($this->session->isReady() === false) {
187
-			// if the master key is enabled we can initialize encryption
188
-			// with a empty password and user name
189
-			if ($this->util->isMasterKeyEnabled()) {
190
-				$this->keyManager->init('', '');
191
-			}
192
-		}
193
-
194
-		if ($this->session->decryptAllModeActivated()) {
195
-			$encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
196
-			$shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
197
-			$this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
198
-				$shareKey,
199
-				$this->session->getDecryptAllKey());
200
-		} else {
201
-			$this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
202
-		}
203
-
204
-		// always use the version from the original file, also part files
205
-		// need to have a correct version number if they get moved over to the
206
-		// final location
207
-		$this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
208
-
209
-		if (
210
-			$mode === 'w'
211
-			|| $mode === 'w+'
212
-			|| $mode === 'wb'
213
-			|| $mode === 'wb+'
214
-		) {
215
-			$this->isWriteOperation = true;
216
-			if (empty($this->fileKey)) {
217
-				$this->fileKey = $this->crypt->generateFileKey();
218
-			}
219
-		} else {
220
-			// if we read a part file we need to increase the version by 1
221
-			// because the version number was also increased by writing
222
-			// the part file
223
-			if(Scanner::isPartialFile($path)) {
224
-				$this->version = $this->version + 1;
225
-			}
226
-		}
227
-
228
-		if ($this->isWriteOperation) {
229
-			$this->cipher = $this->crypt->getCipher();
230
-		} elseif (isset($header['cipher'])) {
231
-			$this->cipher = $header['cipher'];
232
-		} else {
233
-			// if we read a file without a header we fall-back to the legacy cipher
234
-			// which was used in <=oC6
235
-			$this->cipher = $this->crypt->getLegacyCipher();
236
-		}
237
-
238
-		return array('cipher' => $this->cipher, 'signed' => 'true');
239
-	}
240
-
241
-	/**
242
-	 * last chunk received. This is the place where you can perform some final
243
-	 * operation and return some remaining data if something is left in your
244
-	 * buffer.
245
-	 *
246
-	 * @param string $path to the file
247
-	 * @param int $position
248
-	 * @return string remained data which should be written to the file in case
249
-	 *                of a write operation
250
-	 * @throws PublicKeyMissingException
251
-	 * @throws \Exception
252
-	 * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
253
-	 */
254
-	public function end($path, $position = 0) {
255
-		$result = '';
256
-		if ($this->isWriteOperation) {
257
-			// in case of a part file we remember the new signature versions
258
-			// the version will be set later on update.
259
-			// This way we make sure that other apps listening to the pre-hooks
260
-			// still get the old version which should be the correct value for them
261
-			if (Scanner::isPartialFile($path)) {
262
-				self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
263
-			}
264
-			if (!empty($this->writeCache)) {
265
-				$result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
266
-				$this->writeCache = '';
267
-			}
268
-			$publicKeys = array();
269
-			if ($this->useMasterPassword === true) {
270
-				$publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
271
-			} else {
272
-				foreach ($this->accessList['users'] as $uid) {
273
-					try {
274
-						$publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
275
-					} catch (PublicKeyMissingException $e) {
276
-						$this->logger->warning(
277
-							'no public key found for user "{uid}", user will not be able to read the file',
278
-							['app' => 'encryption', 'uid' => $uid]
279
-						);
280
-						// if the public key of the owner is missing we should fail
281
-						if ($uid === $this->user) {
282
-							throw $e;
283
-						}
284
-					}
285
-				}
286
-			}
287
-
288
-			$publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path));
289
-			$encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
290
-			$this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
291
-		}
292
-		return $result;
293
-	}
294
-
295
-
296
-
297
-	/**
298
-	 * encrypt data
299
-	 *
300
-	 * @param string $data you want to encrypt
301
-	 * @param int $position
302
-	 * @return string encrypted data
303
-	 */
304
-	public function encrypt($data, $position = 0) {
305
-		// If extra data is left over from the last round, make sure it
306
-		// is integrated into the next block
307
-		if ($this->writeCache) {
308
-
309
-			// Concat writeCache to start of $data
310
-			$data = $this->writeCache . $data;
311
-
312
-			// Clear the write cache, ready for reuse - it has been
313
-			// flushed and its old contents processed
314
-			$this->writeCache = '';
315
-
316
-		}
317
-
318
-		$encrypted = '';
319
-		// While there still remains some data to be processed & written
320
-		while (strlen($data) > 0) {
321
-
322
-			// Remaining length for this iteration, not of the
323
-			// entire file (may be greater than 8192 bytes)
324
-			$remainingLength = strlen($data);
325
-
326
-			// If data remaining to be written is less than the
327
-			// size of 1 6126 byte block
328
-			if ($remainingLength < $this->unencryptedBlockSizeSigned) {
329
-
330
-				// Set writeCache to contents of $data
331
-				// The writeCache will be carried over to the
332
-				// next write round, and added to the start of
333
-				// $data to ensure that written blocks are
334
-				// always the correct length. If there is still
335
-				// data in writeCache after the writing round
336
-				// has finished, then the data will be written
337
-				// to disk by $this->flush().
338
-				$this->writeCache = $data;
339
-
340
-				// Clear $data ready for next round
341
-				$data = '';
342
-
343
-			} else {
344
-
345
-				// Read the chunk from the start of $data
346
-				$chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
347
-
348
-				$encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
349
-
350
-				// Remove the chunk we just processed from
351
-				// $data, leaving only unprocessed data in $data
352
-				// var, for handling on the next round
353
-				$data = substr($data, $this->unencryptedBlockSizeSigned);
354
-
355
-			}
356
-
357
-		}
358
-
359
-		return $encrypted;
360
-	}
361
-
362
-	/**
363
-	 * decrypt data
364
-	 *
365
-	 * @param string $data you want to decrypt
366
-	 * @param int $position
367
-	 * @return string decrypted data
368
-	 * @throws DecryptionFailedException
369
-	 */
370
-	public function decrypt($data, $position = 0) {
371
-		if (empty($this->fileKey)) {
372
-			$msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
373
-			$hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
374
-			$this->logger->error($msg);
375
-
376
-			throw new DecryptionFailedException($msg, $hint);
377
-		}
378
-
379
-		return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
380
-	}
381
-
382
-	/**
383
-	 * update encrypted file, e.g. give additional users access to the file
384
-	 *
385
-	 * @param string $path path to the file which should be updated
386
-	 * @param string $uid of the user who performs the operation
387
-	 * @param array $accessList who has access to the file contains the key 'users' and 'public'
388
-	 * @return boolean
389
-	 */
390
-	public function update($path, $uid, array $accessList) {
391
-
392
-		if (empty($accessList)) {
393
-			if (isset(self::$rememberVersion[$path])) {
394
-				$this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
395
-				unset(self::$rememberVersion[$path]);
396
-			}
397
-			return;
398
-		}
399
-
400
-		$fileKey = $this->keyManager->getFileKey($path, $uid);
401
-
402
-		if (!empty($fileKey)) {
403
-
404
-			$publicKeys = array();
405
-			if ($this->useMasterPassword === true) {
406
-				$publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
407
-			} else {
408
-				foreach ($accessList['users'] as $user) {
409
-					try {
410
-						$publicKeys[$user] = $this->keyManager->getPublicKey($user);
411
-					} catch (PublicKeyMissingException $e) {
412
-						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
413
-					}
414
-				}
415
-			}
416
-
417
-			$publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path));
418
-
419
-			$encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
420
-
421
-			$this->keyManager->deleteAllFileKeys($path);
422
-
423
-			$this->keyManager->setAllFileKeys($path, $encryptedFileKey);
424
-
425
-		} else {
426
-			$this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
427
-				array('file' => $path, 'app' => 'encryption'));
428
-
429
-			return false;
430
-		}
431
-
432
-		return true;
433
-	}
434
-
435
-	/**
436
-	 * should the file be encrypted or not
437
-	 *
438
-	 * @param string $path
439
-	 * @return boolean
440
-	 */
441
-	public function shouldEncrypt($path) {
442
-		if ($this->util->shouldEncryptHomeStorage() === false) {
443
-			$storage = $this->util->getStorage($path);
444
-			if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
445
-				return false;
446
-			}
447
-		}
448
-		$parts = explode('/', $path);
449
-		if (count($parts) < 4) {
450
-			return false;
451
-		}
452
-
453
-		if ($parts[2] === 'files') {
454
-			return true;
455
-		}
456
-		if ($parts[2] === 'files_versions') {
457
-			return true;
458
-		}
459
-		if ($parts[2] === 'files_trashbin') {
460
-			return true;
461
-		}
462
-
463
-		return false;
464
-	}
465
-
466
-	/**
467
-	 * get size of the unencrypted payload per block.
468
-	 * Nextcloud read/write files with a block size of 8192 byte
469
-	 *
470
-	 * @param bool $signed
471
-	 * @return int
472
-	 */
473
-	public function getUnencryptedBlockSize($signed = false) {
474
-		if ($signed === false) {
475
-			return $this->unencryptedBlockSize;
476
-		}
477
-
478
-		return $this->unencryptedBlockSizeSigned;
479
-	}
480
-
481
-	/**
482
-	 * check if the encryption module is able to read the file,
483
-	 * e.g. if all encryption keys exists
484
-	 *
485
-	 * @param string $path
486
-	 * @param string $uid user for whom we want to check if he can read the file
487
-	 * @return bool
488
-	 * @throws DecryptionFailedException
489
-	 */
490
-	public function isReadable($path, $uid) {
491
-		$fileKey = $this->keyManager->getFileKey($path, $uid);
492
-		if (empty($fileKey)) {
493
-			$owner = $this->util->getOwner($path);
494
-			if ($owner !== $uid) {
495
-				// if it is a shared file we throw a exception with a useful
496
-				// error message because in this case it means that the file was
497
-				// shared with the user at a point where the user didn't had a
498
-				// valid private/public key
499
-				$msg = 'Encryption module "' . $this->getDisplayName() .
500
-					'" is not able to read ' . $path;
501
-				$hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
502
-				$this->logger->warning($msg);
503
-				throw new DecryptionFailedException($msg, $hint);
504
-			}
505
-			return false;
506
-		}
507
-
508
-		return true;
509
-	}
510
-
511
-	/**
512
-	 * Initial encryption of all files
513
-	 *
514
-	 * @param InputInterface $input
515
-	 * @param OutputInterface $output write some status information to the terminal during encryption
516
-	 */
517
-	public function encryptAll(InputInterface $input, OutputInterface $output) {
518
-		$this->encryptAll->encryptAll($input, $output);
519
-	}
520
-
521
-	/**
522
-	 * prepare module to perform decrypt all operation
523
-	 *
524
-	 * @param InputInterface $input
525
-	 * @param OutputInterface $output
526
-	 * @param string $user
527
-	 * @return bool
528
-	 */
529
-	public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
530
-		return $this->decryptAll->prepare($input, $output, $user);
531
-	}
532
-
533
-
534
-	/**
535
-	 * @param string $path
536
-	 * @return string
537
-	 */
538
-	protected function getPathToRealFile($path) {
539
-		$realPath = $path;
540
-		$parts = explode('/', $path);
541
-		if ($parts[2] === 'files_versions') {
542
-			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
543
-			$length = strrpos($realPath, '.');
544
-			$realPath = substr($realPath, 0, $length);
545
-		}
546
-
547
-		return $realPath;
548
-	}
549
-
550
-	/**
551
-	 * remove .part file extension and the ocTransferId from the file to get the
552
-	 * original file name
553
-	 *
554
-	 * @param string $path
555
-	 * @return string
556
-	 */
557
-	protected function stripPartFileExtension($path) {
558
-		if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
559
-			$pos = strrpos($path, '.', -6);
560
-			$path = substr($path, 0, $pos);
561
-		}
562
-
563
-		return $path;
564
-	}
565
-
566
-	/**
567
-	 * get owner of a file
568
-	 *
569
-	 * @param string $path
570
-	 * @return string
571
-	 */
572
-	protected function getOwner($path) {
573
-		if (!isset($this->owner[$path])) {
574
-			$this->owner[$path] = $this->util->getOwner($path);
575
-		}
576
-		return $this->owner[$path];
577
-	}
578
-
579
-	/**
580
-	 * Check if the module is ready to be used by that specific user.
581
-	 * In case a module is not ready - because e.g. key pairs have not been generated
582
-	 * upon login this method can return false before any operation starts and might
583
-	 * cause issues during operations.
584
-	 *
585
-	 * @param string $user
586
-	 * @return boolean
587
-	 * @since 9.1.0
588
-	 */
589
-	public function isReadyForUser($user) {
590
-		return $this->keyManager->userHasKeys($user);
591
-	}
592
-
593
-	/**
594
-	 * We only need a detailed access list if the master key is not enabled
595
-	 *
596
-	 * @return bool
597
-	 */
598
-	public function needDetailedAccessList() {
599
-		return !$this->util->isMasterKeyEnabled();
600
-	}
48
+    const ID = 'OC_DEFAULT_MODULE';
49
+    const DISPLAY_NAME = 'Default encryption module';
50
+
51
+    /**
52
+     * @var Crypt
53
+     */
54
+    private $crypt;
55
+
56
+    /** @var string */
57
+    private $cipher;
58
+
59
+    /** @var string */
60
+    private $path;
61
+
62
+    /** @var string */
63
+    private $user;
64
+
65
+    /** @var  array */
66
+    private $owner;
67
+
68
+    /** @var string */
69
+    private $fileKey;
70
+
71
+    /** @var string */
72
+    private $writeCache;
73
+
74
+    /** @var KeyManager */
75
+    private $keyManager;
76
+
77
+    /** @var array */
78
+    private $accessList;
79
+
80
+    /** @var boolean */
81
+    private $isWriteOperation;
82
+
83
+    /** @var Util */
84
+    private $util;
85
+
86
+    /** @var  Session */
87
+    private $session;
88
+
89
+    /** @var  ILogger */
90
+    private $logger;
91
+
92
+    /** @var IL10N */
93
+    private $l;
94
+
95
+    /** @var EncryptAll */
96
+    private $encryptAll;
97
+
98
+    /** @var  bool */
99
+    private $useMasterPassword;
100
+
101
+    /** @var DecryptAll  */
102
+    private $decryptAll;
103
+
104
+    /** @var int unencrypted block size if block contains signature */
105
+    private $unencryptedBlockSizeSigned = 6072;
106
+
107
+    /** @var int unencrypted block size */
108
+    private $unencryptedBlockSize = 6126;
109
+
110
+    /** @var int Current version of the file */
111
+    private $version = 0;
112
+
113
+    /** @var array remember encryption signature version */
114
+    private static $rememberVersion = [];
115
+
116
+
117
+    /**
118
+     *
119
+     * @param Crypt $crypt
120
+     * @param KeyManager $keyManager
121
+     * @param Util $util
122
+     * @param Session $session
123
+     * @param EncryptAll $encryptAll
124
+     * @param DecryptAll $decryptAll
125
+     * @param ILogger $logger
126
+     * @param IL10N $il10n
127
+     */
128
+    public function __construct(Crypt $crypt,
129
+                                KeyManager $keyManager,
130
+                                Util $util,
131
+                                Session $session,
132
+                                EncryptAll $encryptAll,
133
+                                DecryptAll $decryptAll,
134
+                                ILogger $logger,
135
+                                IL10N $il10n) {
136
+        $this->crypt = $crypt;
137
+        $this->keyManager = $keyManager;
138
+        $this->util = $util;
139
+        $this->session = $session;
140
+        $this->encryptAll = $encryptAll;
141
+        $this->decryptAll = $decryptAll;
142
+        $this->logger = $logger;
143
+        $this->l = $il10n;
144
+        $this->owner = [];
145
+        $this->useMasterPassword = $util->isMasterKeyEnabled();
146
+    }
147
+
148
+    /**
149
+     * @return string defining the technical unique id
150
+     */
151
+    public function getId() {
152
+        return self::ID;
153
+    }
154
+
155
+    /**
156
+     * In comparison to getKey() this function returns a human readable (maybe translated) name
157
+     *
158
+     * @return string
159
+     */
160
+    public function getDisplayName() {
161
+        return self::DISPLAY_NAME;
162
+    }
163
+
164
+    /**
165
+     * start receiving chunks from a file. This is the place where you can
166
+     * perform some initial step before starting encrypting/decrypting the
167
+     * chunks
168
+     *
169
+     * @param string $path to the file
170
+     * @param string $user who read/write the file
171
+     * @param string $mode php stream open mode
172
+     * @param array $header contains the header data read from the file
173
+     * @param array $accessList who has access to the file contains the key 'users' and 'public'
174
+     *
175
+     * @return array $header contain data as key-value pairs which should be
176
+     *                       written to the header, in case of a write operation
177
+     *                       or if no additional data is needed return a empty array
178
+     */
179
+    public function begin($path, $user, $mode, array $header, array $accessList) {
180
+        $this->path = $this->getPathToRealFile($path);
181
+        $this->accessList = $accessList;
182
+        $this->user = $user;
183
+        $this->isWriteOperation = false;
184
+        $this->writeCache = '';
185
+
186
+        if($this->session->isReady() === false) {
187
+            // if the master key is enabled we can initialize encryption
188
+            // with a empty password and user name
189
+            if ($this->util->isMasterKeyEnabled()) {
190
+                $this->keyManager->init('', '');
191
+            }
192
+        }
193
+
194
+        if ($this->session->decryptAllModeActivated()) {
195
+            $encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
196
+            $shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
197
+            $this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
198
+                $shareKey,
199
+                $this->session->getDecryptAllKey());
200
+        } else {
201
+            $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
202
+        }
203
+
204
+        // always use the version from the original file, also part files
205
+        // need to have a correct version number if they get moved over to the
206
+        // final location
207
+        $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
208
+
209
+        if (
210
+            $mode === 'w'
211
+            || $mode === 'w+'
212
+            || $mode === 'wb'
213
+            || $mode === 'wb+'
214
+        ) {
215
+            $this->isWriteOperation = true;
216
+            if (empty($this->fileKey)) {
217
+                $this->fileKey = $this->crypt->generateFileKey();
218
+            }
219
+        } else {
220
+            // if we read a part file we need to increase the version by 1
221
+            // because the version number was also increased by writing
222
+            // the part file
223
+            if(Scanner::isPartialFile($path)) {
224
+                $this->version = $this->version + 1;
225
+            }
226
+        }
227
+
228
+        if ($this->isWriteOperation) {
229
+            $this->cipher = $this->crypt->getCipher();
230
+        } elseif (isset($header['cipher'])) {
231
+            $this->cipher = $header['cipher'];
232
+        } else {
233
+            // if we read a file without a header we fall-back to the legacy cipher
234
+            // which was used in <=oC6
235
+            $this->cipher = $this->crypt->getLegacyCipher();
236
+        }
237
+
238
+        return array('cipher' => $this->cipher, 'signed' => 'true');
239
+    }
240
+
241
+    /**
242
+     * last chunk received. This is the place where you can perform some final
243
+     * operation and return some remaining data if something is left in your
244
+     * buffer.
245
+     *
246
+     * @param string $path to the file
247
+     * @param int $position
248
+     * @return string remained data which should be written to the file in case
249
+     *                of a write operation
250
+     * @throws PublicKeyMissingException
251
+     * @throws \Exception
252
+     * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
253
+     */
254
+    public function end($path, $position = 0) {
255
+        $result = '';
256
+        if ($this->isWriteOperation) {
257
+            // in case of a part file we remember the new signature versions
258
+            // the version will be set later on update.
259
+            // This way we make sure that other apps listening to the pre-hooks
260
+            // still get the old version which should be the correct value for them
261
+            if (Scanner::isPartialFile($path)) {
262
+                self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
263
+            }
264
+            if (!empty($this->writeCache)) {
265
+                $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
266
+                $this->writeCache = '';
267
+            }
268
+            $publicKeys = array();
269
+            if ($this->useMasterPassword === true) {
270
+                $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
271
+            } else {
272
+                foreach ($this->accessList['users'] as $uid) {
273
+                    try {
274
+                        $publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
275
+                    } catch (PublicKeyMissingException $e) {
276
+                        $this->logger->warning(
277
+                            'no public key found for user "{uid}", user will not be able to read the file',
278
+                            ['app' => 'encryption', 'uid' => $uid]
279
+                        );
280
+                        // if the public key of the owner is missing we should fail
281
+                        if ($uid === $this->user) {
282
+                            throw $e;
283
+                        }
284
+                    }
285
+                }
286
+            }
287
+
288
+            $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path));
289
+            $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
290
+            $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
291
+        }
292
+        return $result;
293
+    }
294
+
295
+
296
+
297
+    /**
298
+     * encrypt data
299
+     *
300
+     * @param string $data you want to encrypt
301
+     * @param int $position
302
+     * @return string encrypted data
303
+     */
304
+    public function encrypt($data, $position = 0) {
305
+        // If extra data is left over from the last round, make sure it
306
+        // is integrated into the next block
307
+        if ($this->writeCache) {
308
+
309
+            // Concat writeCache to start of $data
310
+            $data = $this->writeCache . $data;
311
+
312
+            // Clear the write cache, ready for reuse - it has been
313
+            // flushed and its old contents processed
314
+            $this->writeCache = '';
315
+
316
+        }
317
+
318
+        $encrypted = '';
319
+        // While there still remains some data to be processed & written
320
+        while (strlen($data) > 0) {
321
+
322
+            // Remaining length for this iteration, not of the
323
+            // entire file (may be greater than 8192 bytes)
324
+            $remainingLength = strlen($data);
325
+
326
+            // If data remaining to be written is less than the
327
+            // size of 1 6126 byte block
328
+            if ($remainingLength < $this->unencryptedBlockSizeSigned) {
329
+
330
+                // Set writeCache to contents of $data
331
+                // The writeCache will be carried over to the
332
+                // next write round, and added to the start of
333
+                // $data to ensure that written blocks are
334
+                // always the correct length. If there is still
335
+                // data in writeCache after the writing round
336
+                // has finished, then the data will be written
337
+                // to disk by $this->flush().
338
+                $this->writeCache = $data;
339
+
340
+                // Clear $data ready for next round
341
+                $data = '';
342
+
343
+            } else {
344
+
345
+                // Read the chunk from the start of $data
346
+                $chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
347
+
348
+                $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
349
+
350
+                // Remove the chunk we just processed from
351
+                // $data, leaving only unprocessed data in $data
352
+                // var, for handling on the next round
353
+                $data = substr($data, $this->unencryptedBlockSizeSigned);
354
+
355
+            }
356
+
357
+        }
358
+
359
+        return $encrypted;
360
+    }
361
+
362
+    /**
363
+     * decrypt data
364
+     *
365
+     * @param string $data you want to decrypt
366
+     * @param int $position
367
+     * @return string decrypted data
368
+     * @throws DecryptionFailedException
369
+     */
370
+    public function decrypt($data, $position = 0) {
371
+        if (empty($this->fileKey)) {
372
+            $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
373
+            $hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
374
+            $this->logger->error($msg);
375
+
376
+            throw new DecryptionFailedException($msg, $hint);
377
+        }
378
+
379
+        return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
380
+    }
381
+
382
+    /**
383
+     * update encrypted file, e.g. give additional users access to the file
384
+     *
385
+     * @param string $path path to the file which should be updated
386
+     * @param string $uid of the user who performs the operation
387
+     * @param array $accessList who has access to the file contains the key 'users' and 'public'
388
+     * @return boolean
389
+     */
390
+    public function update($path, $uid, array $accessList) {
391
+
392
+        if (empty($accessList)) {
393
+            if (isset(self::$rememberVersion[$path])) {
394
+                $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
395
+                unset(self::$rememberVersion[$path]);
396
+            }
397
+            return;
398
+        }
399
+
400
+        $fileKey = $this->keyManager->getFileKey($path, $uid);
401
+
402
+        if (!empty($fileKey)) {
403
+
404
+            $publicKeys = array();
405
+            if ($this->useMasterPassword === true) {
406
+                $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
407
+            } else {
408
+                foreach ($accessList['users'] as $user) {
409
+                    try {
410
+                        $publicKeys[$user] = $this->keyManager->getPublicKey($user);
411
+                    } catch (PublicKeyMissingException $e) {
412
+                        $this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
413
+                    }
414
+                }
415
+            }
416
+
417
+            $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path));
418
+
419
+            $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
420
+
421
+            $this->keyManager->deleteAllFileKeys($path);
422
+
423
+            $this->keyManager->setAllFileKeys($path, $encryptedFileKey);
424
+
425
+        } else {
426
+            $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
427
+                array('file' => $path, 'app' => 'encryption'));
428
+
429
+            return false;
430
+        }
431
+
432
+        return true;
433
+    }
434
+
435
+    /**
436
+     * should the file be encrypted or not
437
+     *
438
+     * @param string $path
439
+     * @return boolean
440
+     */
441
+    public function shouldEncrypt($path) {
442
+        if ($this->util->shouldEncryptHomeStorage() === false) {
443
+            $storage = $this->util->getStorage($path);
444
+            if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
445
+                return false;
446
+            }
447
+        }
448
+        $parts = explode('/', $path);
449
+        if (count($parts) < 4) {
450
+            return false;
451
+        }
452
+
453
+        if ($parts[2] === 'files') {
454
+            return true;
455
+        }
456
+        if ($parts[2] === 'files_versions') {
457
+            return true;
458
+        }
459
+        if ($parts[2] === 'files_trashbin') {
460
+            return true;
461
+        }
462
+
463
+        return false;
464
+    }
465
+
466
+    /**
467
+     * get size of the unencrypted payload per block.
468
+     * Nextcloud read/write files with a block size of 8192 byte
469
+     *
470
+     * @param bool $signed
471
+     * @return int
472
+     */
473
+    public function getUnencryptedBlockSize($signed = false) {
474
+        if ($signed === false) {
475
+            return $this->unencryptedBlockSize;
476
+        }
477
+
478
+        return $this->unencryptedBlockSizeSigned;
479
+    }
480
+
481
+    /**
482
+     * check if the encryption module is able to read the file,
483
+     * e.g. if all encryption keys exists
484
+     *
485
+     * @param string $path
486
+     * @param string $uid user for whom we want to check if he can read the file
487
+     * @return bool
488
+     * @throws DecryptionFailedException
489
+     */
490
+    public function isReadable($path, $uid) {
491
+        $fileKey = $this->keyManager->getFileKey($path, $uid);
492
+        if (empty($fileKey)) {
493
+            $owner = $this->util->getOwner($path);
494
+            if ($owner !== $uid) {
495
+                // if it is a shared file we throw a exception with a useful
496
+                // error message because in this case it means that the file was
497
+                // shared with the user at a point where the user didn't had a
498
+                // valid private/public key
499
+                $msg = 'Encryption module "' . $this->getDisplayName() .
500
+                    '" is not able to read ' . $path;
501
+                $hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
502
+                $this->logger->warning($msg);
503
+                throw new DecryptionFailedException($msg, $hint);
504
+            }
505
+            return false;
506
+        }
507
+
508
+        return true;
509
+    }
510
+
511
+    /**
512
+     * Initial encryption of all files
513
+     *
514
+     * @param InputInterface $input
515
+     * @param OutputInterface $output write some status information to the terminal during encryption
516
+     */
517
+    public function encryptAll(InputInterface $input, OutputInterface $output) {
518
+        $this->encryptAll->encryptAll($input, $output);
519
+    }
520
+
521
+    /**
522
+     * prepare module to perform decrypt all operation
523
+     *
524
+     * @param InputInterface $input
525
+     * @param OutputInterface $output
526
+     * @param string $user
527
+     * @return bool
528
+     */
529
+    public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
530
+        return $this->decryptAll->prepare($input, $output, $user);
531
+    }
532
+
533
+
534
+    /**
535
+     * @param string $path
536
+     * @return string
537
+     */
538
+    protected function getPathToRealFile($path) {
539
+        $realPath = $path;
540
+        $parts = explode('/', $path);
541
+        if ($parts[2] === 'files_versions') {
542
+            $realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
543
+            $length = strrpos($realPath, '.');
544
+            $realPath = substr($realPath, 0, $length);
545
+        }
546
+
547
+        return $realPath;
548
+    }
549
+
550
+    /**
551
+     * remove .part file extension and the ocTransferId from the file to get the
552
+     * original file name
553
+     *
554
+     * @param string $path
555
+     * @return string
556
+     */
557
+    protected function stripPartFileExtension($path) {
558
+        if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
559
+            $pos = strrpos($path, '.', -6);
560
+            $path = substr($path, 0, $pos);
561
+        }
562
+
563
+        return $path;
564
+    }
565
+
566
+    /**
567
+     * get owner of a file
568
+     *
569
+     * @param string $path
570
+     * @return string
571
+     */
572
+    protected function getOwner($path) {
573
+        if (!isset($this->owner[$path])) {
574
+            $this->owner[$path] = $this->util->getOwner($path);
575
+        }
576
+        return $this->owner[$path];
577
+    }
578
+
579
+    /**
580
+     * Check if the module is ready to be used by that specific user.
581
+     * In case a module is not ready - because e.g. key pairs have not been generated
582
+     * upon login this method can return false before any operation starts and might
583
+     * cause issues during operations.
584
+     *
585
+     * @param string $user
586
+     * @return boolean
587
+     * @since 9.1.0
588
+     */
589
+    public function isReadyForUser($user) {
590
+        return $this->keyManager->userHasKeys($user);
591
+    }
592
+
593
+    /**
594
+     * We only need a detailed access list if the master key is not enabled
595
+     *
596
+     * @return bool
597
+     */
598
+    public function needDetailedAccessList() {
599
+        return !$this->util->isMasterKeyEnabled();
600
+    }
601 601
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Crypto/DecryptAll.php 2 patches
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -35,127 +35,127 @@
 block discarded – undo
35 35
 
36 36
 class DecryptAll {
37 37
 
38
-	/** @var Util  */
39
-	protected $util;
40
-
41
-	/** @var QuestionHelper  */
42
-	protected $questionHelper;
43
-
44
-	/** @var  Crypt */
45
-	protected $crypt;
46
-
47
-	/** @var  KeyManager */
48
-	protected $keyManager;
49
-
50
-	/** @var Session  */
51
-	protected $session;
52
-
53
-	/**
54
-	 * @param Util $util
55
-	 * @param KeyManager $keyManager
56
-	 * @param Crypt $crypt
57
-	 * @param Session $session
58
-	 * @param QuestionHelper $questionHelper
59
-	 */
60
-	public function __construct(
61
-		Util $util,
62
-		KeyManager $keyManager,
63
-		Crypt $crypt,
64
-		Session $session,
65
-		QuestionHelper $questionHelper
66
-	) {
67
-		$this->util = $util;
68
-		$this->keyManager = $keyManager;
69
-		$this->crypt = $crypt;
70
-		$this->session = $session;
71
-		$this->questionHelper = $questionHelper;
72
-	}
73
-
74
-	/**
75
-	 * prepare encryption module to decrypt all files
76
-	 *
77
-	 * @param InputInterface $input
78
-	 * @param OutputInterface $output
79
-	 * @param $user
80
-	 * @return bool
81
-	 */
82
-	public function prepare(InputInterface $input, OutputInterface $output, $user) {
83
-
84
-		$question = new Question('Please enter the recovery key password: ');
85
-
86
-		if($this->util->isMasterKeyEnabled()) {
87
-			$output->writeln('Use master key to decrypt all files');
88
-			$user = $this->keyManager->getMasterKeyId();
89
-			$password =$this->keyManager->getMasterKeyPassword();
90
-		} else {
91
-			$recoveryKeyId = $this->keyManager->getRecoveryKeyId();
92
-			if (!empty($user)) {
93
-				$output->writeln('You can only decrypt the users files if you know');
94
-				$output->writeln('the users password or if he activated the recovery key.');
95
-				$output->writeln('');
96
-				$questionUseLoginPassword = new ConfirmationQuestion(
97
-					'Do you want to use the users login password to decrypt all files? (y/n) ',
98
-					false
99
-				);
100
-				$useLoginPassword = $this->questionHelper->ask($input, $output, $questionUseLoginPassword);
101
-				if ($useLoginPassword) {
102
-					$question = new Question('Please enter the user\'s login password: ');
103
-				} else if ($this->util->isRecoveryEnabledForUser($user) === false) {
104
-					$output->writeln('No recovery key available for user ' . $user);
105
-					return false;
106
-				} else {
107
-					$user = $recoveryKeyId;
108
-				}
109
-			} else {
110
-				$output->writeln('You can only decrypt the files of all users if the');
111
-				$output->writeln('recovery key is enabled by the admin and activated by the users.');
112
-				$output->writeln('');
113
-				$user = $recoveryKeyId;
114
-			}
115
-
116
-			$question->setHidden(true);
117
-			$question->setHiddenFallback(false);
118
-			$password = $this->questionHelper->ask($input, $output, $question);
119
-		}
120
-
121
-		$privateKey = $this->getPrivateKey($user, $password);
122
-		if ($privateKey !== false) {
123
-			$this->updateSession($user, $privateKey);
124
-			return true;
125
-		} else {
126
-			$output->writeln('Could not decrypt private key, maybe you entered the wrong password?');
127
-		}
128
-
129
-
130
-		return false;
131
-	}
132
-
133
-	/**
134
-	 * get the private key which will be used to decrypt all files
135
-	 *
136
-	 * @param string $user
137
-	 * @param string $password
138
-	 * @return bool|string
139
-	 * @throws \OCA\Encryption\Exceptions\PrivateKeyMissingException
140
-	 */
141
-	protected function getPrivateKey($user, $password) {
142
-		$recoveryKeyId = $this->keyManager->getRecoveryKeyId();
143
-		$masterKeyId = $this->keyManager->getMasterKeyId();
144
-		if ($user === $recoveryKeyId) {
145
-			$recoveryKey = $this->keyManager->getSystemPrivateKey($recoveryKeyId);
146
-			$privateKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
147
-		} elseif ($user === $masterKeyId) {
148
-			$masterKey = $this->keyManager->getSystemPrivateKey($masterKeyId);
149
-			$privateKey = $this->crypt->decryptPrivateKey($masterKey, $password, $masterKeyId);
150
-		} else {
151
-			$userKey = $this->keyManager->getPrivateKey($user);
152
-			$privateKey = $this->crypt->decryptPrivateKey($userKey, $password, $user);
153
-		}
154
-
155
-		return $privateKey;
156
-	}
157
-
158
-	protected function updateSession($user, $privateKey) {
159
-		$this->session->prepareDecryptAll($user, $privateKey);
160
-	}
38
+    /** @var Util  */
39
+    protected $util;
40
+
41
+    /** @var QuestionHelper  */
42
+    protected $questionHelper;
43
+
44
+    /** @var  Crypt */
45
+    protected $crypt;
46
+
47
+    /** @var  KeyManager */
48
+    protected $keyManager;
49
+
50
+    /** @var Session  */
51
+    protected $session;
52
+
53
+    /**
54
+     * @param Util $util
55
+     * @param KeyManager $keyManager
56
+     * @param Crypt $crypt
57
+     * @param Session $session
58
+     * @param QuestionHelper $questionHelper
59
+     */
60
+    public function __construct(
61
+        Util $util,
62
+        KeyManager $keyManager,
63
+        Crypt $crypt,
64
+        Session $session,
65
+        QuestionHelper $questionHelper
66
+    ) {
67
+        $this->util = $util;
68
+        $this->keyManager = $keyManager;
69
+        $this->crypt = $crypt;
70
+        $this->session = $session;
71
+        $this->questionHelper = $questionHelper;
72
+    }
73
+
74
+    /**
75
+     * prepare encryption module to decrypt all files
76
+     *
77
+     * @param InputInterface $input
78
+     * @param OutputInterface $output
79
+     * @param $user
80
+     * @return bool
81
+     */
82
+    public function prepare(InputInterface $input, OutputInterface $output, $user) {
83
+
84
+        $question = new Question('Please enter the recovery key password: ');
85
+
86
+        if($this->util->isMasterKeyEnabled()) {
87
+            $output->writeln('Use master key to decrypt all files');
88
+            $user = $this->keyManager->getMasterKeyId();
89
+            $password =$this->keyManager->getMasterKeyPassword();
90
+        } else {
91
+            $recoveryKeyId = $this->keyManager->getRecoveryKeyId();
92
+            if (!empty($user)) {
93
+                $output->writeln('You can only decrypt the users files if you know');
94
+                $output->writeln('the users password or if he activated the recovery key.');
95
+                $output->writeln('');
96
+                $questionUseLoginPassword = new ConfirmationQuestion(
97
+                    'Do you want to use the users login password to decrypt all files? (y/n) ',
98
+                    false
99
+                );
100
+                $useLoginPassword = $this->questionHelper->ask($input, $output, $questionUseLoginPassword);
101
+                if ($useLoginPassword) {
102
+                    $question = new Question('Please enter the user\'s login password: ');
103
+                } else if ($this->util->isRecoveryEnabledForUser($user) === false) {
104
+                    $output->writeln('No recovery key available for user ' . $user);
105
+                    return false;
106
+                } else {
107
+                    $user = $recoveryKeyId;
108
+                }
109
+            } else {
110
+                $output->writeln('You can only decrypt the files of all users if the');
111
+                $output->writeln('recovery key is enabled by the admin and activated by the users.');
112
+                $output->writeln('');
113
+                $user = $recoveryKeyId;
114
+            }
115
+
116
+            $question->setHidden(true);
117
+            $question->setHiddenFallback(false);
118
+            $password = $this->questionHelper->ask($input, $output, $question);
119
+        }
120
+
121
+        $privateKey = $this->getPrivateKey($user, $password);
122
+        if ($privateKey !== false) {
123
+            $this->updateSession($user, $privateKey);
124
+            return true;
125
+        } else {
126
+            $output->writeln('Could not decrypt private key, maybe you entered the wrong password?');
127
+        }
128
+
129
+
130
+        return false;
131
+    }
132
+
133
+    /**
134
+     * get the private key which will be used to decrypt all files
135
+     *
136
+     * @param string $user
137
+     * @param string $password
138
+     * @return bool|string
139
+     * @throws \OCA\Encryption\Exceptions\PrivateKeyMissingException
140
+     */
141
+    protected function getPrivateKey($user, $password) {
142
+        $recoveryKeyId = $this->keyManager->getRecoveryKeyId();
143
+        $masterKeyId = $this->keyManager->getMasterKeyId();
144
+        if ($user === $recoveryKeyId) {
145
+            $recoveryKey = $this->keyManager->getSystemPrivateKey($recoveryKeyId);
146
+            $privateKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
147
+        } elseif ($user === $masterKeyId) {
148
+            $masterKey = $this->keyManager->getSystemPrivateKey($masterKeyId);
149
+            $privateKey = $this->crypt->decryptPrivateKey($masterKey, $password, $masterKeyId);
150
+        } else {
151
+            $userKey = $this->keyManager->getPrivateKey($user);
152
+            $privateKey = $this->crypt->decryptPrivateKey($userKey, $password, $user);
153
+        }
154
+
155
+        return $privateKey;
156
+    }
157
+
158
+    protected function updateSession($user, $privateKey) {
159
+        $this->session->prepareDecryptAll($user, $privateKey);
160
+    }
161 161
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -83,10 +83,10 @@  discard block
 block discarded – undo
83 83
 
84 84
 		$question = new Question('Please enter the recovery key password: ');
85 85
 
86
-		if($this->util->isMasterKeyEnabled()) {
86
+		if ($this->util->isMasterKeyEnabled()) {
87 87
 			$output->writeln('Use master key to decrypt all files');
88 88
 			$user = $this->keyManager->getMasterKeyId();
89
-			$password =$this->keyManager->getMasterKeyPassword();
89
+			$password = $this->keyManager->getMasterKeyPassword();
90 90
 		} else {
91 91
 			$recoveryKeyId = $this->keyManager->getRecoveryKeyId();
92 92
 			if (!empty($user)) {
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 				if ($useLoginPassword) {
102 102
 					$question = new Question('Please enter the user\'s login password: ');
103 103
 				} else if ($this->util->isRecoveryEnabledForUser($user) === false) {
104
-					$output->writeln('No recovery key available for user ' . $user);
104
+					$output->writeln('No recovery key available for user '.$user);
105 105
 					return false;
106 106
 				} else {
107 107
 					$user = $recoveryKeyId;
Please login to merge, or discard this patch.
apps/encryption/lib/HookManager.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -28,38 +28,38 @@
 block discarded – undo
28 28
 
29 29
 class HookManager {
30 30
 
31
-	private $hookInstances = [];
31
+    private $hookInstances = [];
32 32
 
33
-	/**
34
-	 * @param array|IHook $instances
35
-	 *        - This accepts either a single instance of IHook or an array of instances of IHook
36
-	 * @return bool
37
-	 */
38
-	public function registerHook($instances) {
39
-		if (is_array($instances)) {
40
-			foreach ($instances as $instance) {
41
-				if (!$instance instanceof IHook) {
42
-					return false;
43
-				}
44
-				$this->hookInstances[] = $instance;
45
-			}
33
+    /**
34
+     * @param array|IHook $instances
35
+     *        - This accepts either a single instance of IHook or an array of instances of IHook
36
+     * @return bool
37
+     */
38
+    public function registerHook($instances) {
39
+        if (is_array($instances)) {
40
+            foreach ($instances as $instance) {
41
+                if (!$instance instanceof IHook) {
42
+                    return false;
43
+                }
44
+                $this->hookInstances[] = $instance;
45
+            }
46 46
 
47
-		} elseif ($instances instanceof IHook) {
48
-			$this->hookInstances[] = $instances;
49
-		}
50
-		return true;
51
-	}
47
+        } elseif ($instances instanceof IHook) {
48
+            $this->hookInstances[] = $instances;
49
+        }
50
+        return true;
51
+    }
52 52
 
53
-	public function fireHooks() {
54
-		foreach ($this->hookInstances as $instance) {
55
-			/**
56
-			 * Fire off the add hooks method of each instance stored in cache
57
-			 *
58
-			 * @var $instance IHook
59
-			 */
60
-			$instance->addHooks();
61
-		}
53
+    public function fireHooks() {
54
+        foreach ($this->hookInstances as $instance) {
55
+            /**
56
+             * Fire off the add hooks method of each instance stored in cache
57
+             *
58
+             * @var $instance IHook
59
+             */
60
+            $instance->addHooks();
61
+        }
62 62
 
63
-	}
63
+    }
64 64
 
65 65
 }
Please login to merge, or discard this patch.