Completed
Pull Request — master (#3829)
by Maxence
12:57
created
apps/encryption/lib/Controller/StatusController.php 1 patch
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -33,67 +33,67 @@
 block discarded – undo
33 33
 
34 34
 class StatusController extends Controller {
35 35
 
36
-	/** @var IL10N */
37
-	private $l;
36
+    /** @var IL10N */
37
+    private $l;
38 38
 
39
-	/** @var Session */
40
-	private $session;
39
+    /** @var Session */
40
+    private $session;
41 41
 
42
-	/**
43
-	 * @param string $AppName
44
-	 * @param IRequest $request
45
-	 * @param IL10N $l10n
46
-	 * @param Session $session
47
-	 */
48
-	public function __construct($AppName,
49
-								IRequest $request,
50
-								IL10N $l10n,
51
-								Session $session
52
-								) {
53
-		parent::__construct($AppName, $request);
54
-		$this->l = $l10n;
55
-		$this->session = $session;
56
-	}
42
+    /**
43
+     * @param string $AppName
44
+     * @param IRequest $request
45
+     * @param IL10N $l10n
46
+     * @param Session $session
47
+     */
48
+    public function __construct($AppName,
49
+                                IRequest $request,
50
+                                IL10N $l10n,
51
+                                Session $session
52
+                                ) {
53
+        parent::__construct($AppName, $request);
54
+        $this->l = $l10n;
55
+        $this->session = $session;
56
+    }
57 57
 
58
-	/**
59
-	 * @NoAdminRequired
60
-	 * @return DataResponse
61
-	 */
62
-	public function getStatus() {
58
+    /**
59
+     * @NoAdminRequired
60
+     * @return DataResponse
61
+     */
62
+    public function getStatus() {
63 63
 
64
-		$status = 'error';
65
-		$message = 'no valid init status';
66
-		switch( $this->session->getStatus()) {
67
-			case Session::RUN_MIGRATION:
68
-				$status = 'interactionNeeded';
69
-				$message = (string)$this->l->t(
70
-					'You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one. Please run \'occ encryption:migrate\' or contact your administrator'
71
-				);
72
-				break;
73
-			case Session::INIT_EXECUTED:
74
-				$status = 'interactionNeeded';
75
-				$message = (string)$this->l->t(
76
-					'Invalid private key for encryption app. Please update your private key password in your personal settings to recover access to your encrypted files.'
77
-				);
78
-				break;
79
-			case Session::NOT_INITIALIZED:
80
-				$status = 'interactionNeeded';
81
-				$message = (string)$this->l->t(
82
-					'Encryption app is enabled but your keys are not initialized, please log-out and log-in again'
83
-				);
84
-				break;
85
-			case Session::INIT_SUCCESSFUL:
86
-				$status = 'success';
87
-				$message = (string)$this->l->t('Encryption app is enabled and ready');
88
-		}
64
+        $status = 'error';
65
+        $message = 'no valid init status';
66
+        switch( $this->session->getStatus()) {
67
+            case Session::RUN_MIGRATION:
68
+                $status = 'interactionNeeded';
69
+                $message = (string)$this->l->t(
70
+                    'You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one. Please run \'occ encryption:migrate\' or contact your administrator'
71
+                );
72
+                break;
73
+            case Session::INIT_EXECUTED:
74
+                $status = 'interactionNeeded';
75
+                $message = (string)$this->l->t(
76
+                    'Invalid private key for encryption app. Please update your private key password in your personal settings to recover access to your encrypted files.'
77
+                );
78
+                break;
79
+            case Session::NOT_INITIALIZED:
80
+                $status = 'interactionNeeded';
81
+                $message = (string)$this->l->t(
82
+                    'Encryption app is enabled but your keys are not initialized, please log-out and log-in again'
83
+                );
84
+                break;
85
+            case Session::INIT_SUCCESSFUL:
86
+                $status = 'success';
87
+                $message = (string)$this->l->t('Encryption app is enabled and ready');
88
+        }
89 89
 
90
-		return new DataResponse(
91
-			[
92
-				'status' => $status,
93
-				'data' => [
94
-					'message' => $message]
95
-			]
96
-		);
97
-	}
90
+        return new DataResponse(
91
+            [
92
+                'status' => $status,
93
+                'data' => [
94
+                    'message' => $message]
95
+            ]
96
+        );
97
+    }
98 98
 
99 99
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Controller/RecoveryController.php 1 patch
Indentation   +155 added lines, -155 removed lines patch added patch discarded remove patch
@@ -34,160 +34,160 @@
 block discarded – undo
34 34
 use OCP\AppFramework\Http\DataResponse;
35 35
 
36 36
 class RecoveryController extends Controller {
37
-	/**
38
-	 * @var IConfig
39
-	 */
40
-	private $config;
41
-	/**
42
-	 * @var IL10N
43
-	 */
44
-	private $l;
45
-	/**
46
-	 * @var Recovery
47
-	 */
48
-	private $recovery;
49
-
50
-	/**
51
-	 * @param string $AppName
52
-	 * @param IRequest $request
53
-	 * @param IConfig $config
54
-	 * @param IL10N $l10n
55
-	 * @param Recovery $recovery
56
-	 */
57
-	public function __construct($AppName,
58
-								IRequest $request,
59
-								IConfig $config,
60
-								IL10N $l10n,
61
-								Recovery $recovery) {
62
-		parent::__construct($AppName, $request);
63
-		$this->config = $config;
64
-		$this->l = $l10n;
65
-		$this->recovery = $recovery;
66
-	}
67
-
68
-	/**
69
-	 * @param string $recoveryPassword
70
-	 * @param string $confirmPassword
71
-	 * @param string $adminEnableRecovery
72
-	 * @return DataResponse
73
-	 */
74
-	public function adminRecovery($recoveryPassword, $confirmPassword, $adminEnableRecovery) {
75
-		// Check if both passwords are the same
76
-		if (empty($recoveryPassword)) {
77
-			$errorMessage = (string)$this->l->t('Missing recovery key password');
78
-			return new DataResponse(['data' => ['message' => $errorMessage]],
79
-				Http::STATUS_BAD_REQUEST);
80
-		}
81
-
82
-		if (empty($confirmPassword)) {
83
-			$errorMessage = (string)$this->l->t('Please repeat the recovery key password');
84
-			return new DataResponse(['data' => ['message' => $errorMessage]],
85
-				Http::STATUS_BAD_REQUEST);
86
-		}
87
-
88
-		if ($recoveryPassword !== $confirmPassword) {
89
-			$errorMessage = (string)$this->l->t('Repeated recovery key password does not match the provided recovery key password');
90
-			return new DataResponse(['data' => ['message' => $errorMessage]],
91
-				Http::STATUS_BAD_REQUEST);
92
-		}
93
-
94
-		if (isset($adminEnableRecovery) && $adminEnableRecovery === '1') {
95
-			if ($this->recovery->enableAdminRecovery($recoveryPassword)) {
96
-				return new DataResponse(['data' => ['message' => (string)$this->l->t('Recovery key successfully enabled')]]);
97
-			}
98
-			return new DataResponse(['data' => ['message' => (string)$this->l->t('Could not enable recovery key. Please check your recovery key password!')]], Http::STATUS_BAD_REQUEST);
99
-		} elseif (isset($adminEnableRecovery) && $adminEnableRecovery === '0') {
100
-			if ($this->recovery->disableAdminRecovery($recoveryPassword)) {
101
-				return new DataResponse(['data' => ['message' => (string)$this->l->t('Recovery key successfully disabled')]]);
102
-			}
103
-			return new DataResponse(['data' => ['message' => (string)$this->l->t('Could not disable recovery key. Please check your recovery key password!')]], Http::STATUS_BAD_REQUEST);
104
-		}
105
-		// this response should never be sent but just in case.
106
-		return new DataResponse(['data' => ['message' => (string)$this->l->t('Missing parameters')]], Http::STATUS_BAD_REQUEST);
107
-	}
108
-
109
-	/**
110
-	 * @param string $newPassword
111
-	 * @param string $oldPassword
112
-	 * @param string $confirmPassword
113
-	 * @return DataResponse
114
-	 */
115
-	public function changeRecoveryPassword($newPassword, $oldPassword, $confirmPassword) {
116
-		//check if both passwords are the same
117
-		if (empty($oldPassword)) {
118
-			$errorMessage = (string)$this->l->t('Please provide the old recovery password');
119
-			return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
120
-		}
121
-
122
-		if (empty($newPassword)) {
123
-			$errorMessage = (string)$this->l->t('Please provide a new recovery password');
124
-			return new DataResponse (['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
125
-		}
126
-
127
-		if (empty($confirmPassword)) {
128
-			$errorMessage = (string)$this->l->t('Please repeat the new recovery password');
129
-			return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
130
-		}
131
-
132
-		if ($newPassword !== $confirmPassword) {
133
-			$errorMessage = (string)$this->l->t('Repeated recovery key password does not match the provided recovery key password');
134
-			return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
135
-		}
136
-
137
-		$result = $this->recovery->changeRecoveryKeyPassword($newPassword,
138
-			$oldPassword);
139
-
140
-		if ($result) {
141
-			return new DataResponse(
142
-				[
143
-					'data' => [
144
-						'message' => (string)$this->l->t('Password successfully changed.')]
145
-				]
146
-			);
147
-		}
148
-		return new DataResponse(
149
-			[
150
-				'data' => [
151
-					'message' => (string)$this->l->t('Could not change the password. Maybe the old password was not correct.')
152
-				]
153
-			], Http::STATUS_BAD_REQUEST);
154
-	}
155
-
156
-	/**
157
-	 * @NoAdminRequired
158
-	 *
159
-	 * @param string $userEnableRecovery
160
-	 * @return DataResponse
161
-	 */
162
-	public function userSetRecovery($userEnableRecovery) {
163
-		if ($userEnableRecovery === '0' || $userEnableRecovery === '1') {
164
-
165
-			$result = $this->recovery->setRecoveryForUser($userEnableRecovery);
166
-
167
-			if ($result) {
168
-				if ($userEnableRecovery === '0') {
169
-					return new DataResponse(
170
-						[
171
-							'data' => [
172
-								'message' => (string)$this->l->t('Recovery Key disabled')]
173
-						]
174
-					);
175
-				}
176
-				return new DataResponse(
177
-					[
178
-						'data' => [
179
-							'message' => (string)$this->l->t('Recovery Key enabled')]
180
-					]
181
-				);
182
-			}
183
-
184
-		}
185
-		return new DataResponse(
186
-			[
187
-				'data' => [
188
-					'message' => (string)$this->l->t('Could not enable the recovery key, please try again or contact your administrator')
189
-				]
190
-			], Http::STATUS_BAD_REQUEST);
191
-	}
37
+    /**
38
+     * @var IConfig
39
+     */
40
+    private $config;
41
+    /**
42
+     * @var IL10N
43
+     */
44
+    private $l;
45
+    /**
46
+     * @var Recovery
47
+     */
48
+    private $recovery;
49
+
50
+    /**
51
+     * @param string $AppName
52
+     * @param IRequest $request
53
+     * @param IConfig $config
54
+     * @param IL10N $l10n
55
+     * @param Recovery $recovery
56
+     */
57
+    public function __construct($AppName,
58
+                                IRequest $request,
59
+                                IConfig $config,
60
+                                IL10N $l10n,
61
+                                Recovery $recovery) {
62
+        parent::__construct($AppName, $request);
63
+        $this->config = $config;
64
+        $this->l = $l10n;
65
+        $this->recovery = $recovery;
66
+    }
67
+
68
+    /**
69
+     * @param string $recoveryPassword
70
+     * @param string $confirmPassword
71
+     * @param string $adminEnableRecovery
72
+     * @return DataResponse
73
+     */
74
+    public function adminRecovery($recoveryPassword, $confirmPassword, $adminEnableRecovery) {
75
+        // Check if both passwords are the same
76
+        if (empty($recoveryPassword)) {
77
+            $errorMessage = (string)$this->l->t('Missing recovery key password');
78
+            return new DataResponse(['data' => ['message' => $errorMessage]],
79
+                Http::STATUS_BAD_REQUEST);
80
+        }
81
+
82
+        if (empty($confirmPassword)) {
83
+            $errorMessage = (string)$this->l->t('Please repeat the recovery key password');
84
+            return new DataResponse(['data' => ['message' => $errorMessage]],
85
+                Http::STATUS_BAD_REQUEST);
86
+        }
87
+
88
+        if ($recoveryPassword !== $confirmPassword) {
89
+            $errorMessage = (string)$this->l->t('Repeated recovery key password does not match the provided recovery key password');
90
+            return new DataResponse(['data' => ['message' => $errorMessage]],
91
+                Http::STATUS_BAD_REQUEST);
92
+        }
93
+
94
+        if (isset($adminEnableRecovery) && $adminEnableRecovery === '1') {
95
+            if ($this->recovery->enableAdminRecovery($recoveryPassword)) {
96
+                return new DataResponse(['data' => ['message' => (string)$this->l->t('Recovery key successfully enabled')]]);
97
+            }
98
+            return new DataResponse(['data' => ['message' => (string)$this->l->t('Could not enable recovery key. Please check your recovery key password!')]], Http::STATUS_BAD_REQUEST);
99
+        } elseif (isset($adminEnableRecovery) && $adminEnableRecovery === '0') {
100
+            if ($this->recovery->disableAdminRecovery($recoveryPassword)) {
101
+                return new DataResponse(['data' => ['message' => (string)$this->l->t('Recovery key successfully disabled')]]);
102
+            }
103
+            return new DataResponse(['data' => ['message' => (string)$this->l->t('Could not disable recovery key. Please check your recovery key password!')]], Http::STATUS_BAD_REQUEST);
104
+        }
105
+        // this response should never be sent but just in case.
106
+        return new DataResponse(['data' => ['message' => (string)$this->l->t('Missing parameters')]], Http::STATUS_BAD_REQUEST);
107
+    }
108
+
109
+    /**
110
+     * @param string $newPassword
111
+     * @param string $oldPassword
112
+     * @param string $confirmPassword
113
+     * @return DataResponse
114
+     */
115
+    public function changeRecoveryPassword($newPassword, $oldPassword, $confirmPassword) {
116
+        //check if both passwords are the same
117
+        if (empty($oldPassword)) {
118
+            $errorMessage = (string)$this->l->t('Please provide the old recovery password');
119
+            return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
120
+        }
121
+
122
+        if (empty($newPassword)) {
123
+            $errorMessage = (string)$this->l->t('Please provide a new recovery password');
124
+            return new DataResponse (['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
125
+        }
126
+
127
+        if (empty($confirmPassword)) {
128
+            $errorMessage = (string)$this->l->t('Please repeat the new recovery password');
129
+            return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
130
+        }
131
+
132
+        if ($newPassword !== $confirmPassword) {
133
+            $errorMessage = (string)$this->l->t('Repeated recovery key password does not match the provided recovery key password');
134
+            return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
135
+        }
136
+
137
+        $result = $this->recovery->changeRecoveryKeyPassword($newPassword,
138
+            $oldPassword);
139
+
140
+        if ($result) {
141
+            return new DataResponse(
142
+                [
143
+                    'data' => [
144
+                        'message' => (string)$this->l->t('Password successfully changed.')]
145
+                ]
146
+            );
147
+        }
148
+        return new DataResponse(
149
+            [
150
+                'data' => [
151
+                    'message' => (string)$this->l->t('Could not change the password. Maybe the old password was not correct.')
152
+                ]
153
+            ], Http::STATUS_BAD_REQUEST);
154
+    }
155
+
156
+    /**
157
+     * @NoAdminRequired
158
+     *
159
+     * @param string $userEnableRecovery
160
+     * @return DataResponse
161
+     */
162
+    public function userSetRecovery($userEnableRecovery) {
163
+        if ($userEnableRecovery === '0' || $userEnableRecovery === '1') {
164
+
165
+            $result = $this->recovery->setRecoveryForUser($userEnableRecovery);
166
+
167
+            if ($result) {
168
+                if ($userEnableRecovery === '0') {
169
+                    return new DataResponse(
170
+                        [
171
+                            'data' => [
172
+                                'message' => (string)$this->l->t('Recovery Key disabled')]
173
+                        ]
174
+                    );
175
+                }
176
+                return new DataResponse(
177
+                    [
178
+                        'data' => [
179
+                            'message' => (string)$this->l->t('Recovery Key enabled')]
180
+                    ]
181
+                );
182
+            }
183
+
184
+        }
185
+        return new DataResponse(
186
+            [
187
+                'data' => [
188
+                    'message' => (string)$this->l->t('Could not enable the recovery key, please try again or contact your administrator')
189
+                ]
190
+            ], Http::STATUS_BAD_REQUEST);
191
+    }
192 192
 
193 193
 }
Please login to merge, or discard this patch.
apps/encryption/lib/KeyManager.php 1 patch
Indentation   +661 added lines, -661 removed lines patch added patch discarded remove patch
@@ -38,665 +38,665 @@
 block discarded – undo
38 38
 
39 39
 class KeyManager {
40 40
 
41
-	/**
42
-	 * @var Session
43
-	 */
44
-	protected $session;
45
-	/**
46
-	 * @var IStorage
47
-	 */
48
-	private $keyStorage;
49
-	/**
50
-	 * @var Crypt
51
-	 */
52
-	private $crypt;
53
-	/**
54
-	 * @var string
55
-	 */
56
-	private $recoveryKeyId;
57
-	/**
58
-	 * @var string
59
-	 */
60
-	private $publicShareKeyId;
61
-	/**
62
-	 * @var string
63
-	 */
64
-	private $masterKeyId;
65
-	/**
66
-	 * @var string UserID
67
-	 */
68
-	private $keyId;
69
-	/**
70
-	 * @var string
71
-	 */
72
-	private $publicKeyId = 'publicKey';
73
-	/**
74
-	 * @var string
75
-	 */
76
-	private $privateKeyId = 'privateKey';
77
-
78
-	/**
79
-	 * @var string
80
-	 */
81
-	private $shareKeyId = 'shareKey';
82
-
83
-	/**
84
-	 * @var string
85
-	 */
86
-	private $fileKeyId = 'fileKey';
87
-	/**
88
-	 * @var IConfig
89
-	 */
90
-	private $config;
91
-	/**
92
-	 * @var ILogger
93
-	 */
94
-	private $log;
95
-	/**
96
-	 * @var Util
97
-	 */
98
-	private $util;
99
-
100
-	/**
101
-	 * @param IStorage $keyStorage
102
-	 * @param Crypt $crypt
103
-	 * @param IConfig $config
104
-	 * @param IUserSession $userSession
105
-	 * @param Session $session
106
-	 * @param ILogger $log
107
-	 * @param Util $util
108
-	 */
109
-	public function __construct(
110
-		IStorage $keyStorage,
111
-		Crypt $crypt,
112
-		IConfig $config,
113
-		IUserSession $userSession,
114
-		Session $session,
115
-		ILogger $log,
116
-		Util $util
117
-	) {
118
-
119
-		$this->util = $util;
120
-		$this->session = $session;
121
-		$this->keyStorage = $keyStorage;
122
-		$this->crypt = $crypt;
123
-		$this->config = $config;
124
-		$this->log = $log;
125
-
126
-		$this->recoveryKeyId = $this->config->getAppValue('encryption',
127
-			'recoveryKeyId');
128
-		if (empty($this->recoveryKeyId)) {
129
-			$this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8);
130
-			$this->config->setAppValue('encryption',
131
-				'recoveryKeyId',
132
-				$this->recoveryKeyId);
133
-		}
134
-
135
-		$this->publicShareKeyId = $this->config->getAppValue('encryption',
136
-			'publicShareKeyId');
137
-		if (empty($this->publicShareKeyId)) {
138
-			$this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8);
139
-			$this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId);
140
-		}
141
-
142
-		$this->masterKeyId = $this->config->getAppValue('encryption',
143
-			'masterKeyId');
144
-		if (empty($this->masterKeyId)) {
145
-			$this->masterKeyId = 'master_' . substr(md5(time()), 0, 8);
146
-			$this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId);
147
-		}
148
-
149
-		$this->keyId = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false;
150
-		$this->log = $log;
151
-	}
152
-
153
-	/**
154
-	 * check if key pair for public link shares exists, if not we create one
155
-	 */
156
-	public function validateShareKey() {
157
-		$shareKey = $this->getPublicShareKey();
158
-		if (empty($shareKey)) {
159
-			$keyPair = $this->crypt->createKeyPair();
160
-
161
-			// Save public key
162
-			$this->keyStorage->setSystemUserKey(
163
-				$this->publicShareKeyId . '.publicKey', $keyPair['publicKey'],
164
-				Encryption::ID);
165
-
166
-			// Encrypt private key empty passphrase
167
-			$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], '');
168
-			$header = $this->crypt->generateHeader();
169
-			$this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey);
170
-		}
171
-	}
172
-
173
-	/**
174
-	 * check if a key pair for the master key exists, if not we create one
175
-	 */
176
-	public function validateMasterKey() {
177
-
178
-		if ($this->util->isMasterKeyEnabled() === false) {
179
-			return;
180
-		}
181
-
182
-		$masterKey = $this->getPublicMasterKey();
183
-		if (empty($masterKey)) {
184
-			$keyPair = $this->crypt->createKeyPair();
185
-
186
-			// Save public key
187
-			$this->keyStorage->setSystemUserKey(
188
-				$this->masterKeyId . '.publicKey', $keyPair['publicKey'],
189
-				Encryption::ID);
190
-
191
-			// Encrypt private key with system password
192
-			$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId);
193
-			$header = $this->crypt->generateHeader();
194
-			$this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey);
195
-		}
196
-	}
197
-
198
-	/**
199
-	 * @return bool
200
-	 */
201
-	public function recoveryKeyExists() {
202
-		$key = $this->getRecoveryKey();
203
-		return (!empty($key));
204
-	}
205
-
206
-	/**
207
-	 * get recovery key
208
-	 *
209
-	 * @return string
210
-	 */
211
-	public function getRecoveryKey() {
212
-		return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID);
213
-	}
214
-
215
-	/**
216
-	 * get recovery key ID
217
-	 *
218
-	 * @return string
219
-	 */
220
-	public function getRecoveryKeyId() {
221
-		return $this->recoveryKeyId;
222
-	}
223
-
224
-	/**
225
-	 * @param string $password
226
-	 * @return bool
227
-	 */
228
-	public function checkRecoveryPassword($password) {
229
-		$recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID);
230
-		$decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
231
-
232
-		if ($decryptedRecoveryKey) {
233
-			return true;
234
-		}
235
-		return false;
236
-	}
237
-
238
-	/**
239
-	 * @param string $uid
240
-	 * @param string $password
241
-	 * @param string $keyPair
242
-	 * @return bool
243
-	 */
244
-	public function storeKeyPair($uid, $password, $keyPair) {
245
-		// Save Public Key
246
-		$this->setPublicKey($uid, $keyPair['publicKey']);
247
-
248
-		$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid);
249
-
250
-		$header = $this->crypt->generateHeader();
251
-
252
-		if ($encryptedKey) {
253
-			$this->setPrivateKey($uid, $header . $encryptedKey);
254
-			return true;
255
-		}
256
-		return false;
257
-	}
258
-
259
-	/**
260
-	 * @param string $password
261
-	 * @param array $keyPair
262
-	 * @return bool
263
-	 */
264
-	public function setRecoveryKey($password, $keyPair) {
265
-		// Save Public Key
266
-		$this->keyStorage->setSystemUserKey($this->getRecoveryKeyId().
267
-			'.publicKey',
268
-			$keyPair['publicKey'],
269
-			Encryption::ID);
270
-
271
-		$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password);
272
-		$header = $this->crypt->generateHeader();
273
-
274
-		if ($encryptedKey) {
275
-			$this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey);
276
-			return true;
277
-		}
278
-		return false;
279
-	}
280
-
281
-	/**
282
-	 * @param $userId
283
-	 * @param $key
284
-	 * @return bool
285
-	 */
286
-	public function setPublicKey($userId, $key) {
287
-		return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID);
288
-	}
289
-
290
-	/**
291
-	 * @param $userId
292
-	 * @param string $key
293
-	 * @return bool
294
-	 */
295
-	public function setPrivateKey($userId, $key) {
296
-		return $this->keyStorage->setUserKey($userId,
297
-			$this->privateKeyId,
298
-			$key,
299
-			Encryption::ID);
300
-	}
301
-
302
-	/**
303
-	 * write file key to key storage
304
-	 *
305
-	 * @param string $path
306
-	 * @param string $key
307
-	 * @return boolean
308
-	 */
309
-	public function setFileKey($path, $key) {
310
-		return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID);
311
-	}
312
-
313
-	/**
314
-	 * set all file keys (the file key and the corresponding share keys)
315
-	 *
316
-	 * @param string $path
317
-	 * @param array $keys
318
-	 */
319
-	public function setAllFileKeys($path, $keys) {
320
-		$this->setFileKey($path, $keys['data']);
321
-		foreach ($keys['keys'] as $uid => $keyFile) {
322
-			$this->setShareKey($path, $uid, $keyFile);
323
-		}
324
-	}
325
-
326
-	/**
327
-	 * write share key to the key storage
328
-	 *
329
-	 * @param string $path
330
-	 * @param string $uid
331
-	 * @param string $key
332
-	 * @return boolean
333
-	 */
334
-	public function setShareKey($path, $uid, $key) {
335
-		$keyId = $uid . '.' . $this->shareKeyId;
336
-		return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID);
337
-	}
338
-
339
-	/**
340
-	 * Decrypt private key and store it
341
-	 *
342
-	 * @param string $uid user id
343
-	 * @param string $passPhrase users password
344
-	 * @return boolean
345
-	 */
346
-	public function init($uid, $passPhrase) {
347
-
348
-		$this->session->setStatus(Session::INIT_EXECUTED);
349
-
350
-		try {
351
-			if($this->util->isMasterKeyEnabled()) {
352
-				$uid = $this->getMasterKeyId();
353
-				$passPhrase = $this->getMasterKeyPassword();
354
-				$privateKey = $this->getSystemPrivateKey($uid);
355
-			} else {
356
-				$privateKey = $this->getPrivateKey($uid);
357
-			}
358
-			$privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid);
359
-		} catch (PrivateKeyMissingException $e) {
360
-			return false;
361
-		} catch (DecryptionFailedException $e) {
362
-			return false;
363
-		} catch (\Exception $e) {
364
-			$this->log->warning(
365
-				'Could not decrypt the private key from user "' . $uid . '"" during login. ' .
366
-				'Assume password change on the user back-end. Error message: '
367
-				. $e->getMessage()
368
-			);
369
-			return false;
370
-		}
371
-
372
-		if ($privateKey) {
373
-			$this->session->setPrivateKey($privateKey);
374
-			$this->session->setStatus(Session::INIT_SUCCESSFUL);
375
-			return true;
376
-		}
377
-
378
-		return false;
379
-	}
380
-
381
-	/**
382
-	 * @param $userId
383
-	 * @return string
384
-	 * @throws PrivateKeyMissingException
385
-	 */
386
-	public function getPrivateKey($userId) {
387
-		$privateKey = $this->keyStorage->getUserKey($userId,
388
-			$this->privateKeyId, Encryption::ID);
389
-
390
-		if (strlen($privateKey) !== 0) {
391
-			return $privateKey;
392
-		}
393
-		throw new PrivateKeyMissingException($userId);
394
-	}
395
-
396
-	/**
397
-	 * @param string $path
398
-	 * @param $uid
399
-	 * @return string
400
-	 */
401
-	public function getFileKey($path, $uid) {
402
-		$encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID);
403
-
404
-		if (empty($encryptedFileKey)) {
405
-			return '';
406
-		}
407
-
408
-		if ($this->util->isMasterKeyEnabled()) {
409
-			$uid = $this->getMasterKeyId();
410
-		}
411
-
412
-		if (is_null($uid)) {
413
-			$uid = $this->getPublicShareKeyId();
414
-			$shareKey = $this->getShareKey($path, $uid);
415
-			$privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID);
416
-			$privateKey = $this->crypt->decryptPrivateKey($privateKey);
417
-		} else {
418
-			$shareKey = $this->getShareKey($path, $uid);
419
-			$privateKey = $this->session->getPrivateKey();
420
-		}
421
-
422
-		if ($encryptedFileKey && $shareKey && $privateKey) {
423
-			return $this->crypt->multiKeyDecrypt($encryptedFileKey,
424
-				$shareKey,
425
-				$privateKey);
426
-		}
427
-
428
-		return '';
429
-	}
430
-
431
-	/**
432
-	 * Get the current version of a file
433
-	 *
434
-	 * @param string $path
435
-	 * @param View $view
436
-	 * @return int
437
-	 */
438
-	public function getVersion($path, View $view) {
439
-		$fileInfo = $view->getFileInfo($path);
440
-		if($fileInfo === false) {
441
-			return 0;
442
-		}
443
-		return $fileInfo->getEncryptedVersion();
444
-	}
445
-
446
-	/**
447
-	 * Set the current version of a file
448
-	 *
449
-	 * @param string $path
450
-	 * @param int $version
451
-	 * @param View $view
452
-	 */
453
-	public function setVersion($path, $version, View $view) {
454
-		$fileInfo= $view->getFileInfo($path);
455
-
456
-		if($fileInfo !== false) {
457
-			$cache = $fileInfo->getStorage()->getCache();
458
-			$cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
459
-		}
460
-	}
461
-
462
-	/**
463
-	 * get the encrypted file key
464
-	 *
465
-	 * @param string $path
466
-	 * @return string
467
-	 */
468
-	public function getEncryptedFileKey($path) {
469
-		$encryptedFileKey = $this->keyStorage->getFileKey($path,
470
-			$this->fileKeyId, Encryption::ID);
471
-
472
-		return $encryptedFileKey;
473
-	}
474
-
475
-	/**
476
-	 * delete share key
477
-	 *
478
-	 * @param string $path
479
-	 * @param string $keyId
480
-	 * @return boolean
481
-	 */
482
-	public function deleteShareKey($path, $keyId) {
483
-		return $this->keyStorage->deleteFileKey(
484
-			$path,
485
-			$keyId . '.' . $this->shareKeyId,
486
-			Encryption::ID);
487
-	}
488
-
489
-
490
-	/**
491
-	 * @param $path
492
-	 * @param $uid
493
-	 * @return mixed
494
-	 */
495
-	public function getShareKey($path, $uid) {
496
-		$keyId = $uid . '.' . $this->shareKeyId;
497
-		return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID);
498
-	}
499
-
500
-	/**
501
-	 * check if user has a private and a public key
502
-	 *
503
-	 * @param string $userId
504
-	 * @return bool
505
-	 * @throws PrivateKeyMissingException
506
-	 * @throws PublicKeyMissingException
507
-	 */
508
-	public function userHasKeys($userId) {
509
-		$privateKey = $publicKey = true;
510
-		$exception = null;
511
-
512
-		try {
513
-			$this->getPrivateKey($userId);
514
-		} catch (PrivateKeyMissingException $e) {
515
-			$privateKey = false;
516
-			$exception = $e;
517
-		}
518
-		try {
519
-			$this->getPublicKey($userId);
520
-		} catch (PublicKeyMissingException $e) {
521
-			$publicKey = false;
522
-			$exception = $e;
523
-		}
524
-
525
-		if ($privateKey && $publicKey) {
526
-			return true;
527
-		} elseif (!$privateKey && !$publicKey) {
528
-			return false;
529
-		} else {
530
-			throw $exception;
531
-		}
532
-	}
533
-
534
-	/**
535
-	 * @param $userId
536
-	 * @return mixed
537
-	 * @throws PublicKeyMissingException
538
-	 */
539
-	public function getPublicKey($userId) {
540
-		$publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID);
541
-
542
-		if (strlen($publicKey) !== 0) {
543
-			return $publicKey;
544
-		}
545
-		throw new PublicKeyMissingException($userId);
546
-	}
547
-
548
-	public function getPublicShareKeyId() {
549
-		return $this->publicShareKeyId;
550
-	}
551
-
552
-	/**
553
-	 * get public key for public link shares
554
-	 *
555
-	 * @return string
556
-	 */
557
-	public function getPublicShareKey() {
558
-		return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID);
559
-	}
560
-
561
-	/**
562
-	 * @param string $purpose
563
-	 * @param string $uid
564
-	 */
565
-	public function backupUserKeys($purpose, $uid) {
566
-		$this->keyStorage->backupUserKeys(Encryption::ID, $purpose, $uid);
567
-	}
568
-
569
-	/**
570
-	 * creat a backup of the users private and public key and then  delete it
571
-	 *
572
-	 * @param string $uid
573
-	 */
574
-	public function deleteUserKeys($uid) {
575
-		$this->deletePublicKey($uid);
576
-		$this->deletePrivateKey($uid);
577
-	}
578
-
579
-	/**
580
-	 * @param $uid
581
-	 * @return bool
582
-	 */
583
-	public function deletePublicKey($uid) {
584
-		return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID);
585
-	}
586
-
587
-	/**
588
-	 * @param string $uid
589
-	 * @return bool
590
-	 */
591
-	private function deletePrivateKey($uid) {
592
-		return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID);
593
-	}
594
-
595
-	/**
596
-	 * @param string $path
597
-	 * @return bool
598
-	 */
599
-	public function deleteAllFileKeys($path) {
600
-		return $this->keyStorage->deleteAllFileKeys($path);
601
-	}
602
-
603
-	/**
604
-	 * @param array $userIds
605
-	 * @return array
606
-	 * @throws PublicKeyMissingException
607
-	 */
608
-	public function getPublicKeys(array $userIds) {
609
-		$keys = [];
610
-
611
-		foreach ($userIds as $userId) {
612
-			try {
613
-				$keys[$userId] = $this->getPublicKey($userId);
614
-			} catch (PublicKeyMissingException $e) {
615
-				continue;
616
-			}
617
-		}
618
-
619
-		return $keys;
620
-
621
-	}
622
-
623
-	/**
624
-	 * @param string $keyId
625
-	 * @return string returns openssl key
626
-	 */
627
-	public function getSystemPrivateKey($keyId) {
628
-		return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID);
629
-	}
630
-
631
-	/**
632
-	 * @param string $keyId
633
-	 * @param string $key
634
-	 * @return string returns openssl key
635
-	 */
636
-	public function setSystemPrivateKey($keyId, $key) {
637
-		return $this->keyStorage->setSystemUserKey(
638
-			$keyId . '.' . $this->privateKeyId,
639
-			$key,
640
-			Encryption::ID);
641
-	}
642
-
643
-	/**
644
-	 * add system keys such as the public share key and the recovery key
645
-	 *
646
-	 * @param array $accessList
647
-	 * @param array $publicKeys
648
-	 * @param string $uid
649
-	 * @return array
650
-	 * @throws PublicKeyMissingException
651
-	 */
652
-	public function addSystemKeys(array $accessList, array $publicKeys, $uid) {
653
-		if (!empty($accessList['public'])) {
654
-			$publicShareKey = $this->getPublicShareKey();
655
-			if (empty($publicShareKey)) {
656
-				throw new PublicKeyMissingException($this->getPublicShareKeyId());
657
-			}
658
-			$publicKeys[$this->getPublicShareKeyId()] = $publicShareKey;
659
-		}
660
-
661
-		if ($this->recoveryKeyExists() &&
662
-			$this->util->isRecoveryEnabledForUser($uid)) {
663
-
664
-			$publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey();
665
-		}
666
-
667
-		return $publicKeys;
668
-	}
669
-
670
-	/**
671
-	 * get master key password
672
-	 *
673
-	 * @return string
674
-	 * @throws \Exception
675
-	 */
676
-	public function getMasterKeyPassword() {
677
-		$password = $this->config->getSystemValue('secret');
678
-		if (empty($password)){
679
-			throw new \Exception('Can not get secret from ownCloud instance');
680
-		}
681
-
682
-		return $password;
683
-	}
684
-
685
-	/**
686
-	 * return master key id
687
-	 *
688
-	 * @return string
689
-	 */
690
-	public function getMasterKeyId() {
691
-		return $this->masterKeyId;
692
-	}
693
-
694
-	/**
695
-	 * get public master key
696
-	 *
697
-	 * @return string
698
-	 */
699
-	public function getPublicMasterKey() {
700
-		return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID);
701
-	}
41
+    /**
42
+     * @var Session
43
+     */
44
+    protected $session;
45
+    /**
46
+     * @var IStorage
47
+     */
48
+    private $keyStorage;
49
+    /**
50
+     * @var Crypt
51
+     */
52
+    private $crypt;
53
+    /**
54
+     * @var string
55
+     */
56
+    private $recoveryKeyId;
57
+    /**
58
+     * @var string
59
+     */
60
+    private $publicShareKeyId;
61
+    /**
62
+     * @var string
63
+     */
64
+    private $masterKeyId;
65
+    /**
66
+     * @var string UserID
67
+     */
68
+    private $keyId;
69
+    /**
70
+     * @var string
71
+     */
72
+    private $publicKeyId = 'publicKey';
73
+    /**
74
+     * @var string
75
+     */
76
+    private $privateKeyId = 'privateKey';
77
+
78
+    /**
79
+     * @var string
80
+     */
81
+    private $shareKeyId = 'shareKey';
82
+
83
+    /**
84
+     * @var string
85
+     */
86
+    private $fileKeyId = 'fileKey';
87
+    /**
88
+     * @var IConfig
89
+     */
90
+    private $config;
91
+    /**
92
+     * @var ILogger
93
+     */
94
+    private $log;
95
+    /**
96
+     * @var Util
97
+     */
98
+    private $util;
99
+
100
+    /**
101
+     * @param IStorage $keyStorage
102
+     * @param Crypt $crypt
103
+     * @param IConfig $config
104
+     * @param IUserSession $userSession
105
+     * @param Session $session
106
+     * @param ILogger $log
107
+     * @param Util $util
108
+     */
109
+    public function __construct(
110
+        IStorage $keyStorage,
111
+        Crypt $crypt,
112
+        IConfig $config,
113
+        IUserSession $userSession,
114
+        Session $session,
115
+        ILogger $log,
116
+        Util $util
117
+    ) {
118
+
119
+        $this->util = $util;
120
+        $this->session = $session;
121
+        $this->keyStorage = $keyStorage;
122
+        $this->crypt = $crypt;
123
+        $this->config = $config;
124
+        $this->log = $log;
125
+
126
+        $this->recoveryKeyId = $this->config->getAppValue('encryption',
127
+            'recoveryKeyId');
128
+        if (empty($this->recoveryKeyId)) {
129
+            $this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8);
130
+            $this->config->setAppValue('encryption',
131
+                'recoveryKeyId',
132
+                $this->recoveryKeyId);
133
+        }
134
+
135
+        $this->publicShareKeyId = $this->config->getAppValue('encryption',
136
+            'publicShareKeyId');
137
+        if (empty($this->publicShareKeyId)) {
138
+            $this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8);
139
+            $this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId);
140
+        }
141
+
142
+        $this->masterKeyId = $this->config->getAppValue('encryption',
143
+            'masterKeyId');
144
+        if (empty($this->masterKeyId)) {
145
+            $this->masterKeyId = 'master_' . substr(md5(time()), 0, 8);
146
+            $this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId);
147
+        }
148
+
149
+        $this->keyId = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false;
150
+        $this->log = $log;
151
+    }
152
+
153
+    /**
154
+     * check if key pair for public link shares exists, if not we create one
155
+     */
156
+    public function validateShareKey() {
157
+        $shareKey = $this->getPublicShareKey();
158
+        if (empty($shareKey)) {
159
+            $keyPair = $this->crypt->createKeyPair();
160
+
161
+            // Save public key
162
+            $this->keyStorage->setSystemUserKey(
163
+                $this->publicShareKeyId . '.publicKey', $keyPair['publicKey'],
164
+                Encryption::ID);
165
+
166
+            // Encrypt private key empty passphrase
167
+            $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], '');
168
+            $header = $this->crypt->generateHeader();
169
+            $this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey);
170
+        }
171
+    }
172
+
173
+    /**
174
+     * check if a key pair for the master key exists, if not we create one
175
+     */
176
+    public function validateMasterKey() {
177
+
178
+        if ($this->util->isMasterKeyEnabled() === false) {
179
+            return;
180
+        }
181
+
182
+        $masterKey = $this->getPublicMasterKey();
183
+        if (empty($masterKey)) {
184
+            $keyPair = $this->crypt->createKeyPair();
185
+
186
+            // Save public key
187
+            $this->keyStorage->setSystemUserKey(
188
+                $this->masterKeyId . '.publicKey', $keyPair['publicKey'],
189
+                Encryption::ID);
190
+
191
+            // Encrypt private key with system password
192
+            $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId);
193
+            $header = $this->crypt->generateHeader();
194
+            $this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey);
195
+        }
196
+    }
197
+
198
+    /**
199
+     * @return bool
200
+     */
201
+    public function recoveryKeyExists() {
202
+        $key = $this->getRecoveryKey();
203
+        return (!empty($key));
204
+    }
205
+
206
+    /**
207
+     * get recovery key
208
+     *
209
+     * @return string
210
+     */
211
+    public function getRecoveryKey() {
212
+        return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID);
213
+    }
214
+
215
+    /**
216
+     * get recovery key ID
217
+     *
218
+     * @return string
219
+     */
220
+    public function getRecoveryKeyId() {
221
+        return $this->recoveryKeyId;
222
+    }
223
+
224
+    /**
225
+     * @param string $password
226
+     * @return bool
227
+     */
228
+    public function checkRecoveryPassword($password) {
229
+        $recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID);
230
+        $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
231
+
232
+        if ($decryptedRecoveryKey) {
233
+            return true;
234
+        }
235
+        return false;
236
+    }
237
+
238
+    /**
239
+     * @param string $uid
240
+     * @param string $password
241
+     * @param string $keyPair
242
+     * @return bool
243
+     */
244
+    public function storeKeyPair($uid, $password, $keyPair) {
245
+        // Save Public Key
246
+        $this->setPublicKey($uid, $keyPair['publicKey']);
247
+
248
+        $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid);
249
+
250
+        $header = $this->crypt->generateHeader();
251
+
252
+        if ($encryptedKey) {
253
+            $this->setPrivateKey($uid, $header . $encryptedKey);
254
+            return true;
255
+        }
256
+        return false;
257
+    }
258
+
259
+    /**
260
+     * @param string $password
261
+     * @param array $keyPair
262
+     * @return bool
263
+     */
264
+    public function setRecoveryKey($password, $keyPair) {
265
+        // Save Public Key
266
+        $this->keyStorage->setSystemUserKey($this->getRecoveryKeyId().
267
+            '.publicKey',
268
+            $keyPair['publicKey'],
269
+            Encryption::ID);
270
+
271
+        $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password);
272
+        $header = $this->crypt->generateHeader();
273
+
274
+        if ($encryptedKey) {
275
+            $this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey);
276
+            return true;
277
+        }
278
+        return false;
279
+    }
280
+
281
+    /**
282
+     * @param $userId
283
+     * @param $key
284
+     * @return bool
285
+     */
286
+    public function setPublicKey($userId, $key) {
287
+        return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID);
288
+    }
289
+
290
+    /**
291
+     * @param $userId
292
+     * @param string $key
293
+     * @return bool
294
+     */
295
+    public function setPrivateKey($userId, $key) {
296
+        return $this->keyStorage->setUserKey($userId,
297
+            $this->privateKeyId,
298
+            $key,
299
+            Encryption::ID);
300
+    }
301
+
302
+    /**
303
+     * write file key to key storage
304
+     *
305
+     * @param string $path
306
+     * @param string $key
307
+     * @return boolean
308
+     */
309
+    public function setFileKey($path, $key) {
310
+        return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID);
311
+    }
312
+
313
+    /**
314
+     * set all file keys (the file key and the corresponding share keys)
315
+     *
316
+     * @param string $path
317
+     * @param array $keys
318
+     */
319
+    public function setAllFileKeys($path, $keys) {
320
+        $this->setFileKey($path, $keys['data']);
321
+        foreach ($keys['keys'] as $uid => $keyFile) {
322
+            $this->setShareKey($path, $uid, $keyFile);
323
+        }
324
+    }
325
+
326
+    /**
327
+     * write share key to the key storage
328
+     *
329
+     * @param string $path
330
+     * @param string $uid
331
+     * @param string $key
332
+     * @return boolean
333
+     */
334
+    public function setShareKey($path, $uid, $key) {
335
+        $keyId = $uid . '.' . $this->shareKeyId;
336
+        return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID);
337
+    }
338
+
339
+    /**
340
+     * Decrypt private key and store it
341
+     *
342
+     * @param string $uid user id
343
+     * @param string $passPhrase users password
344
+     * @return boolean
345
+     */
346
+    public function init($uid, $passPhrase) {
347
+
348
+        $this->session->setStatus(Session::INIT_EXECUTED);
349
+
350
+        try {
351
+            if($this->util->isMasterKeyEnabled()) {
352
+                $uid = $this->getMasterKeyId();
353
+                $passPhrase = $this->getMasterKeyPassword();
354
+                $privateKey = $this->getSystemPrivateKey($uid);
355
+            } else {
356
+                $privateKey = $this->getPrivateKey($uid);
357
+            }
358
+            $privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid);
359
+        } catch (PrivateKeyMissingException $e) {
360
+            return false;
361
+        } catch (DecryptionFailedException $e) {
362
+            return false;
363
+        } catch (\Exception $e) {
364
+            $this->log->warning(
365
+                'Could not decrypt the private key from user "' . $uid . '"" during login. ' .
366
+                'Assume password change on the user back-end. Error message: '
367
+                . $e->getMessage()
368
+            );
369
+            return false;
370
+        }
371
+
372
+        if ($privateKey) {
373
+            $this->session->setPrivateKey($privateKey);
374
+            $this->session->setStatus(Session::INIT_SUCCESSFUL);
375
+            return true;
376
+        }
377
+
378
+        return false;
379
+    }
380
+
381
+    /**
382
+     * @param $userId
383
+     * @return string
384
+     * @throws PrivateKeyMissingException
385
+     */
386
+    public function getPrivateKey($userId) {
387
+        $privateKey = $this->keyStorage->getUserKey($userId,
388
+            $this->privateKeyId, Encryption::ID);
389
+
390
+        if (strlen($privateKey) !== 0) {
391
+            return $privateKey;
392
+        }
393
+        throw new PrivateKeyMissingException($userId);
394
+    }
395
+
396
+    /**
397
+     * @param string $path
398
+     * @param $uid
399
+     * @return string
400
+     */
401
+    public function getFileKey($path, $uid) {
402
+        $encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID);
403
+
404
+        if (empty($encryptedFileKey)) {
405
+            return '';
406
+        }
407
+
408
+        if ($this->util->isMasterKeyEnabled()) {
409
+            $uid = $this->getMasterKeyId();
410
+        }
411
+
412
+        if (is_null($uid)) {
413
+            $uid = $this->getPublicShareKeyId();
414
+            $shareKey = $this->getShareKey($path, $uid);
415
+            $privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID);
416
+            $privateKey = $this->crypt->decryptPrivateKey($privateKey);
417
+        } else {
418
+            $shareKey = $this->getShareKey($path, $uid);
419
+            $privateKey = $this->session->getPrivateKey();
420
+        }
421
+
422
+        if ($encryptedFileKey && $shareKey && $privateKey) {
423
+            return $this->crypt->multiKeyDecrypt($encryptedFileKey,
424
+                $shareKey,
425
+                $privateKey);
426
+        }
427
+
428
+        return '';
429
+    }
430
+
431
+    /**
432
+     * Get the current version of a file
433
+     *
434
+     * @param string $path
435
+     * @param View $view
436
+     * @return int
437
+     */
438
+    public function getVersion($path, View $view) {
439
+        $fileInfo = $view->getFileInfo($path);
440
+        if($fileInfo === false) {
441
+            return 0;
442
+        }
443
+        return $fileInfo->getEncryptedVersion();
444
+    }
445
+
446
+    /**
447
+     * Set the current version of a file
448
+     *
449
+     * @param string $path
450
+     * @param int $version
451
+     * @param View $view
452
+     */
453
+    public function setVersion($path, $version, View $view) {
454
+        $fileInfo= $view->getFileInfo($path);
455
+
456
+        if($fileInfo !== false) {
457
+            $cache = $fileInfo->getStorage()->getCache();
458
+            $cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
459
+        }
460
+    }
461
+
462
+    /**
463
+     * get the encrypted file key
464
+     *
465
+     * @param string $path
466
+     * @return string
467
+     */
468
+    public function getEncryptedFileKey($path) {
469
+        $encryptedFileKey = $this->keyStorage->getFileKey($path,
470
+            $this->fileKeyId, Encryption::ID);
471
+
472
+        return $encryptedFileKey;
473
+    }
474
+
475
+    /**
476
+     * delete share key
477
+     *
478
+     * @param string $path
479
+     * @param string $keyId
480
+     * @return boolean
481
+     */
482
+    public function deleteShareKey($path, $keyId) {
483
+        return $this->keyStorage->deleteFileKey(
484
+            $path,
485
+            $keyId . '.' . $this->shareKeyId,
486
+            Encryption::ID);
487
+    }
488
+
489
+
490
+    /**
491
+     * @param $path
492
+     * @param $uid
493
+     * @return mixed
494
+     */
495
+    public function getShareKey($path, $uid) {
496
+        $keyId = $uid . '.' . $this->shareKeyId;
497
+        return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID);
498
+    }
499
+
500
+    /**
501
+     * check if user has a private and a public key
502
+     *
503
+     * @param string $userId
504
+     * @return bool
505
+     * @throws PrivateKeyMissingException
506
+     * @throws PublicKeyMissingException
507
+     */
508
+    public function userHasKeys($userId) {
509
+        $privateKey = $publicKey = true;
510
+        $exception = null;
511
+
512
+        try {
513
+            $this->getPrivateKey($userId);
514
+        } catch (PrivateKeyMissingException $e) {
515
+            $privateKey = false;
516
+            $exception = $e;
517
+        }
518
+        try {
519
+            $this->getPublicKey($userId);
520
+        } catch (PublicKeyMissingException $e) {
521
+            $publicKey = false;
522
+            $exception = $e;
523
+        }
524
+
525
+        if ($privateKey && $publicKey) {
526
+            return true;
527
+        } elseif (!$privateKey && !$publicKey) {
528
+            return false;
529
+        } else {
530
+            throw $exception;
531
+        }
532
+    }
533
+
534
+    /**
535
+     * @param $userId
536
+     * @return mixed
537
+     * @throws PublicKeyMissingException
538
+     */
539
+    public function getPublicKey($userId) {
540
+        $publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID);
541
+
542
+        if (strlen($publicKey) !== 0) {
543
+            return $publicKey;
544
+        }
545
+        throw new PublicKeyMissingException($userId);
546
+    }
547
+
548
+    public function getPublicShareKeyId() {
549
+        return $this->publicShareKeyId;
550
+    }
551
+
552
+    /**
553
+     * get public key for public link shares
554
+     *
555
+     * @return string
556
+     */
557
+    public function getPublicShareKey() {
558
+        return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID);
559
+    }
560
+
561
+    /**
562
+     * @param string $purpose
563
+     * @param string $uid
564
+     */
565
+    public function backupUserKeys($purpose, $uid) {
566
+        $this->keyStorage->backupUserKeys(Encryption::ID, $purpose, $uid);
567
+    }
568
+
569
+    /**
570
+     * creat a backup of the users private and public key and then  delete it
571
+     *
572
+     * @param string $uid
573
+     */
574
+    public function deleteUserKeys($uid) {
575
+        $this->deletePublicKey($uid);
576
+        $this->deletePrivateKey($uid);
577
+    }
578
+
579
+    /**
580
+     * @param $uid
581
+     * @return bool
582
+     */
583
+    public function deletePublicKey($uid) {
584
+        return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID);
585
+    }
586
+
587
+    /**
588
+     * @param string $uid
589
+     * @return bool
590
+     */
591
+    private function deletePrivateKey($uid) {
592
+        return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID);
593
+    }
594
+
595
+    /**
596
+     * @param string $path
597
+     * @return bool
598
+     */
599
+    public function deleteAllFileKeys($path) {
600
+        return $this->keyStorage->deleteAllFileKeys($path);
601
+    }
602
+
603
+    /**
604
+     * @param array $userIds
605
+     * @return array
606
+     * @throws PublicKeyMissingException
607
+     */
608
+    public function getPublicKeys(array $userIds) {
609
+        $keys = [];
610
+
611
+        foreach ($userIds as $userId) {
612
+            try {
613
+                $keys[$userId] = $this->getPublicKey($userId);
614
+            } catch (PublicKeyMissingException $e) {
615
+                continue;
616
+            }
617
+        }
618
+
619
+        return $keys;
620
+
621
+    }
622
+
623
+    /**
624
+     * @param string $keyId
625
+     * @return string returns openssl key
626
+     */
627
+    public function getSystemPrivateKey($keyId) {
628
+        return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID);
629
+    }
630
+
631
+    /**
632
+     * @param string $keyId
633
+     * @param string $key
634
+     * @return string returns openssl key
635
+     */
636
+    public function setSystemPrivateKey($keyId, $key) {
637
+        return $this->keyStorage->setSystemUserKey(
638
+            $keyId . '.' . $this->privateKeyId,
639
+            $key,
640
+            Encryption::ID);
641
+    }
642
+
643
+    /**
644
+     * add system keys such as the public share key and the recovery key
645
+     *
646
+     * @param array $accessList
647
+     * @param array $publicKeys
648
+     * @param string $uid
649
+     * @return array
650
+     * @throws PublicKeyMissingException
651
+     */
652
+    public function addSystemKeys(array $accessList, array $publicKeys, $uid) {
653
+        if (!empty($accessList['public'])) {
654
+            $publicShareKey = $this->getPublicShareKey();
655
+            if (empty($publicShareKey)) {
656
+                throw new PublicKeyMissingException($this->getPublicShareKeyId());
657
+            }
658
+            $publicKeys[$this->getPublicShareKeyId()] = $publicShareKey;
659
+        }
660
+
661
+        if ($this->recoveryKeyExists() &&
662
+            $this->util->isRecoveryEnabledForUser($uid)) {
663
+
664
+            $publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey();
665
+        }
666
+
667
+        return $publicKeys;
668
+    }
669
+
670
+    /**
671
+     * get master key password
672
+     *
673
+     * @return string
674
+     * @throws \Exception
675
+     */
676
+    public function getMasterKeyPassword() {
677
+        $password = $this->config->getSystemValue('secret');
678
+        if (empty($password)){
679
+            throw new \Exception('Can not get secret from ownCloud instance');
680
+        }
681
+
682
+        return $password;
683
+    }
684
+
685
+    /**
686
+     * return master key id
687
+     *
688
+     * @return string
689
+     */
690
+    public function getMasterKeyId() {
691
+        return $this->masterKeyId;
692
+    }
693
+
694
+    /**
695
+     * get public master key
696
+     *
697
+     * @return string
698
+     */
699
+    public function getPublicMasterKey() {
700
+        return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID);
701
+    }
702 702
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Exceptions/PublicKeyMissingException.php 1 patch
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.
apps/encryption/lib/Exceptions/PrivateKeyMissingException.php 1 patch
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.
apps/encryption/lib/AppInfo/Application.php 1 patch
Indentation   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -48,227 +48,227 @@
 block discarded – undo
48 48
 
49 49
 class Application extends \OCP\AppFramework\App {
50 50
 
51
-	/** @var IManager */
52
-	private $encryptionManager;
53
-	/** @var IConfig */
54
-	private $config;
55
-
56
-	/**
57
-	 * @param array $urlParams
58
-	 * @param bool $encryptionSystemReady
59
-	 */
60
-	public function __construct($urlParams = array(), $encryptionSystemReady = true) {
61
-		parent::__construct('encryption', $urlParams);
62
-		$this->encryptionManager = \OC::$server->getEncryptionManager();
63
-		$this->config = \OC::$server->getConfig();
64
-		$this->registerServices();
65
-		if($encryptionSystemReady === false) {
66
-			/** @var Session $session */
67
-			$session = $this->getContainer()->query('Session');
68
-			$session->setStatus(Session::RUN_MIGRATION);
69
-		}
70
-		if ($this->encryptionManager->isEnabled() && $encryptionSystemReady) {
71
-			/** @var Setup $setup */
72
-			$setup = $this->getContainer()->query('UserSetup');
73
-			$setup->setupSystem();
74
-		}
75
-	}
76
-
77
-	/**
78
-	 * register hooks
79
-	 */
80
-
81
-	public function registerHooks() {
82
-		if (!$this->config->getSystemValue('maintenance', false)) {
83
-
84
-			$container = $this->getContainer();
85
-			$server = $container->getServer();
86
-			// Register our hooks and fire them.
87
-			$hookManager = new HookManager();
88
-
89
-			$hookManager->registerHook([
90
-				new UserHooks($container->query('KeyManager'),
91
-					$server->getUserManager(),
92
-					$server->getLogger(),
93
-					$container->query('UserSetup'),
94
-					$server->getUserSession(),
95
-					$container->query('Util'),
96
-					$container->query('Session'),
97
-					$container->query('Crypt'),
98
-					$container->query('Recovery'))
99
-			]);
100
-
101
-			$hookManager->fireHooks();
102
-
103
-		} else {
104
-			// Logout user if we are in maintenance to force re-login
105
-			$this->getContainer()->getServer()->getUserSession()->logout();
106
-		}
107
-	}
108
-
109
-	public function registerEncryptionModule() {
110
-		$container = $this->getContainer();
111
-
112
-
113
-		$this->encryptionManager->registerEncryptionModule(
114
-			Encryption::ID,
115
-			Encryption::DISPLAY_NAME,
116
-			function() use ($container) {
117
-
118
-			return new Encryption(
119
-				$container->query('Crypt'),
120
-				$container->query('KeyManager'),
121
-				$container->query('Util'),
122
-				$container->query('Session'),
123
-				$container->query('EncryptAll'),
124
-				$container->query('DecryptAll'),
125
-				$container->getServer()->getLogger(),
126
-				$container->getServer()->getL10N($container->getAppName())
127
-			);
128
-		});
129
-
130
-	}
131
-
132
-	public function registerServices() {
133
-		$container = $this->getContainer();
134
-
135
-		$container->registerService('Crypt',
136
-			function (IAppContainer $c) {
137
-				$server = $c->getServer();
138
-				return new Crypt($server->getLogger(),
139
-					$server->getUserSession(),
140
-					$server->getConfig(),
141
-					$server->getL10N($c->getAppName()));
142
-			});
143
-
144
-		$container->registerService('Session',
145
-			function (IAppContainer $c) {
146
-				$server = $c->getServer();
147
-				return new Session($server->getSession());
148
-			}
149
-		);
150
-
151
-		$container->registerService('KeyManager',
152
-			function (IAppContainer $c) {
153
-				$server = $c->getServer();
154
-
155
-				return new KeyManager($server->getEncryptionKeyStorage(),
156
-					$c->query('Crypt'),
157
-					$server->getConfig(),
158
-					$server->getUserSession(),
159
-					new Session($server->getSession()),
160
-					$server->getLogger(),
161
-					$c->query('Util')
162
-				);
163
-			});
164
-
165
-		$container->registerService('Recovery',
166
-			function (IAppContainer $c) {
167
-				$server = $c->getServer();
168
-
169
-				return new Recovery(
170
-					$server->getUserSession(),
171
-					$c->query('Crypt'),
172
-					$server->getSecureRandom(),
173
-					$c->query('KeyManager'),
174
-					$server->getConfig(),
175
-					$server->getEncryptionKeyStorage(),
176
-					$server->getEncryptionFilesHelper(),
177
-					new View());
178
-			});
179
-
180
-		$container->registerService('RecoveryController', function (IAppContainer $c) {
181
-			$server = $c->getServer();
182
-			return new RecoveryController(
183
-				$c->getAppName(),
184
-				$server->getRequest(),
185
-				$server->getConfig(),
186
-				$server->getL10N($c->getAppName()),
187
-				$c->query('Recovery'));
188
-		});
189
-
190
-		$container->registerService('StatusController', function (IAppContainer $c) {
191
-			$server = $c->getServer();
192
-			return new StatusController(
193
-				$c->getAppName(),
194
-				$server->getRequest(),
195
-				$server->getL10N($c->getAppName()),
196
-				$c->query('Session')
197
-			);
198
-		});
199
-
200
-		$container->registerService('SettingsController', function (IAppContainer $c) {
201
-			$server = $c->getServer();
202
-			return new SettingsController(
203
-				$c->getAppName(),
204
-				$server->getRequest(),
205
-				$server->getL10N($c->getAppName()),
206
-				$server->getUserManager(),
207
-				$server->getUserSession(),
208
-				$c->query('KeyManager'),
209
-				$c->query('Crypt'),
210
-				$c->query('Session'),
211
-				$server->getSession(),
212
-				$c->query('Util')
213
-			);
214
-		});
215
-
216
-		$container->registerService('UserSetup',
217
-			function (IAppContainer $c) {
218
-				$server = $c->getServer();
219
-				return new Setup($server->getLogger(),
220
-					$server->getUserSession(),
221
-					$c->query('Crypt'),
222
-					$c->query('KeyManager'));
223
-			});
224
-
225
-		$container->registerService('Util',
226
-			function (IAppContainer $c) {
227
-				$server = $c->getServer();
228
-
229
-				return new Util(
230
-					new View(),
231
-					$c->query('Crypt'),
232
-					$server->getLogger(),
233
-					$server->getUserSession(),
234
-					$server->getConfig(),
235
-					$server->getUserManager());
236
-			});
237
-
238
-		$container->registerService('EncryptAll',
239
-			function (IAppContainer $c) {
240
-				$server = $c->getServer();
241
-				return new EncryptAll(
242
-					$c->query('UserSetup'),
243
-					$c->getServer()->getUserManager(),
244
-					new View(),
245
-					$c->query('KeyManager'),
246
-					$c->query('Util'),
247
-					$server->getConfig(),
248
-					$server->getMailer(),
249
-					$server->getL10N('encryption'),
250
-					new QuestionHelper(),
251
-					$server->getSecureRandom()
252
-				);
253
-			}
254
-		);
255
-
256
-		$container->registerService('DecryptAll',
257
-			function (IAppContainer $c) {
258
-				return new DecryptAll(
259
-					$c->query('Util'),
260
-					$c->query('KeyManager'),
261
-					$c->query('Crypt'),
262
-					$c->query('Session'),
263
-					new QuestionHelper()
264
-				);
265
-			}
266
-		);
267
-
268
-	}
269
-
270
-	public function registerSettings() {
271
-		// Register settings scripts
272
-		App::registerPersonal('encryption', 'settings/settings-personal');
273
-	}
51
+    /** @var IManager */
52
+    private $encryptionManager;
53
+    /** @var IConfig */
54
+    private $config;
55
+
56
+    /**
57
+     * @param array $urlParams
58
+     * @param bool $encryptionSystemReady
59
+     */
60
+    public function __construct($urlParams = array(), $encryptionSystemReady = true) {
61
+        parent::__construct('encryption', $urlParams);
62
+        $this->encryptionManager = \OC::$server->getEncryptionManager();
63
+        $this->config = \OC::$server->getConfig();
64
+        $this->registerServices();
65
+        if($encryptionSystemReady === false) {
66
+            /** @var Session $session */
67
+            $session = $this->getContainer()->query('Session');
68
+            $session->setStatus(Session::RUN_MIGRATION);
69
+        }
70
+        if ($this->encryptionManager->isEnabled() && $encryptionSystemReady) {
71
+            /** @var Setup $setup */
72
+            $setup = $this->getContainer()->query('UserSetup');
73
+            $setup->setupSystem();
74
+        }
75
+    }
76
+
77
+    /**
78
+     * register hooks
79
+     */
80
+
81
+    public function registerHooks() {
82
+        if (!$this->config->getSystemValue('maintenance', false)) {
83
+
84
+            $container = $this->getContainer();
85
+            $server = $container->getServer();
86
+            // Register our hooks and fire them.
87
+            $hookManager = new HookManager();
88
+
89
+            $hookManager->registerHook([
90
+                new UserHooks($container->query('KeyManager'),
91
+                    $server->getUserManager(),
92
+                    $server->getLogger(),
93
+                    $container->query('UserSetup'),
94
+                    $server->getUserSession(),
95
+                    $container->query('Util'),
96
+                    $container->query('Session'),
97
+                    $container->query('Crypt'),
98
+                    $container->query('Recovery'))
99
+            ]);
100
+
101
+            $hookManager->fireHooks();
102
+
103
+        } else {
104
+            // Logout user if we are in maintenance to force re-login
105
+            $this->getContainer()->getServer()->getUserSession()->logout();
106
+        }
107
+    }
108
+
109
+    public function registerEncryptionModule() {
110
+        $container = $this->getContainer();
111
+
112
+
113
+        $this->encryptionManager->registerEncryptionModule(
114
+            Encryption::ID,
115
+            Encryption::DISPLAY_NAME,
116
+            function() use ($container) {
117
+
118
+            return new Encryption(
119
+                $container->query('Crypt'),
120
+                $container->query('KeyManager'),
121
+                $container->query('Util'),
122
+                $container->query('Session'),
123
+                $container->query('EncryptAll'),
124
+                $container->query('DecryptAll'),
125
+                $container->getServer()->getLogger(),
126
+                $container->getServer()->getL10N($container->getAppName())
127
+            );
128
+        });
129
+
130
+    }
131
+
132
+    public function registerServices() {
133
+        $container = $this->getContainer();
134
+
135
+        $container->registerService('Crypt',
136
+            function (IAppContainer $c) {
137
+                $server = $c->getServer();
138
+                return new Crypt($server->getLogger(),
139
+                    $server->getUserSession(),
140
+                    $server->getConfig(),
141
+                    $server->getL10N($c->getAppName()));
142
+            });
143
+
144
+        $container->registerService('Session',
145
+            function (IAppContainer $c) {
146
+                $server = $c->getServer();
147
+                return new Session($server->getSession());
148
+            }
149
+        );
150
+
151
+        $container->registerService('KeyManager',
152
+            function (IAppContainer $c) {
153
+                $server = $c->getServer();
154
+
155
+                return new KeyManager($server->getEncryptionKeyStorage(),
156
+                    $c->query('Crypt'),
157
+                    $server->getConfig(),
158
+                    $server->getUserSession(),
159
+                    new Session($server->getSession()),
160
+                    $server->getLogger(),
161
+                    $c->query('Util')
162
+                );
163
+            });
164
+
165
+        $container->registerService('Recovery',
166
+            function (IAppContainer $c) {
167
+                $server = $c->getServer();
168
+
169
+                return new Recovery(
170
+                    $server->getUserSession(),
171
+                    $c->query('Crypt'),
172
+                    $server->getSecureRandom(),
173
+                    $c->query('KeyManager'),
174
+                    $server->getConfig(),
175
+                    $server->getEncryptionKeyStorage(),
176
+                    $server->getEncryptionFilesHelper(),
177
+                    new View());
178
+            });
179
+
180
+        $container->registerService('RecoveryController', function (IAppContainer $c) {
181
+            $server = $c->getServer();
182
+            return new RecoveryController(
183
+                $c->getAppName(),
184
+                $server->getRequest(),
185
+                $server->getConfig(),
186
+                $server->getL10N($c->getAppName()),
187
+                $c->query('Recovery'));
188
+        });
189
+
190
+        $container->registerService('StatusController', function (IAppContainer $c) {
191
+            $server = $c->getServer();
192
+            return new StatusController(
193
+                $c->getAppName(),
194
+                $server->getRequest(),
195
+                $server->getL10N($c->getAppName()),
196
+                $c->query('Session')
197
+            );
198
+        });
199
+
200
+        $container->registerService('SettingsController', function (IAppContainer $c) {
201
+            $server = $c->getServer();
202
+            return new SettingsController(
203
+                $c->getAppName(),
204
+                $server->getRequest(),
205
+                $server->getL10N($c->getAppName()),
206
+                $server->getUserManager(),
207
+                $server->getUserSession(),
208
+                $c->query('KeyManager'),
209
+                $c->query('Crypt'),
210
+                $c->query('Session'),
211
+                $server->getSession(),
212
+                $c->query('Util')
213
+            );
214
+        });
215
+
216
+        $container->registerService('UserSetup',
217
+            function (IAppContainer $c) {
218
+                $server = $c->getServer();
219
+                return new Setup($server->getLogger(),
220
+                    $server->getUserSession(),
221
+                    $c->query('Crypt'),
222
+                    $c->query('KeyManager'));
223
+            });
224
+
225
+        $container->registerService('Util',
226
+            function (IAppContainer $c) {
227
+                $server = $c->getServer();
228
+
229
+                return new Util(
230
+                    new View(),
231
+                    $c->query('Crypt'),
232
+                    $server->getLogger(),
233
+                    $server->getUserSession(),
234
+                    $server->getConfig(),
235
+                    $server->getUserManager());
236
+            });
237
+
238
+        $container->registerService('EncryptAll',
239
+            function (IAppContainer $c) {
240
+                $server = $c->getServer();
241
+                return new EncryptAll(
242
+                    $c->query('UserSetup'),
243
+                    $c->getServer()->getUserManager(),
244
+                    new View(),
245
+                    $c->query('KeyManager'),
246
+                    $c->query('Util'),
247
+                    $server->getConfig(),
248
+                    $server->getMailer(),
249
+                    $server->getL10N('encryption'),
250
+                    new QuestionHelper(),
251
+                    $server->getSecureRandom()
252
+                );
253
+            }
254
+        );
255
+
256
+        $container->registerService('DecryptAll',
257
+            function (IAppContainer $c) {
258
+                return new DecryptAll(
259
+                    $c->query('Util'),
260
+                    $c->query('KeyManager'),
261
+                    $c->query('Crypt'),
262
+                    $c->query('Session'),
263
+                    new QuestionHelper()
264
+                );
265
+            }
266
+        );
267
+
268
+    }
269
+
270
+    public function registerSettings() {
271
+        // Register settings scripts
272
+        App::registerPersonal('encryption', 'settings/settings-personal');
273
+    }
274 274
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Recovery.php 1 patch
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.
apps/encryption/lib/Command/MigrateKeys.php 1 patch
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -36,91 +36,91 @@
 block discarded – undo
36 36
 
37 37
 class MigrateKeys extends Command {
38 38
 
39
-	/** @var IUserManager */
40
-	private $userManager;
41
-	/** @var View */
42
-	private $view;
43
-	/** @var IDBConnection */
44
-	private $connection;
45
-	/** @var IConfig */
46
-	private $config;
47
-	/** @var  ILogger */
48
-	private $logger;
39
+    /** @var IUserManager */
40
+    private $userManager;
41
+    /** @var View */
42
+    private $view;
43
+    /** @var IDBConnection */
44
+    private $connection;
45
+    /** @var IConfig */
46
+    private $config;
47
+    /** @var  ILogger */
48
+    private $logger;
49 49
 
50
-	/**
51
-	 * @param IUserManager $userManager
52
-	 * @param View $view
53
-	 * @param IDBConnection $connection
54
-	 * @param IConfig $config
55
-	 * @param ILogger $logger
56
-	 */
57
-	public function __construct(IUserManager $userManager,
58
-								View $view,
59
-								IDBConnection $connection,
60
-								IConfig $config,
61
-								ILogger $logger) {
50
+    /**
51
+     * @param IUserManager $userManager
52
+     * @param View $view
53
+     * @param IDBConnection $connection
54
+     * @param IConfig $config
55
+     * @param ILogger $logger
56
+     */
57
+    public function __construct(IUserManager $userManager,
58
+                                View $view,
59
+                                IDBConnection $connection,
60
+                                IConfig $config,
61
+                                ILogger $logger) {
62 62
 
63
-		$this->userManager = $userManager;
64
-		$this->view = $view;
65
-		$this->connection = $connection;
66
-		$this->config = $config;
67
-		$this->logger = $logger;
68
-		parent::__construct();
69
-	}
63
+        $this->userManager = $userManager;
64
+        $this->view = $view;
65
+        $this->connection = $connection;
66
+        $this->config = $config;
67
+        $this->logger = $logger;
68
+        parent::__construct();
69
+    }
70 70
 
71
-	protected function configure() {
72
-		$this
73
-			->setName('encryption:migrate')
74
-			->setDescription('initial migration to encryption 2.0')
75
-			->addArgument(
76
-				'user_id',
77
-				InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
78
-				'will migrate keys of the given user(s)'
79
-			);
80
-	}
71
+    protected function configure() {
72
+        $this
73
+            ->setName('encryption:migrate')
74
+            ->setDescription('initial migration to encryption 2.0')
75
+            ->addArgument(
76
+                'user_id',
77
+                InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
78
+                'will migrate keys of the given user(s)'
79
+            );
80
+    }
81 81
 
82
-	protected function execute(InputInterface $input, OutputInterface $output) {
82
+    protected function execute(InputInterface $input, OutputInterface $output) {
83 83
 
84
-		// perform system reorganization
85
-		$migration = new Migration($this->config, $this->view, $this->connection, $this->logger);
84
+        // perform system reorganization
85
+        $migration = new Migration($this->config, $this->view, $this->connection, $this->logger);
86 86
 
87
-		$users = $input->getArgument('user_id');
88
-		if (!empty($users)) {
89
-			foreach ($users as $user) {
90
-				if ($this->userManager->userExists($user)) {
91
-					$output->writeln("Migrating keys   <info>$user</info>");
92
-					$migration->reorganizeFolderStructureForUser($user);
93
-				} else {
94
-					$output->writeln("<error>Unknown user $user</error>");
95
-				}
96
-			}
97
-		} else {
98
-			$output->writeln("Reorganize system folder structure");
99
-			$migration->reorganizeSystemFolderStructure();
100
-			$migration->updateDB();
101
-			foreach($this->userManager->getBackends() as $backend) {
102
-				$name = get_class($backend);
87
+        $users = $input->getArgument('user_id');
88
+        if (!empty($users)) {
89
+            foreach ($users as $user) {
90
+                if ($this->userManager->userExists($user)) {
91
+                    $output->writeln("Migrating keys   <info>$user</info>");
92
+                    $migration->reorganizeFolderStructureForUser($user);
93
+                } else {
94
+                    $output->writeln("<error>Unknown user $user</error>");
95
+                }
96
+            }
97
+        } else {
98
+            $output->writeln("Reorganize system folder structure");
99
+            $migration->reorganizeSystemFolderStructure();
100
+            $migration->updateDB();
101
+            foreach($this->userManager->getBackends() as $backend) {
102
+                $name = get_class($backend);
103 103
 
104
-				if ($backend instanceof IUserBackend) {
105
-					$name = $backend->getBackendName();
106
-				}
104
+                if ($backend instanceof IUserBackend) {
105
+                    $name = $backend->getBackendName();
106
+                }
107 107
 
108
-				$output->writeln("Migrating keys for users on backend <info>$name</info>");
108
+                $output->writeln("Migrating keys for users on backend <info>$name</info>");
109 109
 
110
-				$limit = 500;
111
-				$offset = 0;
112
-				do {
113
-					$users = $backend->getUsers('', $limit, $offset);
114
-					foreach ($users as $user) {
115
-						$output->writeln("   <info>$user</info>");
116
-						$migration->reorganizeFolderStructureForUser($user);
117
-					}
118
-					$offset += $limit;
119
-				} while(count($users) >= $limit);
120
-			}
121
-		}
110
+                $limit = 500;
111
+                $offset = 0;
112
+                do {
113
+                    $users = $backend->getUsers('', $limit, $offset);
114
+                    foreach ($users as $user) {
115
+                        $output->writeln("   <info>$user</info>");
116
+                        $migration->reorganizeFolderStructureForUser($user);
117
+                    }
118
+                    $offset += $limit;
119
+                } while(count($users) >= $limit);
120
+            }
121
+        }
122 122
 
123
-		$migration->finalCleanUp();
123
+        $migration->finalCleanUp();
124 124
 
125
-	}
125
+    }
126 126
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Command/EnableMasterKey.php 1 patch
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.