Completed
Push — master ( 4da6b7...5a998d )
by Björn
14:04
created
apps/files_trashbin/lib/Storage.php 2 patches
Indentation   +239 added lines, -239 removed lines patch added patch discarded remove patch
@@ -34,244 +34,244 @@
 block discarded – undo
34 34
 
35 35
 class Storage extends Wrapper {
36 36
 
37
-	private $mountPoint;
38
-	// remember already deleted files to avoid infinite loops if the trash bin
39
-	// move files across storages
40
-	private $deletedFiles = array();
41
-
42
-	/**
43
-	 * Disable trash logic
44
-	 *
45
-	 * @var bool
46
-	 */
47
-	private static $disableTrash = false;
48
-
49
-	/**
50
-	 * remember which file/folder was moved out of s shared folder
51
-	 * in this case we want to add a copy to the owners trash bin
52
-	 *
53
-	 * @var array
54
-	 */
55
-	private static $moveOutOfSharedFolder = [];
56
-
57
-	/** @var  IUserManager */
58
-	private $userManager;
59
-
60
-	/** @var ILogger */
61
-	private $logger;
62
-
63
-	/**
64
-	 * Storage constructor.
65
-	 *
66
-	 * @param array $parameters
67
-	 * @param IUserManager|null $userManager
68
-	 */
69
-	public function __construct($parameters,
70
-								IUserManager $userManager = null,
71
-								ILogger $logger = null) {
72
-		$this->mountPoint = $parameters['mountPoint'];
73
-		$this->userManager = $userManager;
74
-		$this->logger = $logger;
75
-		parent::__construct($parameters);
76
-	}
77
-
78
-	/**
79
-	 * @internal
80
-	 */
81
-	public static function preRenameHook($params) {
82
-		// in cross-storage cases, a rename is a copy + unlink,
83
-		// that last unlink must not go to trash, only exception:
84
-		// if the file was moved from a shared storage to a local folder,
85
-		// in this case the owner should get a copy in his trash bin so that
86
-		// they can restore the files again
87
-
88
-		$oldPath = $params['oldpath'];
89
-		$newPath = dirname($params['newpath']);
90
-		$currentUser = \OC::$server->getUserSession()->getUser();
91
-
92
-		$fileMovedOutOfSharedFolder = false;
93
-
94
-		try {
95
-			if ($currentUser) {
96
-				$currentUserId = $currentUser->getUID();
97
-
98
-				$view = new View($currentUserId . '/files');
99
-				$fileInfo = $view->getFileInfo($oldPath);
100
-				if ($fileInfo) {
101
-					$sourceStorage = $fileInfo->getStorage();
102
-					$sourceOwner = $view->getOwner($oldPath);
103
-					$targetOwner = $view->getOwner($newPath);
104
-
105
-					if ($sourceOwner !== $targetOwner
106
-						&& $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')
107
-					) {
108
-						$fileMovedOutOfSharedFolder = true;
109
-					}
110
-				}
111
-			}
112
-		} catch (\Exception $e) {
113
-			// do nothing, in this case we just disable the trashbin and continue
114
-			$logger = \OC::$server->getLogger();
115
-			$logger->debug('Trashbin storage could not check if a file was moved out of a shared folder: ' . $e->getMessage());
116
-		}
117
-
118
-		if($fileMovedOutOfSharedFolder) {
119
-			self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true;
120
-		} else {
121
-			self::$disableTrash = true;
122
-		}
123
-
124
-	}
125
-
126
-	/**
127
-	 * @internal
128
-	 */
129
-	public static function postRenameHook($params) {
130
-		self::$disableTrash = false;
131
-	}
132
-
133
-	/**
134
-	 * Rename path1 to path2 by calling the wrapped storage.
135
-	 *
136
-	 * @param string $path1 first path
137
-	 * @param string $path2 second path
138
-	 * @return bool
139
-	 */
140
-	public function rename($path1, $path2) {
141
-		$result = $this->storage->rename($path1, $path2);
142
-		if ($result === false) {
143
-			// when rename failed, the post_rename hook isn't triggered,
144
-			// but we still want to reenable the trash logic
145
-			self::$disableTrash = false;
146
-		}
147
-		return $result;
148
-	}
149
-
150
-	/**
151
-	 * Deletes the given file by moving it into the trashbin.
152
-	 *
153
-	 * @param string $path path of file or folder to delete
154
-	 *
155
-	 * @return bool true if the operation succeeded, false otherwise
156
-	 */
157
-	public function unlink($path) {
158
-		try {
159
-			if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
160
-				$result = $this->doDelete($path, 'unlink', true);
161
-				unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
162
-			} else {
163
-				$result = $this->doDelete($path, 'unlink');
164
-			}
165
-		} catch (GenericEncryptionException $e) {
166
-			// in case of a encryption exception we delete the file right away
167
-			$this->logger->info(
168
-				"Can't move file" .  $path .
169
-				"to the trash bin, therefore it was deleted right away");
170
-
171
-			$result = $this->storage->unlink($path);
172
-		}
173
-
174
-		return $result;
175
-	}
176
-
177
-	/**
178
-	 * Deletes the given folder by moving it into the trashbin.
179
-	 *
180
-	 * @param string $path path of folder to delete
181
-	 *
182
-	 * @return bool true if the operation succeeded, false otherwise
183
-	 */
184
-	public function rmdir($path) {
185
-		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
186
-			$result = $this->doDelete($path, 'rmdir', true);
187
-			unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
188
-		} else {
189
-			$result = $this->doDelete($path, 'rmdir');
190
-		}
191
-
192
-		return $result;
193
-	}
194
-
195
-	/**
196
-	 * check if it is a file located in data/user/files only files in the
197
-	 * 'files' directory should be moved to the trash
198
-	 *
199
-	 * @param $path
200
-	 * @return bool
201
-	 */
202
-	protected function shouldMoveToTrash($path){
203
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
204
-		$parts = explode('/', $normalized);
205
-		if (count($parts) < 4) {
206
-			return false;
207
-		}
208
-
209
-		if ($this->userManager->userExists($parts[1]) && $parts[2] == 'files') {
210
-			return true;
211
-		}
212
-
213
-		return false;
214
-	}
215
-
216
-	/**
217
-	 * Run the delete operation with the given method
218
-	 *
219
-	 * @param string $path path of file or folder to delete
220
-	 * @param string $method either "unlink" or "rmdir"
221
-	 * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
222
-	 *
223
-	 * @return bool true if the operation succeeded, false otherwise
224
-	 */
225
-	private function doDelete($path, $method, $ownerOnly = false) {
226
-		if (self::$disableTrash
227
-			|| !\OC_App::isEnabled('files_trashbin')
228
-			|| (pathinfo($path, PATHINFO_EXTENSION) === 'part')
229
-			|| $this->shouldMoveToTrash($path) === false
230
-		) {
231
-			return call_user_func_array([$this->storage, $method], [$path]);
232
-		}
233
-
234
-		// check permissions before we continue, this is especially important for
235
-		// shared files
236
-		if (!$this->isDeletable($path)) {
237
-			return false;
238
-		}
239
-
240
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true);
241
-		$result = true;
242
-		$view = Filesystem::getView();
243
-		if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) {
244
-			$this->deletedFiles[$normalized] = $normalized;
245
-			if ($filesPath = $view->getRelativePath($normalized)) {
246
-				$filesPath = trim($filesPath, '/');
247
-				$result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath, $ownerOnly);
248
-				// in cross-storage cases the file will be copied
249
-				// but not deleted, so we delete it here
250
-				if ($result) {
251
-					call_user_func_array([$this->storage, $method], [$path]);
252
-				}
253
-			} else {
254
-				$result = call_user_func_array([$this->storage, $method], [$path]);
255
-			}
256
-			unset($this->deletedFiles[$normalized]);
257
-		} else if ($this->storage->file_exists($path)) {
258
-			$result = call_user_func_array([$this->storage, $method], [$path]);
259
-		}
260
-
261
-		return $result;
262
-	}
263
-
264
-	/**
265
-	 * Setup the storate wrapper callback
266
-	 */
267
-	public static function setupStorage() {
268
-		\OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) {
269
-			return new \OCA\Files_Trashbin\Storage(
270
-				array('storage' => $storage, 'mountPoint' => $mountPoint),
271
-				\OC::$server->getUserManager(),
272
-				\OC::$server->getLogger()
273
-			);
274
-		}, 1);
275
-	}
37
+    private $mountPoint;
38
+    // remember already deleted files to avoid infinite loops if the trash bin
39
+    // move files across storages
40
+    private $deletedFiles = array();
41
+
42
+    /**
43
+     * Disable trash logic
44
+     *
45
+     * @var bool
46
+     */
47
+    private static $disableTrash = false;
48
+
49
+    /**
50
+     * remember which file/folder was moved out of s shared folder
51
+     * in this case we want to add a copy to the owners trash bin
52
+     *
53
+     * @var array
54
+     */
55
+    private static $moveOutOfSharedFolder = [];
56
+
57
+    /** @var  IUserManager */
58
+    private $userManager;
59
+
60
+    /** @var ILogger */
61
+    private $logger;
62
+
63
+    /**
64
+     * Storage constructor.
65
+     *
66
+     * @param array $parameters
67
+     * @param IUserManager|null $userManager
68
+     */
69
+    public function __construct($parameters,
70
+                                IUserManager $userManager = null,
71
+                                ILogger $logger = null) {
72
+        $this->mountPoint = $parameters['mountPoint'];
73
+        $this->userManager = $userManager;
74
+        $this->logger = $logger;
75
+        parent::__construct($parameters);
76
+    }
77
+
78
+    /**
79
+     * @internal
80
+     */
81
+    public static function preRenameHook($params) {
82
+        // in cross-storage cases, a rename is a copy + unlink,
83
+        // that last unlink must not go to trash, only exception:
84
+        // if the file was moved from a shared storage to a local folder,
85
+        // in this case the owner should get a copy in his trash bin so that
86
+        // they can restore the files again
87
+
88
+        $oldPath = $params['oldpath'];
89
+        $newPath = dirname($params['newpath']);
90
+        $currentUser = \OC::$server->getUserSession()->getUser();
91
+
92
+        $fileMovedOutOfSharedFolder = false;
93
+
94
+        try {
95
+            if ($currentUser) {
96
+                $currentUserId = $currentUser->getUID();
97
+
98
+                $view = new View($currentUserId . '/files');
99
+                $fileInfo = $view->getFileInfo($oldPath);
100
+                if ($fileInfo) {
101
+                    $sourceStorage = $fileInfo->getStorage();
102
+                    $sourceOwner = $view->getOwner($oldPath);
103
+                    $targetOwner = $view->getOwner($newPath);
104
+
105
+                    if ($sourceOwner !== $targetOwner
106
+                        && $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')
107
+                    ) {
108
+                        $fileMovedOutOfSharedFolder = true;
109
+                    }
110
+                }
111
+            }
112
+        } catch (\Exception $e) {
113
+            // do nothing, in this case we just disable the trashbin and continue
114
+            $logger = \OC::$server->getLogger();
115
+            $logger->debug('Trashbin storage could not check if a file was moved out of a shared folder: ' . $e->getMessage());
116
+        }
117
+
118
+        if($fileMovedOutOfSharedFolder) {
119
+            self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true;
120
+        } else {
121
+            self::$disableTrash = true;
122
+        }
123
+
124
+    }
125
+
126
+    /**
127
+     * @internal
128
+     */
129
+    public static function postRenameHook($params) {
130
+        self::$disableTrash = false;
131
+    }
132
+
133
+    /**
134
+     * Rename path1 to path2 by calling the wrapped storage.
135
+     *
136
+     * @param string $path1 first path
137
+     * @param string $path2 second path
138
+     * @return bool
139
+     */
140
+    public function rename($path1, $path2) {
141
+        $result = $this->storage->rename($path1, $path2);
142
+        if ($result === false) {
143
+            // when rename failed, the post_rename hook isn't triggered,
144
+            // but we still want to reenable the trash logic
145
+            self::$disableTrash = false;
146
+        }
147
+        return $result;
148
+    }
149
+
150
+    /**
151
+     * Deletes the given file by moving it into the trashbin.
152
+     *
153
+     * @param string $path path of file or folder to delete
154
+     *
155
+     * @return bool true if the operation succeeded, false otherwise
156
+     */
157
+    public function unlink($path) {
158
+        try {
159
+            if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
160
+                $result = $this->doDelete($path, 'unlink', true);
161
+                unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
162
+            } else {
163
+                $result = $this->doDelete($path, 'unlink');
164
+            }
165
+        } catch (GenericEncryptionException $e) {
166
+            // in case of a encryption exception we delete the file right away
167
+            $this->logger->info(
168
+                "Can't move file" .  $path .
169
+                "to the trash bin, therefore it was deleted right away");
170
+
171
+            $result = $this->storage->unlink($path);
172
+        }
173
+
174
+        return $result;
175
+    }
176
+
177
+    /**
178
+     * Deletes the given folder by moving it into the trashbin.
179
+     *
180
+     * @param string $path path of folder to delete
181
+     *
182
+     * @return bool true if the operation succeeded, false otherwise
183
+     */
184
+    public function rmdir($path) {
185
+        if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
186
+            $result = $this->doDelete($path, 'rmdir', true);
187
+            unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
188
+        } else {
189
+            $result = $this->doDelete($path, 'rmdir');
190
+        }
191
+
192
+        return $result;
193
+    }
194
+
195
+    /**
196
+     * check if it is a file located in data/user/files only files in the
197
+     * 'files' directory should be moved to the trash
198
+     *
199
+     * @param $path
200
+     * @return bool
201
+     */
202
+    protected function shouldMoveToTrash($path){
203
+        $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
204
+        $parts = explode('/', $normalized);
205
+        if (count($parts) < 4) {
206
+            return false;
207
+        }
208
+
209
+        if ($this->userManager->userExists($parts[1]) && $parts[2] == 'files') {
210
+            return true;
211
+        }
212
+
213
+        return false;
214
+    }
215
+
216
+    /**
217
+     * Run the delete operation with the given method
218
+     *
219
+     * @param string $path path of file or folder to delete
220
+     * @param string $method either "unlink" or "rmdir"
221
+     * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
222
+     *
223
+     * @return bool true if the operation succeeded, false otherwise
224
+     */
225
+    private function doDelete($path, $method, $ownerOnly = false) {
226
+        if (self::$disableTrash
227
+            || !\OC_App::isEnabled('files_trashbin')
228
+            || (pathinfo($path, PATHINFO_EXTENSION) === 'part')
229
+            || $this->shouldMoveToTrash($path) === false
230
+        ) {
231
+            return call_user_func_array([$this->storage, $method], [$path]);
232
+        }
233
+
234
+        // check permissions before we continue, this is especially important for
235
+        // shared files
236
+        if (!$this->isDeletable($path)) {
237
+            return false;
238
+        }
239
+
240
+        $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true);
241
+        $result = true;
242
+        $view = Filesystem::getView();
243
+        if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) {
244
+            $this->deletedFiles[$normalized] = $normalized;
245
+            if ($filesPath = $view->getRelativePath($normalized)) {
246
+                $filesPath = trim($filesPath, '/');
247
+                $result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath, $ownerOnly);
248
+                // in cross-storage cases the file will be copied
249
+                // but not deleted, so we delete it here
250
+                if ($result) {
251
+                    call_user_func_array([$this->storage, $method], [$path]);
252
+                }
253
+            } else {
254
+                $result = call_user_func_array([$this->storage, $method], [$path]);
255
+            }
256
+            unset($this->deletedFiles[$normalized]);
257
+        } else if ($this->storage->file_exists($path)) {
258
+            $result = call_user_func_array([$this->storage, $method], [$path]);
259
+        }
260
+
261
+        return $result;
262
+    }
263
+
264
+    /**
265
+     * Setup the storate wrapper callback
266
+     */
267
+    public static function setupStorage() {
268
+        \OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) {
269
+            return new \OCA\Files_Trashbin\Storage(
270
+                array('storage' => $storage, 'mountPoint' => $mountPoint),
271
+                \OC::$server->getUserManager(),
272
+                \OC::$server->getLogger()
273
+            );
274
+        }, 1);
275
+    }
276 276
 
277 277
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 			if ($currentUser) {
96 96
 				$currentUserId = $currentUser->getUID();
97 97
 
98
-				$view = new View($currentUserId . '/files');
98
+				$view = new View($currentUserId.'/files');
99 99
 				$fileInfo = $view->getFileInfo($oldPath);
100 100
 				if ($fileInfo) {
101 101
 					$sourceStorage = $fileInfo->getStorage();
@@ -112,11 +112,11 @@  discard block
 block discarded – undo
112 112
 		} catch (\Exception $e) {
113 113
 			// do nothing, in this case we just disable the trashbin and continue
114 114
 			$logger = \OC::$server->getLogger();
115
-			$logger->debug('Trashbin storage could not check if a file was moved out of a shared folder: ' . $e->getMessage());
115
+			$logger->debug('Trashbin storage could not check if a file was moved out of a shared folder: '.$e->getMessage());
116 116
 		}
117 117
 
118
-		if($fileMovedOutOfSharedFolder) {
119
-			self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true;
118
+		if ($fileMovedOutOfSharedFolder) {
119
+			self::$moveOutOfSharedFolder['/'.$currentUserId.'/files'.$oldPath] = true;
120 120
 		} else {
121 121
 			self::$disableTrash = true;
122 122
 		}
@@ -156,16 +156,16 @@  discard block
 block discarded – undo
156 156
 	 */
157 157
 	public function unlink($path) {
158 158
 		try {
159
-			if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
159
+			if (isset(self::$moveOutOfSharedFolder[$this->mountPoint.$path])) {
160 160
 				$result = $this->doDelete($path, 'unlink', true);
161
-				unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
161
+				unset(self::$moveOutOfSharedFolder[$this->mountPoint.$path]);
162 162
 			} else {
163 163
 				$result = $this->doDelete($path, 'unlink');
164 164
 			}
165 165
 		} catch (GenericEncryptionException $e) {
166 166
 			// in case of a encryption exception we delete the file right away
167 167
 			$this->logger->info(
168
-				"Can't move file" .  $path .
168
+				"Can't move file".$path.
169 169
 				"to the trash bin, therefore it was deleted right away");
170 170
 
171 171
 			$result = $this->storage->unlink($path);
@@ -182,9 +182,9 @@  discard block
 block discarded – undo
182 182
 	 * @return bool true if the operation succeeded, false otherwise
183 183
 	 */
184 184
 	public function rmdir($path) {
185
-		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
185
+		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint.$path])) {
186 186
 			$result = $this->doDelete($path, 'rmdir', true);
187
-			unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
187
+			unset(self::$moveOutOfSharedFolder[$this->mountPoint.$path]);
188 188
 		} else {
189 189
 			$result = $this->doDelete($path, 'rmdir');
190 190
 		}
@@ -199,8 +199,8 @@  discard block
 block discarded – undo
199 199
 	 * @param $path
200 200
 	 * @return bool
201 201
 	 */
202
-	protected function shouldMoveToTrash($path){
203
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
202
+	protected function shouldMoveToTrash($path) {
203
+		$normalized = Filesystem::normalizePath($this->mountPoint.'/'.$path);
204 204
 		$parts = explode('/', $normalized);
205 205
 		if (count($parts) < 4) {
206 206
 			return false;
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
 			return false;
238 238
 		}
239 239
 
240
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true);
240
+		$normalized = Filesystem::normalizePath($this->mountPoint.'/'.$path, true, false, true);
241 241
 		$result = true;
242 242
 		$view = Filesystem::getView();
243 243
 		if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) {
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 	 * Setup the storate wrapper callback
266 266
 	 */
267 267
 	public static function setupStorage() {
268
-		\OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) {
268
+		\OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function($mountPoint, $storage) {
269 269
 			return new \OCA\Files_Trashbin\Storage(
270 270
 				array('storage' => $storage, 'mountPoint' => $mountPoint),
271 271
 				\OC::$server->getUserManager(),
Please login to merge, or discard this patch.
apps/encryption/lib/Crypto/Crypt.php 1 patch
Indentation   +636 added lines, -636 removed lines patch added patch discarded remove patch
@@ -53,641 +53,641 @@
 block discarded – undo
53 53
  */
54 54
 class Crypt {
55 55
 
56
-	const DEFAULT_CIPHER = 'AES-256-CTR';
57
-	// default cipher from old ownCloud versions
58
-	const LEGACY_CIPHER = 'AES-128-CFB';
59
-
60
-	// default key format, old ownCloud version encrypted the private key directly
61
-	// with the user password
62
-	const LEGACY_KEY_FORMAT = 'password';
63
-
64
-	const HEADER_START = 'HBEGIN';
65
-	const HEADER_END = 'HEND';
66
-
67
-	/** @var ILogger */
68
-	private $logger;
69
-
70
-	/** @var string */
71
-	private $user;
72
-
73
-	/** @var IConfig */
74
-	private $config;
75
-
76
-	/** @var array */
77
-	private $supportedKeyFormats;
78
-
79
-	/** @var IL10N */
80
-	private $l;
81
-
82
-	/** @var array */
83
-	private $supportedCiphersAndKeySize = [
84
-		'AES-256-CTR' => 32,
85
-		'AES-128-CTR' => 16,
86
-		'AES-256-CFB' => 32,
87
-		'AES-128-CFB' => 16,
88
-	];
89
-
90
-	/**
91
-	 * @param ILogger $logger
92
-	 * @param IUserSession $userSession
93
-	 * @param IConfig $config
94
-	 * @param IL10N $l
95
-	 */
96
-	public function __construct(ILogger $logger, IUserSession $userSession, IConfig $config, IL10N $l) {
97
-		$this->logger = $logger;
98
-		$this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : '"no user given"';
99
-		$this->config = $config;
100
-		$this->l = $l;
101
-		$this->supportedKeyFormats = ['hash', 'password'];
102
-	}
103
-
104
-	/**
105
-	 * create new private/public key-pair for user
106
-	 *
107
-	 * @return array|bool
108
-	 */
109
-	public function createKeyPair() {
110
-
111
-		$log = $this->logger;
112
-		$res = $this->getOpenSSLPKey();
113
-
114
-		if (!$res) {
115
-			$log->error("Encryption Library couldn't generate users key-pair for {$this->user}",
116
-				['app' => 'encryption']);
117
-
118
-			if (openssl_error_string()) {
119
-				$log->error('Encryption library openssl_pkey_new() fails: ' . openssl_error_string(),
120
-					['app' => 'encryption']);
121
-			}
122
-		} elseif (openssl_pkey_export($res,
123
-			$privateKey,
124
-			null,
125
-			$this->getOpenSSLConfig())) {
126
-			$keyDetails = openssl_pkey_get_details($res);
127
-			$publicKey = $keyDetails['key'];
128
-
129
-			return [
130
-				'publicKey' => $publicKey,
131
-				'privateKey' => $privateKey
132
-			];
133
-		}
134
-		$log->error('Encryption library couldn\'t export users private key, please check your servers OpenSSL configuration.' . $this->user,
135
-			['app' => 'encryption']);
136
-		if (openssl_error_string()) {
137
-			$log->error('Encryption Library:' . openssl_error_string(),
138
-				['app' => 'encryption']);
139
-		}
140
-
141
-		return false;
142
-	}
143
-
144
-	/**
145
-	 * Generates a new private key
146
-	 *
147
-	 * @return resource
148
-	 */
149
-	public function getOpenSSLPKey() {
150
-		$config = $this->getOpenSSLConfig();
151
-		return openssl_pkey_new($config);
152
-	}
153
-
154
-	/**
155
-	 * get openSSL Config
156
-	 *
157
-	 * @return array
158
-	 */
159
-	private function getOpenSSLConfig() {
160
-		$config = ['private_key_bits' => 4096];
161
-		$config = array_merge(
162
-			$config,
163
-			$this->config->getSystemValue('openssl', [])
164
-		);
165
-		return $config;
166
-	}
167
-
168
-	/**
169
-	 * @param string $plainContent
170
-	 * @param string $passPhrase
171
-	 * @param int $version
172
-	 * @param int $position
173
-	 * @return false|string
174
-	 * @throws EncryptionFailedException
175
-	 */
176
-	public function symmetricEncryptFileContent($plainContent, $passPhrase, $version, $position) {
177
-
178
-		if (!$plainContent) {
179
-			$this->logger->error('Encryption Library, symmetrical encryption failed no content given',
180
-				['app' => 'encryption']);
181
-			return false;
182
-		}
183
-
184
-		$iv = $this->generateIv();
185
-
186
-		$encryptedContent = $this->encrypt($plainContent,
187
-			$iv,
188
-			$passPhrase,
189
-			$this->getCipher());
190
-
191
-		// Create a signature based on the key as well as the current version
192
-		$sig = $this->createSignature($encryptedContent, $passPhrase.$version.$position);
193
-
194
-		// combine content to encrypt the IV identifier and actual IV
195
-		$catFile = $this->concatIV($encryptedContent, $iv);
196
-		$catFile = $this->concatSig($catFile, $sig);
197
-		$padded = $this->addPadding($catFile);
198
-
199
-		return $padded;
200
-	}
201
-
202
-	/**
203
-	 * generate header for encrypted file
204
-	 *
205
-	 * @param string $keyFormat (can be 'hash' or 'password')
206
-	 * @return string
207
-	 * @throws \InvalidArgumentException
208
-	 */
209
-	public function generateHeader($keyFormat = 'hash') {
210
-
211
-		if (in_array($keyFormat, $this->supportedKeyFormats, true) === false) {
212
-			throw new \InvalidArgumentException('key format "' . $keyFormat . '" is not supported');
213
-		}
214
-
215
-		$cipher = $this->getCipher();
216
-
217
-		$header = self::HEADER_START
218
-			. ':cipher:' . $cipher
219
-			. ':keyFormat:' . $keyFormat
220
-			. ':' . self::HEADER_END;
221
-
222
-		return $header;
223
-	}
224
-
225
-	/**
226
-	 * @param string $plainContent
227
-	 * @param string $iv
228
-	 * @param string $passPhrase
229
-	 * @param string $cipher
230
-	 * @return string
231
-	 * @throws EncryptionFailedException
232
-	 */
233
-	private function encrypt($plainContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) {
234
-		$encryptedContent = openssl_encrypt($plainContent,
235
-			$cipher,
236
-			$passPhrase,
237
-			false,
238
-			$iv);
239
-
240
-		if (!$encryptedContent) {
241
-			$error = 'Encryption (symmetric) of content failed';
242
-			$this->logger->error($error . openssl_error_string(),
243
-				['app' => 'encryption']);
244
-			throw new EncryptionFailedException($error);
245
-		}
246
-
247
-		return $encryptedContent;
248
-	}
249
-
250
-	/**
251
-	 * return Cipher either from config.php or the default cipher defined in
252
-	 * this class
253
-	 *
254
-	 * @return string
255
-	 */
256
-	public function getCipher() {
257
-		$cipher = $this->config->getSystemValue('cipher', self::DEFAULT_CIPHER);
258
-		if (!isset($this->supportedCiphersAndKeySize[$cipher])) {
259
-			$this->logger->warning(
260
-					sprintf(
261
-							'Unsupported cipher (%s) defined in config.php supported. Falling back to %s',
262
-							$cipher,
263
-							self::DEFAULT_CIPHER
264
-					),
265
-				['app' => 'encryption']);
266
-			$cipher = self::DEFAULT_CIPHER;
267
-		}
268
-
269
-		// Workaround for OpenSSL 0.9.8. Fallback to an old cipher that should work.
270
-		if(OPENSSL_VERSION_NUMBER < 0x1000101f) {
271
-			if($cipher === 'AES-256-CTR' || $cipher === 'AES-128-CTR') {
272
-				$cipher = self::LEGACY_CIPHER;
273
-			}
274
-		}
275
-
276
-		return $cipher;
277
-	}
278
-
279
-	/**
280
-	 * get key size depending on the cipher
281
-	 *
282
-	 * @param string $cipher
283
-	 * @return int
284
-	 * @throws \InvalidArgumentException
285
-	 */
286
-	protected function getKeySize($cipher) {
287
-		if(isset($this->supportedCiphersAndKeySize[$cipher])) {
288
-			return $this->supportedCiphersAndKeySize[$cipher];
289
-		}
290
-
291
-		throw new \InvalidArgumentException(
292
-			sprintf(
293
-					'Unsupported cipher (%s) defined.',
294
-					$cipher
295
-			)
296
-		);
297
-	}
298
-
299
-	/**
300
-	 * get legacy cipher
301
-	 *
302
-	 * @return string
303
-	 */
304
-	public function getLegacyCipher() {
305
-		return self::LEGACY_CIPHER;
306
-	}
307
-
308
-	/**
309
-	 * @param string $encryptedContent
310
-	 * @param string $iv
311
-	 * @return string
312
-	 */
313
-	private function concatIV($encryptedContent, $iv) {
314
-		return $encryptedContent . '00iv00' . $iv;
315
-	}
316
-
317
-	/**
318
-	 * @param string $encryptedContent
319
-	 * @param string $signature
320
-	 * @return string
321
-	 */
322
-	private function concatSig($encryptedContent, $signature) {
323
-		return $encryptedContent . '00sig00' . $signature;
324
-	}
325
-
326
-	/**
327
-	 * Note: This is _NOT_ a padding used for encryption purposes. It is solely
328
-	 * used to achieve the PHP stream size. It has _NOTHING_ to do with the
329
-	 * encrypted content and is not used in any crypto primitive.
330
-	 *
331
-	 * @param string $data
332
-	 * @return string
333
-	 */
334
-	private function addPadding($data) {
335
-		return $data . 'xxx';
336
-	}
337
-
338
-	/**
339
-	 * generate password hash used to encrypt the users private key
340
-	 *
341
-	 * @param string $password
342
-	 * @param string $cipher
343
-	 * @param string $uid only used for user keys
344
-	 * @return string
345
-	 */
346
-	protected function generatePasswordHash($password, $cipher, $uid = '') {
347
-		$instanceId = $this->config->getSystemValue('instanceid');
348
-		$instanceSecret = $this->config->getSystemValue('secret');
349
-		$salt = hash('sha256', $uid . $instanceId . $instanceSecret, true);
350
-		$keySize = $this->getKeySize($cipher);
351
-
352
-		$hash = hash_pbkdf2(
353
-			'sha256',
354
-			$password,
355
-			$salt,
356
-			100000,
357
-			$keySize,
358
-			true
359
-		);
360
-
361
-		return $hash;
362
-	}
363
-
364
-	/**
365
-	 * encrypt private key
366
-	 *
367
-	 * @param string $privateKey
368
-	 * @param string $password
369
-	 * @param string $uid for regular users, empty for system keys
370
-	 * @return false|string
371
-	 */
372
-	public function encryptPrivateKey($privateKey, $password, $uid = '') {
373
-		$cipher = $this->getCipher();
374
-		$hash = $this->generatePasswordHash($password, $cipher, $uid);
375
-		$encryptedKey = $this->symmetricEncryptFileContent(
376
-			$privateKey,
377
-			$hash,
378
-			0,
379
-			0
380
-		);
381
-
382
-		return $encryptedKey;
383
-	}
384
-
385
-	/**
386
-	 * @param string $privateKey
387
-	 * @param string $password
388
-	 * @param string $uid for regular users, empty for system keys
389
-	 * @return false|string
390
-	 */
391
-	public function decryptPrivateKey($privateKey, $password = '', $uid = '') {
392
-
393
-		$header = $this->parseHeader($privateKey);
394
-
395
-		if (isset($header['cipher'])) {
396
-			$cipher = $header['cipher'];
397
-		} else {
398
-			$cipher = self::LEGACY_CIPHER;
399
-		}
400
-
401
-		if (isset($header['keyFormat'])) {
402
-			$keyFormat = $header['keyFormat'];
403
-		} else {
404
-			$keyFormat = self::LEGACY_KEY_FORMAT;
405
-		}
406
-
407
-		if ($keyFormat === 'hash') {
408
-			$password = $this->generatePasswordHash($password, $cipher, $uid);
409
-		}
410
-
411
-		// If we found a header we need to remove it from the key we want to decrypt
412
-		if (!empty($header)) {
413
-			$privateKey = substr($privateKey,
414
-				strpos($privateKey,
415
-					self::HEADER_END) + strlen(self::HEADER_END));
416
-		}
417
-
418
-		$plainKey = $this->symmetricDecryptFileContent(
419
-			$privateKey,
420
-			$password,
421
-			$cipher,
422
-			0
423
-		);
424
-
425
-		if ($this->isValidPrivateKey($plainKey) === false) {
426
-			return false;
427
-		}
428
-
429
-		return $plainKey;
430
-	}
431
-
432
-	/**
433
-	 * check if it is a valid private key
434
-	 *
435
-	 * @param string $plainKey
436
-	 * @return bool
437
-	 */
438
-	protected function isValidPrivateKey($plainKey) {
439
-		$res = openssl_get_privatekey($plainKey);
440
-		if (is_resource($res)) {
441
-			$sslInfo = openssl_pkey_get_details($res);
442
-			if (isset($sslInfo['key'])) {
443
-				return true;
444
-			}
445
-		}
446
-
447
-		return false;
448
-	}
449
-
450
-	/**
451
-	 * @param string $keyFileContents
452
-	 * @param string $passPhrase
453
-	 * @param string $cipher
454
-	 * @param int $version
455
-	 * @param int $position
456
-	 * @return string
457
-	 * @throws DecryptionFailedException
458
-	 */
459
-	public function symmetricDecryptFileContent($keyFileContents, $passPhrase, $cipher = self::DEFAULT_CIPHER, $version = 0, $position = 0) {
460
-		$catFile = $this->splitMetaData($keyFileContents, $cipher);
461
-
462
-		if ($catFile['signature'] !== false) {
463
-			$this->checkSignature($catFile['encrypted'], $passPhrase.$version.$position, $catFile['signature']);
464
-		}
465
-
466
-		return $this->decrypt($catFile['encrypted'],
467
-			$catFile['iv'],
468
-			$passPhrase,
469
-			$cipher);
470
-	}
471
-
472
-	/**
473
-	 * check for valid signature
474
-	 *
475
-	 * @param string $data
476
-	 * @param string $passPhrase
477
-	 * @param string $expectedSignature
478
-	 * @throws GenericEncryptionException
479
-	 */
480
-	private function checkSignature($data, $passPhrase, $expectedSignature) {
481
-		$signature = $this->createSignature($data, $passPhrase);
482
-		if (!hash_equals($expectedSignature, $signature)) {
483
-			throw new GenericEncryptionException('Bad Signature', $this->l->t('Bad Signature'));
484
-		}
485
-	}
486
-
487
-	/**
488
-	 * create signature
489
-	 *
490
-	 * @param string $data
491
-	 * @param string $passPhrase
492
-	 * @return string
493
-	 */
494
-	private function createSignature($data, $passPhrase) {
495
-		$passPhrase = hash('sha512', $passPhrase . 'a', true);
496
-		$signature = hash_hmac('sha256', $data, $passPhrase);
497
-		return $signature;
498
-	}
499
-
500
-
501
-	/**
502
-	 * remove padding
503
-	 *
504
-	 * @param string $padded
505
-	 * @param bool $hasSignature did the block contain a signature, in this case we use a different padding
506
-	 * @return string|false
507
-	 */
508
-	private function removePadding($padded, $hasSignature = false) {
509
-		if ($hasSignature === false && substr($padded, -2) === 'xx') {
510
-			return substr($padded, 0, -2);
511
-		} elseif ($hasSignature === true && substr($padded, -3) === 'xxx') {
512
-			return substr($padded, 0, -3);
513
-		}
514
-		return false;
515
-	}
516
-
517
-	/**
518
-	 * split meta data from encrypted file
519
-	 * Note: for now, we assume that the meta data always start with the iv
520
-	 *       followed by the signature, if available
521
-	 *
522
-	 * @param string $catFile
523
-	 * @param string $cipher
524
-	 * @return array
525
-	 */
526
-	private function splitMetaData($catFile, $cipher) {
527
-		if ($this->hasSignature($catFile, $cipher)) {
528
-			$catFile = $this->removePadding($catFile, true);
529
-			$meta = substr($catFile, -93);
530
-			$iv = substr($meta, strlen('00iv00'), 16);
531
-			$sig = substr($meta, 22 + strlen('00sig00'));
532
-			$encrypted = substr($catFile, 0, -93);
533
-		} else {
534
-			$catFile = $this->removePadding($catFile);
535
-			$meta = substr($catFile, -22);
536
-			$iv = substr($meta, -16);
537
-			$sig = false;
538
-			$encrypted = substr($catFile, 0, -22);
539
-		}
540
-
541
-		return [
542
-			'encrypted' => $encrypted,
543
-			'iv' => $iv,
544
-			'signature' => $sig
545
-		];
546
-	}
547
-
548
-	/**
549
-	 * check if encrypted block is signed
550
-	 *
551
-	 * @param string $catFile
552
-	 * @param string $cipher
553
-	 * @return bool
554
-	 * @throws GenericEncryptionException
555
-	 */
556
-	private function hasSignature($catFile, $cipher) {
557
-		$meta = substr($catFile, -93);
558
-		$signaturePosition = strpos($meta, '00sig00');
559
-
560
-		// enforce signature for the new 'CTR' ciphers
561
-		if ($signaturePosition === false && strpos(strtolower($cipher), 'ctr') !== false) {
562
-			throw new GenericEncryptionException('Missing Signature', $this->l->t('Missing Signature'));
563
-		}
564
-
565
-		return ($signaturePosition !== false);
566
-	}
567
-
568
-
569
-	/**
570
-	 * @param string $encryptedContent
571
-	 * @param string $iv
572
-	 * @param string $passPhrase
573
-	 * @param string $cipher
574
-	 * @return string
575
-	 * @throws DecryptionFailedException
576
-	 */
577
-	private function decrypt($encryptedContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) {
578
-		$plainContent = openssl_decrypt($encryptedContent,
579
-			$cipher,
580
-			$passPhrase,
581
-			false,
582
-			$iv);
583
-
584
-		if ($plainContent) {
585
-			return $plainContent;
586
-		} else {
587
-			throw new DecryptionFailedException('Encryption library: Decryption (symmetric) of content failed: ' . openssl_error_string());
588
-		}
589
-	}
590
-
591
-	/**
592
-	 * @param string $data
593
-	 * @return array
594
-	 */
595
-	protected function parseHeader($data) {
596
-		$result = [];
597
-
598
-		if (substr($data, 0, strlen(self::HEADER_START)) === self::HEADER_START) {
599
-			$endAt = strpos($data, self::HEADER_END);
600
-			$header = substr($data, 0, $endAt + strlen(self::HEADER_END));
601
-
602
-			// +1 not to start with an ':' which would result in empty element at the beginning
603
-			$exploded = explode(':',
604
-				substr($header, strlen(self::HEADER_START) + 1));
605
-
606
-			$element = array_shift($exploded);
607
-
608
-			while ($element != self::HEADER_END) {
609
-				$result[$element] = array_shift($exploded);
610
-				$element = array_shift($exploded);
611
-			}
612
-		}
613
-
614
-		return $result;
615
-	}
616
-
617
-	/**
618
-	 * generate initialization vector
619
-	 *
620
-	 * @return string
621
-	 * @throws GenericEncryptionException
622
-	 */
623
-	private function generateIv() {
624
-		return random_bytes(16);
625
-	}
626
-
627
-	/**
628
-	 * Generate a cryptographically secure pseudo-random 256-bit ASCII key, used
629
-	 * as file key
630
-	 *
631
-	 * @return string
632
-	 * @throws \Exception
633
-	 */
634
-	public function generateFileKey() {
635
-		return random_bytes(32);
636
-	}
637
-
638
-	/**
639
-	 * @param $encKeyFile
640
-	 * @param $shareKey
641
-	 * @param $privateKey
642
-	 * @return string
643
-	 * @throws MultiKeyDecryptException
644
-	 */
645
-	public function multiKeyDecrypt($encKeyFile, $shareKey, $privateKey) {
646
-		if (!$encKeyFile) {
647
-			throw new MultiKeyDecryptException('Cannot multikey decrypt empty plain content');
648
-		}
649
-
650
-		if (openssl_open($encKeyFile, $plainContent, $shareKey, $privateKey)) {
651
-			return $plainContent;
652
-		} else {
653
-			throw new MultiKeyDecryptException('multikeydecrypt with share key failed:' . openssl_error_string());
654
-		}
655
-	}
656
-
657
-	/**
658
-	 * @param string $plainContent
659
-	 * @param array $keyFiles
660
-	 * @return array
661
-	 * @throws MultiKeyEncryptException
662
-	 */
663
-	public function multiKeyEncrypt($plainContent, array $keyFiles) {
664
-		// openssl_seal returns false without errors if plaincontent is empty
665
-		// so trigger our own error
666
-		if (empty($plainContent)) {
667
-			throw new MultiKeyEncryptException('Cannot multikeyencrypt empty plain content');
668
-		}
669
-
670
-		// Set empty vars to be set by openssl by reference
671
-		$sealed = '';
672
-		$shareKeys = [];
673
-		$mappedShareKeys = [];
674
-
675
-		if (openssl_seal($plainContent, $sealed, $shareKeys, $keyFiles)) {
676
-			$i = 0;
677
-
678
-			// Ensure each shareKey is labelled with its corresponding key id
679
-			foreach ($keyFiles as $userId => $publicKey) {
680
-				$mappedShareKeys[$userId] = $shareKeys[$i];
681
-				$i++;
682
-			}
683
-
684
-			return [
685
-				'keys' => $mappedShareKeys,
686
-				'data' => $sealed
687
-			];
688
-		} else {
689
-			throw new MultiKeyEncryptException('multikeyencryption failed ' . openssl_error_string());
690
-		}
691
-	}
56
+    const DEFAULT_CIPHER = 'AES-256-CTR';
57
+    // default cipher from old ownCloud versions
58
+    const LEGACY_CIPHER = 'AES-128-CFB';
59
+
60
+    // default key format, old ownCloud version encrypted the private key directly
61
+    // with the user password
62
+    const LEGACY_KEY_FORMAT = 'password';
63
+
64
+    const HEADER_START = 'HBEGIN';
65
+    const HEADER_END = 'HEND';
66
+
67
+    /** @var ILogger */
68
+    private $logger;
69
+
70
+    /** @var string */
71
+    private $user;
72
+
73
+    /** @var IConfig */
74
+    private $config;
75
+
76
+    /** @var array */
77
+    private $supportedKeyFormats;
78
+
79
+    /** @var IL10N */
80
+    private $l;
81
+
82
+    /** @var array */
83
+    private $supportedCiphersAndKeySize = [
84
+        'AES-256-CTR' => 32,
85
+        'AES-128-CTR' => 16,
86
+        'AES-256-CFB' => 32,
87
+        'AES-128-CFB' => 16,
88
+    ];
89
+
90
+    /**
91
+     * @param ILogger $logger
92
+     * @param IUserSession $userSession
93
+     * @param IConfig $config
94
+     * @param IL10N $l
95
+     */
96
+    public function __construct(ILogger $logger, IUserSession $userSession, IConfig $config, IL10N $l) {
97
+        $this->logger = $logger;
98
+        $this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : '"no user given"';
99
+        $this->config = $config;
100
+        $this->l = $l;
101
+        $this->supportedKeyFormats = ['hash', 'password'];
102
+    }
103
+
104
+    /**
105
+     * create new private/public key-pair for user
106
+     *
107
+     * @return array|bool
108
+     */
109
+    public function createKeyPair() {
110
+
111
+        $log = $this->logger;
112
+        $res = $this->getOpenSSLPKey();
113
+
114
+        if (!$res) {
115
+            $log->error("Encryption Library couldn't generate users key-pair for {$this->user}",
116
+                ['app' => 'encryption']);
117
+
118
+            if (openssl_error_string()) {
119
+                $log->error('Encryption library openssl_pkey_new() fails: ' . openssl_error_string(),
120
+                    ['app' => 'encryption']);
121
+            }
122
+        } elseif (openssl_pkey_export($res,
123
+            $privateKey,
124
+            null,
125
+            $this->getOpenSSLConfig())) {
126
+            $keyDetails = openssl_pkey_get_details($res);
127
+            $publicKey = $keyDetails['key'];
128
+
129
+            return [
130
+                'publicKey' => $publicKey,
131
+                'privateKey' => $privateKey
132
+            ];
133
+        }
134
+        $log->error('Encryption library couldn\'t export users private key, please check your servers OpenSSL configuration.' . $this->user,
135
+            ['app' => 'encryption']);
136
+        if (openssl_error_string()) {
137
+            $log->error('Encryption Library:' . openssl_error_string(),
138
+                ['app' => 'encryption']);
139
+        }
140
+
141
+        return false;
142
+    }
143
+
144
+    /**
145
+     * Generates a new private key
146
+     *
147
+     * @return resource
148
+     */
149
+    public function getOpenSSLPKey() {
150
+        $config = $this->getOpenSSLConfig();
151
+        return openssl_pkey_new($config);
152
+    }
153
+
154
+    /**
155
+     * get openSSL Config
156
+     *
157
+     * @return array
158
+     */
159
+    private function getOpenSSLConfig() {
160
+        $config = ['private_key_bits' => 4096];
161
+        $config = array_merge(
162
+            $config,
163
+            $this->config->getSystemValue('openssl', [])
164
+        );
165
+        return $config;
166
+    }
167
+
168
+    /**
169
+     * @param string $plainContent
170
+     * @param string $passPhrase
171
+     * @param int $version
172
+     * @param int $position
173
+     * @return false|string
174
+     * @throws EncryptionFailedException
175
+     */
176
+    public function symmetricEncryptFileContent($plainContent, $passPhrase, $version, $position) {
177
+
178
+        if (!$plainContent) {
179
+            $this->logger->error('Encryption Library, symmetrical encryption failed no content given',
180
+                ['app' => 'encryption']);
181
+            return false;
182
+        }
183
+
184
+        $iv = $this->generateIv();
185
+
186
+        $encryptedContent = $this->encrypt($plainContent,
187
+            $iv,
188
+            $passPhrase,
189
+            $this->getCipher());
190
+
191
+        // Create a signature based on the key as well as the current version
192
+        $sig = $this->createSignature($encryptedContent, $passPhrase.$version.$position);
193
+
194
+        // combine content to encrypt the IV identifier and actual IV
195
+        $catFile = $this->concatIV($encryptedContent, $iv);
196
+        $catFile = $this->concatSig($catFile, $sig);
197
+        $padded = $this->addPadding($catFile);
198
+
199
+        return $padded;
200
+    }
201
+
202
+    /**
203
+     * generate header for encrypted file
204
+     *
205
+     * @param string $keyFormat (can be 'hash' or 'password')
206
+     * @return string
207
+     * @throws \InvalidArgumentException
208
+     */
209
+    public function generateHeader($keyFormat = 'hash') {
210
+
211
+        if (in_array($keyFormat, $this->supportedKeyFormats, true) === false) {
212
+            throw new \InvalidArgumentException('key format "' . $keyFormat . '" is not supported');
213
+        }
214
+
215
+        $cipher = $this->getCipher();
216
+
217
+        $header = self::HEADER_START
218
+            . ':cipher:' . $cipher
219
+            . ':keyFormat:' . $keyFormat
220
+            . ':' . self::HEADER_END;
221
+
222
+        return $header;
223
+    }
224
+
225
+    /**
226
+     * @param string $plainContent
227
+     * @param string $iv
228
+     * @param string $passPhrase
229
+     * @param string $cipher
230
+     * @return string
231
+     * @throws EncryptionFailedException
232
+     */
233
+    private function encrypt($plainContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) {
234
+        $encryptedContent = openssl_encrypt($plainContent,
235
+            $cipher,
236
+            $passPhrase,
237
+            false,
238
+            $iv);
239
+
240
+        if (!$encryptedContent) {
241
+            $error = 'Encryption (symmetric) of content failed';
242
+            $this->logger->error($error . openssl_error_string(),
243
+                ['app' => 'encryption']);
244
+            throw new EncryptionFailedException($error);
245
+        }
246
+
247
+        return $encryptedContent;
248
+    }
249
+
250
+    /**
251
+     * return Cipher either from config.php or the default cipher defined in
252
+     * this class
253
+     *
254
+     * @return string
255
+     */
256
+    public function getCipher() {
257
+        $cipher = $this->config->getSystemValue('cipher', self::DEFAULT_CIPHER);
258
+        if (!isset($this->supportedCiphersAndKeySize[$cipher])) {
259
+            $this->logger->warning(
260
+                    sprintf(
261
+                            'Unsupported cipher (%s) defined in config.php supported. Falling back to %s',
262
+                            $cipher,
263
+                            self::DEFAULT_CIPHER
264
+                    ),
265
+                ['app' => 'encryption']);
266
+            $cipher = self::DEFAULT_CIPHER;
267
+        }
268
+
269
+        // Workaround for OpenSSL 0.9.8. Fallback to an old cipher that should work.
270
+        if(OPENSSL_VERSION_NUMBER < 0x1000101f) {
271
+            if($cipher === 'AES-256-CTR' || $cipher === 'AES-128-CTR') {
272
+                $cipher = self::LEGACY_CIPHER;
273
+            }
274
+        }
275
+
276
+        return $cipher;
277
+    }
278
+
279
+    /**
280
+     * get key size depending on the cipher
281
+     *
282
+     * @param string $cipher
283
+     * @return int
284
+     * @throws \InvalidArgumentException
285
+     */
286
+    protected function getKeySize($cipher) {
287
+        if(isset($this->supportedCiphersAndKeySize[$cipher])) {
288
+            return $this->supportedCiphersAndKeySize[$cipher];
289
+        }
290
+
291
+        throw new \InvalidArgumentException(
292
+            sprintf(
293
+                    'Unsupported cipher (%s) defined.',
294
+                    $cipher
295
+            )
296
+        );
297
+    }
298
+
299
+    /**
300
+     * get legacy cipher
301
+     *
302
+     * @return string
303
+     */
304
+    public function getLegacyCipher() {
305
+        return self::LEGACY_CIPHER;
306
+    }
307
+
308
+    /**
309
+     * @param string $encryptedContent
310
+     * @param string $iv
311
+     * @return string
312
+     */
313
+    private function concatIV($encryptedContent, $iv) {
314
+        return $encryptedContent . '00iv00' . $iv;
315
+    }
316
+
317
+    /**
318
+     * @param string $encryptedContent
319
+     * @param string $signature
320
+     * @return string
321
+     */
322
+    private function concatSig($encryptedContent, $signature) {
323
+        return $encryptedContent . '00sig00' . $signature;
324
+    }
325
+
326
+    /**
327
+     * Note: This is _NOT_ a padding used for encryption purposes. It is solely
328
+     * used to achieve the PHP stream size. It has _NOTHING_ to do with the
329
+     * encrypted content and is not used in any crypto primitive.
330
+     *
331
+     * @param string $data
332
+     * @return string
333
+     */
334
+    private function addPadding($data) {
335
+        return $data . 'xxx';
336
+    }
337
+
338
+    /**
339
+     * generate password hash used to encrypt the users private key
340
+     *
341
+     * @param string $password
342
+     * @param string $cipher
343
+     * @param string $uid only used for user keys
344
+     * @return string
345
+     */
346
+    protected function generatePasswordHash($password, $cipher, $uid = '') {
347
+        $instanceId = $this->config->getSystemValue('instanceid');
348
+        $instanceSecret = $this->config->getSystemValue('secret');
349
+        $salt = hash('sha256', $uid . $instanceId . $instanceSecret, true);
350
+        $keySize = $this->getKeySize($cipher);
351
+
352
+        $hash = hash_pbkdf2(
353
+            'sha256',
354
+            $password,
355
+            $salt,
356
+            100000,
357
+            $keySize,
358
+            true
359
+        );
360
+
361
+        return $hash;
362
+    }
363
+
364
+    /**
365
+     * encrypt private key
366
+     *
367
+     * @param string $privateKey
368
+     * @param string $password
369
+     * @param string $uid for regular users, empty for system keys
370
+     * @return false|string
371
+     */
372
+    public function encryptPrivateKey($privateKey, $password, $uid = '') {
373
+        $cipher = $this->getCipher();
374
+        $hash = $this->generatePasswordHash($password, $cipher, $uid);
375
+        $encryptedKey = $this->symmetricEncryptFileContent(
376
+            $privateKey,
377
+            $hash,
378
+            0,
379
+            0
380
+        );
381
+
382
+        return $encryptedKey;
383
+    }
384
+
385
+    /**
386
+     * @param string $privateKey
387
+     * @param string $password
388
+     * @param string $uid for regular users, empty for system keys
389
+     * @return false|string
390
+     */
391
+    public function decryptPrivateKey($privateKey, $password = '', $uid = '') {
392
+
393
+        $header = $this->parseHeader($privateKey);
394
+
395
+        if (isset($header['cipher'])) {
396
+            $cipher = $header['cipher'];
397
+        } else {
398
+            $cipher = self::LEGACY_CIPHER;
399
+        }
400
+
401
+        if (isset($header['keyFormat'])) {
402
+            $keyFormat = $header['keyFormat'];
403
+        } else {
404
+            $keyFormat = self::LEGACY_KEY_FORMAT;
405
+        }
406
+
407
+        if ($keyFormat === 'hash') {
408
+            $password = $this->generatePasswordHash($password, $cipher, $uid);
409
+        }
410
+
411
+        // If we found a header we need to remove it from the key we want to decrypt
412
+        if (!empty($header)) {
413
+            $privateKey = substr($privateKey,
414
+                strpos($privateKey,
415
+                    self::HEADER_END) + strlen(self::HEADER_END));
416
+        }
417
+
418
+        $plainKey = $this->symmetricDecryptFileContent(
419
+            $privateKey,
420
+            $password,
421
+            $cipher,
422
+            0
423
+        );
424
+
425
+        if ($this->isValidPrivateKey($plainKey) === false) {
426
+            return false;
427
+        }
428
+
429
+        return $plainKey;
430
+    }
431
+
432
+    /**
433
+     * check if it is a valid private key
434
+     *
435
+     * @param string $plainKey
436
+     * @return bool
437
+     */
438
+    protected function isValidPrivateKey($plainKey) {
439
+        $res = openssl_get_privatekey($plainKey);
440
+        if (is_resource($res)) {
441
+            $sslInfo = openssl_pkey_get_details($res);
442
+            if (isset($sslInfo['key'])) {
443
+                return true;
444
+            }
445
+        }
446
+
447
+        return false;
448
+    }
449
+
450
+    /**
451
+     * @param string $keyFileContents
452
+     * @param string $passPhrase
453
+     * @param string $cipher
454
+     * @param int $version
455
+     * @param int $position
456
+     * @return string
457
+     * @throws DecryptionFailedException
458
+     */
459
+    public function symmetricDecryptFileContent($keyFileContents, $passPhrase, $cipher = self::DEFAULT_CIPHER, $version = 0, $position = 0) {
460
+        $catFile = $this->splitMetaData($keyFileContents, $cipher);
461
+
462
+        if ($catFile['signature'] !== false) {
463
+            $this->checkSignature($catFile['encrypted'], $passPhrase.$version.$position, $catFile['signature']);
464
+        }
465
+
466
+        return $this->decrypt($catFile['encrypted'],
467
+            $catFile['iv'],
468
+            $passPhrase,
469
+            $cipher);
470
+    }
471
+
472
+    /**
473
+     * check for valid signature
474
+     *
475
+     * @param string $data
476
+     * @param string $passPhrase
477
+     * @param string $expectedSignature
478
+     * @throws GenericEncryptionException
479
+     */
480
+    private function checkSignature($data, $passPhrase, $expectedSignature) {
481
+        $signature = $this->createSignature($data, $passPhrase);
482
+        if (!hash_equals($expectedSignature, $signature)) {
483
+            throw new GenericEncryptionException('Bad Signature', $this->l->t('Bad Signature'));
484
+        }
485
+    }
486
+
487
+    /**
488
+     * create signature
489
+     *
490
+     * @param string $data
491
+     * @param string $passPhrase
492
+     * @return string
493
+     */
494
+    private function createSignature($data, $passPhrase) {
495
+        $passPhrase = hash('sha512', $passPhrase . 'a', true);
496
+        $signature = hash_hmac('sha256', $data, $passPhrase);
497
+        return $signature;
498
+    }
499
+
500
+
501
+    /**
502
+     * remove padding
503
+     *
504
+     * @param string $padded
505
+     * @param bool $hasSignature did the block contain a signature, in this case we use a different padding
506
+     * @return string|false
507
+     */
508
+    private function removePadding($padded, $hasSignature = false) {
509
+        if ($hasSignature === false && substr($padded, -2) === 'xx') {
510
+            return substr($padded, 0, -2);
511
+        } elseif ($hasSignature === true && substr($padded, -3) === 'xxx') {
512
+            return substr($padded, 0, -3);
513
+        }
514
+        return false;
515
+    }
516
+
517
+    /**
518
+     * split meta data from encrypted file
519
+     * Note: for now, we assume that the meta data always start with the iv
520
+     *       followed by the signature, if available
521
+     *
522
+     * @param string $catFile
523
+     * @param string $cipher
524
+     * @return array
525
+     */
526
+    private function splitMetaData($catFile, $cipher) {
527
+        if ($this->hasSignature($catFile, $cipher)) {
528
+            $catFile = $this->removePadding($catFile, true);
529
+            $meta = substr($catFile, -93);
530
+            $iv = substr($meta, strlen('00iv00'), 16);
531
+            $sig = substr($meta, 22 + strlen('00sig00'));
532
+            $encrypted = substr($catFile, 0, -93);
533
+        } else {
534
+            $catFile = $this->removePadding($catFile);
535
+            $meta = substr($catFile, -22);
536
+            $iv = substr($meta, -16);
537
+            $sig = false;
538
+            $encrypted = substr($catFile, 0, -22);
539
+        }
540
+
541
+        return [
542
+            'encrypted' => $encrypted,
543
+            'iv' => $iv,
544
+            'signature' => $sig
545
+        ];
546
+    }
547
+
548
+    /**
549
+     * check if encrypted block is signed
550
+     *
551
+     * @param string $catFile
552
+     * @param string $cipher
553
+     * @return bool
554
+     * @throws GenericEncryptionException
555
+     */
556
+    private function hasSignature($catFile, $cipher) {
557
+        $meta = substr($catFile, -93);
558
+        $signaturePosition = strpos($meta, '00sig00');
559
+
560
+        // enforce signature for the new 'CTR' ciphers
561
+        if ($signaturePosition === false && strpos(strtolower($cipher), 'ctr') !== false) {
562
+            throw new GenericEncryptionException('Missing Signature', $this->l->t('Missing Signature'));
563
+        }
564
+
565
+        return ($signaturePosition !== false);
566
+    }
567
+
568
+
569
+    /**
570
+     * @param string $encryptedContent
571
+     * @param string $iv
572
+     * @param string $passPhrase
573
+     * @param string $cipher
574
+     * @return string
575
+     * @throws DecryptionFailedException
576
+     */
577
+    private function decrypt($encryptedContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) {
578
+        $plainContent = openssl_decrypt($encryptedContent,
579
+            $cipher,
580
+            $passPhrase,
581
+            false,
582
+            $iv);
583
+
584
+        if ($plainContent) {
585
+            return $plainContent;
586
+        } else {
587
+            throw new DecryptionFailedException('Encryption library: Decryption (symmetric) of content failed: ' . openssl_error_string());
588
+        }
589
+    }
590
+
591
+    /**
592
+     * @param string $data
593
+     * @return array
594
+     */
595
+    protected function parseHeader($data) {
596
+        $result = [];
597
+
598
+        if (substr($data, 0, strlen(self::HEADER_START)) === self::HEADER_START) {
599
+            $endAt = strpos($data, self::HEADER_END);
600
+            $header = substr($data, 0, $endAt + strlen(self::HEADER_END));
601
+
602
+            // +1 not to start with an ':' which would result in empty element at the beginning
603
+            $exploded = explode(':',
604
+                substr($header, strlen(self::HEADER_START) + 1));
605
+
606
+            $element = array_shift($exploded);
607
+
608
+            while ($element != self::HEADER_END) {
609
+                $result[$element] = array_shift($exploded);
610
+                $element = array_shift($exploded);
611
+            }
612
+        }
613
+
614
+        return $result;
615
+    }
616
+
617
+    /**
618
+     * generate initialization vector
619
+     *
620
+     * @return string
621
+     * @throws GenericEncryptionException
622
+     */
623
+    private function generateIv() {
624
+        return random_bytes(16);
625
+    }
626
+
627
+    /**
628
+     * Generate a cryptographically secure pseudo-random 256-bit ASCII key, used
629
+     * as file key
630
+     *
631
+     * @return string
632
+     * @throws \Exception
633
+     */
634
+    public function generateFileKey() {
635
+        return random_bytes(32);
636
+    }
637
+
638
+    /**
639
+     * @param $encKeyFile
640
+     * @param $shareKey
641
+     * @param $privateKey
642
+     * @return string
643
+     * @throws MultiKeyDecryptException
644
+     */
645
+    public function multiKeyDecrypt($encKeyFile, $shareKey, $privateKey) {
646
+        if (!$encKeyFile) {
647
+            throw new MultiKeyDecryptException('Cannot multikey decrypt empty plain content');
648
+        }
649
+
650
+        if (openssl_open($encKeyFile, $plainContent, $shareKey, $privateKey)) {
651
+            return $plainContent;
652
+        } else {
653
+            throw new MultiKeyDecryptException('multikeydecrypt with share key failed:' . openssl_error_string());
654
+        }
655
+    }
656
+
657
+    /**
658
+     * @param string $plainContent
659
+     * @param array $keyFiles
660
+     * @return array
661
+     * @throws MultiKeyEncryptException
662
+     */
663
+    public function multiKeyEncrypt($plainContent, array $keyFiles) {
664
+        // openssl_seal returns false without errors if plaincontent is empty
665
+        // so trigger our own error
666
+        if (empty($plainContent)) {
667
+            throw new MultiKeyEncryptException('Cannot multikeyencrypt empty plain content');
668
+        }
669
+
670
+        // Set empty vars to be set by openssl by reference
671
+        $sealed = '';
672
+        $shareKeys = [];
673
+        $mappedShareKeys = [];
674
+
675
+        if (openssl_seal($plainContent, $sealed, $shareKeys, $keyFiles)) {
676
+            $i = 0;
677
+
678
+            // Ensure each shareKey is labelled with its corresponding key id
679
+            foreach ($keyFiles as $userId => $publicKey) {
680
+                $mappedShareKeys[$userId] = $shareKeys[$i];
681
+                $i++;
682
+            }
683
+
684
+            return [
685
+                'keys' => $mappedShareKeys,
686
+                'data' => $sealed
687
+            ];
688
+        } else {
689
+            throw new MultiKeyEncryptException('multikeyencryption failed ' . openssl_error_string());
690
+        }
691
+    }
692 692
 }
693 693
 
Please login to merge, or discard this patch.