Completed
Pull Request — master (#3829)
by Maxence
12:57
created
apps/encryption/lib/Hooks/Contracts/IHook.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -24,10 +24,10 @@
 block discarded – undo
24 24
 
25 25
 
26 26
 interface IHook {
27
-	/**
28
-	 * Connects Hooks
29
-	 *
30
-	 * @return null
31
-	 */
32
-	public function addHooks();
27
+    /**
28
+     * Connects Hooks
29
+     *
30
+     * @return null
31
+     */
32
+    public function addHooks();
33 33
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Settings/Admin.php 1 patch
Indentation   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -38,90 +38,90 @@
 block discarded – undo
38 38
 
39 39
 class Admin implements ISettings {
40 40
 
41
-	/** @var IL10N */
42
-	private $l;
43
-
44
-	/** @var ILogger */
45
-	private $logger;
46
-
47
-	/** @var IUserSession */
48
-	private $userSession;
49
-
50
-	/** @var IConfig */
51
-	private $config;
52
-
53
-	/** @var IUserManager */
54
-	private $userManager;
55
-
56
-	/** @var ISession */
57
-	private $session;
58
-
59
-	public function __construct(
60
-		IL10N $l,
61
-		ILogger $logger,
62
-		IUserSession $userSession,
63
-		IConfig $config,
64
-		IUserManager $userManager,
65
-		ISession $session
66
-	) {
67
-		$this->l = $l;
68
-		$this->logger = $logger;
69
-		$this->userSession = $userSession;
70
-		$this->config = $config;
71
-		$this->userManager = $userManager;
72
-		$this->session = $session;
73
-	}
74
-
75
-	/**
76
-	 * @return TemplateResponse
77
-	 */
78
-	public function getForm() {
79
-		$crypt = new Crypt(
80
-			$this->logger,
81
-			$this->userSession,
82
-			$this->config,
83
-			$this->l);
84
-
85
-		$util = new Util(
86
-			new View(),
87
-			$crypt,
88
-			$this->logger,
89
-			$this->userSession,
90
-			$this->config,
91
-			$this->userManager);
92
-
93
-		// Check if an adminRecovery account is enabled for recovering files after lost pwd
94
-		$recoveryAdminEnabled = $this->config->getAppValue('encryption', 'recoveryAdminEnabled', '0');
95
-		$session = new Session($this->session);
96
-
97
-		$encryptHomeStorage = $util->shouldEncryptHomeStorage();
98
-
99
-		$parameters = [
100
-			'recoveryEnabled'    => $recoveryAdminEnabled,
101
-			'initStatus'         => $session->getStatus(),
102
-			'encryptHomeStorage' => $encryptHomeStorage,
103
-			'masterKeyEnabled'   => $util->isMasterKeyEnabled(),
104
-		];
105
-
106
-		return new TemplateResponse('encryption', 'settings-admin', $parameters, '');
107
-	}
108
-
109
-	/**
110
-	 * @return string the section ID, e.g. 'sharing'
111
-	 */
112
-	public function getSection() {
113
-		return 'encryption';
114
-	}
115
-
116
-	/**
117
-	 * @return int whether the form should be rather on the top or bottom of
118
-	 * the admin section. The forms are arranged in ascending order of the
119
-	 * priority values. It is required to return a value between 0 and 100.
120
-	 *
121
-	 * E.g.: 70
122
-	 */
123
-	public function getPriority() {
124
-		return 5;
125
-	}
41
+    /** @var IL10N */
42
+    private $l;
43
+
44
+    /** @var ILogger */
45
+    private $logger;
46
+
47
+    /** @var IUserSession */
48
+    private $userSession;
49
+
50
+    /** @var IConfig */
51
+    private $config;
52
+
53
+    /** @var IUserManager */
54
+    private $userManager;
55
+
56
+    /** @var ISession */
57
+    private $session;
58
+
59
+    public function __construct(
60
+        IL10N $l,
61
+        ILogger $logger,
62
+        IUserSession $userSession,
63
+        IConfig $config,
64
+        IUserManager $userManager,
65
+        ISession $session
66
+    ) {
67
+        $this->l = $l;
68
+        $this->logger = $logger;
69
+        $this->userSession = $userSession;
70
+        $this->config = $config;
71
+        $this->userManager = $userManager;
72
+        $this->session = $session;
73
+    }
74
+
75
+    /**
76
+     * @return TemplateResponse
77
+     */
78
+    public function getForm() {
79
+        $crypt = new Crypt(
80
+            $this->logger,
81
+            $this->userSession,
82
+            $this->config,
83
+            $this->l);
84
+
85
+        $util = new Util(
86
+            new View(),
87
+            $crypt,
88
+            $this->logger,
89
+            $this->userSession,
90
+            $this->config,
91
+            $this->userManager);
92
+
93
+        // Check if an adminRecovery account is enabled for recovering files after lost pwd
94
+        $recoveryAdminEnabled = $this->config->getAppValue('encryption', 'recoveryAdminEnabled', '0');
95
+        $session = new Session($this->session);
96
+
97
+        $encryptHomeStorage = $util->shouldEncryptHomeStorage();
98
+
99
+        $parameters = [
100
+            'recoveryEnabled'    => $recoveryAdminEnabled,
101
+            'initStatus'         => $session->getStatus(),
102
+            'encryptHomeStorage' => $encryptHomeStorage,
103
+            'masterKeyEnabled'   => $util->isMasterKeyEnabled(),
104
+        ];
105
+
106
+        return new TemplateResponse('encryption', 'settings-admin', $parameters, '');
107
+    }
108
+
109
+    /**
110
+     * @return string the section ID, e.g. 'sharing'
111
+     */
112
+    public function getSection() {
113
+        return 'encryption';
114
+    }
115
+
116
+    /**
117
+     * @return int whether the form should be rather on the top or bottom of
118
+     * the admin section. The forms are arranged in ascending order of the
119
+     * priority values. It is required to return a value between 0 and 100.
120
+     *
121
+     * E.g.: 70
122
+     */
123
+    public function getPriority() {
124
+        return 5;
125
+    }
126 126
 
127 127
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Session.php 1 patch
Indentation   +154 added lines, -154 removed lines patch added patch discarded remove patch
@@ -29,159 +29,159 @@
 block discarded – undo
29 29
 
30 30
 class Session {
31 31
 
32
-	/** @var ISession */
33
-	protected $session;
34
-
35
-	const NOT_INITIALIZED = '0';
36
-	const INIT_EXECUTED = '1';
37
-	const INIT_SUCCESSFUL = '2';
38
-	const RUN_MIGRATION = '3';
39
-
40
-	/**
41
-	 * @param ISession $session
42
-	 */
43
-	public function __construct(ISession $session) {
44
-		$this->session = $session;
45
-	}
46
-
47
-	/**
48
-	 * Sets status of encryption app
49
-	 *
50
-	 * @param string $status INIT_SUCCESSFUL, INIT_EXECUTED, NOT_INITIALIZED
51
-	 */
52
-	public function setStatus($status) {
53
-		$this->session->set('encryptionInitialized', $status);
54
-	}
55
-
56
-	/**
57
-	 * Gets status if we already tried to initialize the encryption app
58
-	 *
59
-	 * @return string init status INIT_SUCCESSFUL, INIT_EXECUTED, NOT_INITIALIZED
60
-	 */
61
-	public function getStatus() {
62
-		$status = $this->session->get('encryptionInitialized');
63
-		if (is_null($status)) {
64
-			$status = self::NOT_INITIALIZED;
65
-		}
66
-
67
-		return $status;
68
-	}
69
-
70
-	/**
71
-	 * check if encryption was initialized successfully
72
-	 *
73
-	 * @return bool
74
-	 */
75
-	public function isReady() {
76
-		$status = $this->getStatus();
77
-		return $status === self::INIT_SUCCESSFUL;
78
-	}
79
-
80
-	/**
81
-	 * Gets user or public share private key from session
82
-	 *
83
-	 * @return string $privateKey The user's plaintext private key
84
-	 * @throws Exceptions\PrivateKeyMissingException
85
-	 */
86
-	public function getPrivateKey() {
87
-		$key = $this->session->get('privateKey');
88
-		if (is_null($key)) {
89
-			throw new Exceptions\PrivateKeyMissingException('please try to log-out and log-in again', 0);
90
-		}
91
-		return $key;
92
-	}
93
-
94
-	/**
95
-	 * check if private key is set
96
-	 *
97
-	 * @return boolean
98
-	 */
99
-	public function isPrivateKeySet() {
100
-		$key = $this->session->get('privateKey');
101
-		if (is_null($key)) {
102
-			return false;
103
-		}
104
-
105
-		return true;
106
-	}
107
-
108
-	/**
109
-	 * Sets user private key to session
110
-	 *
111
-	 * @param string $key users private key
112
-	 *
113
-	 * @note this should only be set on login
114
-	 */
115
-	public function setPrivateKey($key) {
116
-		$this->session->set('privateKey', $key);
117
-	}
118
-
119
-	/**
120
-	 * store data needed for the decrypt all operation in the session
121
-	 *
122
-	 * @param string $user
123
-	 * @param string $key
124
-	 */
125
-	public function prepareDecryptAll($user, $key) {
126
-		$this->session->set('decryptAll', true);
127
-		$this->session->set('decryptAllKey', $key);
128
-		$this->session->set('decryptAllUid', $user);
129
-	}
130
-
131
-	/**
132
-	 * check if we are in decrypt all mode
133
-	 *
134
-	 * @return bool
135
-	 */
136
-	public function decryptAllModeActivated() {
137
-		$decryptAll = $this->session->get('decryptAll');
138
-		return ($decryptAll === true);
139
-	}
140
-
141
-	/**
142
-	 * get uid used for decrypt all operation
143
-	 *
144
-	 * @return string
145
-	 * @throws \Exception
146
-	 */
147
-	public function getDecryptAllUid() {
148
-		$uid = $this->session->get('decryptAllUid');
149
-		if (is_null($uid) && $this->decryptAllModeActivated()) {
150
-			throw new \Exception('No uid found while in decrypt all mode');
151
-		} elseif (is_null($uid)) {
152
-			throw new \Exception('Please activate decrypt all mode first');
153
-		}
154
-
155
-		return $uid;
156
-	}
157
-
158
-	/**
159
-	 * get private key for decrypt all operation
160
-	 *
161
-	 * @return string
162
-	 * @throws PrivateKeyMissingException
163
-	 */
164
-	public function getDecryptAllKey() {
165
-		$privateKey = $this->session->get('decryptAllKey');
166
-		if (is_null($privateKey) && $this->decryptAllModeActivated()) {
167
-			throw new PrivateKeyMissingException('No private key found while in decrypt all mode');
168
-		} elseif (is_null($privateKey)) {
169
-			throw new PrivateKeyMissingException('Please activate decrypt all mode first');
170
-		}
171
-
172
-		return $privateKey;
173
-	}
174
-
175
-	/**
176
-	 * remove keys from session
177
-	 */
178
-	public function clear() {
179
-		$this->session->remove('publicSharePrivateKey');
180
-		$this->session->remove('privateKey');
181
-		$this->session->remove('encryptionInitialized');
182
-		$this->session->remove('decryptAll');
183
-		$this->session->remove('decryptAllKey');
184
-		$this->session->remove('decryptAllUid');
185
-	}
32
+    /** @var ISession */
33
+    protected $session;
34
+
35
+    const NOT_INITIALIZED = '0';
36
+    const INIT_EXECUTED = '1';
37
+    const INIT_SUCCESSFUL = '2';
38
+    const RUN_MIGRATION = '3';
39
+
40
+    /**
41
+     * @param ISession $session
42
+     */
43
+    public function __construct(ISession $session) {
44
+        $this->session = $session;
45
+    }
46
+
47
+    /**
48
+     * Sets status of encryption app
49
+     *
50
+     * @param string $status INIT_SUCCESSFUL, INIT_EXECUTED, NOT_INITIALIZED
51
+     */
52
+    public function setStatus($status) {
53
+        $this->session->set('encryptionInitialized', $status);
54
+    }
55
+
56
+    /**
57
+     * Gets status if we already tried to initialize the encryption app
58
+     *
59
+     * @return string init status INIT_SUCCESSFUL, INIT_EXECUTED, NOT_INITIALIZED
60
+     */
61
+    public function getStatus() {
62
+        $status = $this->session->get('encryptionInitialized');
63
+        if (is_null($status)) {
64
+            $status = self::NOT_INITIALIZED;
65
+        }
66
+
67
+        return $status;
68
+    }
69
+
70
+    /**
71
+     * check if encryption was initialized successfully
72
+     *
73
+     * @return bool
74
+     */
75
+    public function isReady() {
76
+        $status = $this->getStatus();
77
+        return $status === self::INIT_SUCCESSFUL;
78
+    }
79
+
80
+    /**
81
+     * Gets user or public share private key from session
82
+     *
83
+     * @return string $privateKey The user's plaintext private key
84
+     * @throws Exceptions\PrivateKeyMissingException
85
+     */
86
+    public function getPrivateKey() {
87
+        $key = $this->session->get('privateKey');
88
+        if (is_null($key)) {
89
+            throw new Exceptions\PrivateKeyMissingException('please try to log-out and log-in again', 0);
90
+        }
91
+        return $key;
92
+    }
93
+
94
+    /**
95
+     * check if private key is set
96
+     *
97
+     * @return boolean
98
+     */
99
+    public function isPrivateKeySet() {
100
+        $key = $this->session->get('privateKey');
101
+        if (is_null($key)) {
102
+            return false;
103
+        }
104
+
105
+        return true;
106
+    }
107
+
108
+    /**
109
+     * Sets user private key to session
110
+     *
111
+     * @param string $key users private key
112
+     *
113
+     * @note this should only be set on login
114
+     */
115
+    public function setPrivateKey($key) {
116
+        $this->session->set('privateKey', $key);
117
+    }
118
+
119
+    /**
120
+     * store data needed for the decrypt all operation in the session
121
+     *
122
+     * @param string $user
123
+     * @param string $key
124
+     */
125
+    public function prepareDecryptAll($user, $key) {
126
+        $this->session->set('decryptAll', true);
127
+        $this->session->set('decryptAllKey', $key);
128
+        $this->session->set('decryptAllUid', $user);
129
+    }
130
+
131
+    /**
132
+     * check if we are in decrypt all mode
133
+     *
134
+     * @return bool
135
+     */
136
+    public function decryptAllModeActivated() {
137
+        $decryptAll = $this->session->get('decryptAll');
138
+        return ($decryptAll === true);
139
+    }
140
+
141
+    /**
142
+     * get uid used for decrypt all operation
143
+     *
144
+     * @return string
145
+     * @throws \Exception
146
+     */
147
+    public function getDecryptAllUid() {
148
+        $uid = $this->session->get('decryptAllUid');
149
+        if (is_null($uid) && $this->decryptAllModeActivated()) {
150
+            throw new \Exception('No uid found while in decrypt all mode');
151
+        } elseif (is_null($uid)) {
152
+            throw new \Exception('Please activate decrypt all mode first');
153
+        }
154
+
155
+        return $uid;
156
+    }
157
+
158
+    /**
159
+     * get private key for decrypt all operation
160
+     *
161
+     * @return string
162
+     * @throws PrivateKeyMissingException
163
+     */
164
+    public function getDecryptAllKey() {
165
+        $privateKey = $this->session->get('decryptAllKey');
166
+        if (is_null($privateKey) && $this->decryptAllModeActivated()) {
167
+            throw new PrivateKeyMissingException('No private key found while in decrypt all mode');
168
+        } elseif (is_null($privateKey)) {
169
+            throw new PrivateKeyMissingException('Please activate decrypt all mode first');
170
+        }
171
+
172
+        return $privateKey;
173
+    }
174
+
175
+    /**
176
+     * remove keys from session
177
+     */
178
+    public function clear() {
179
+        $this->session->remove('publicSharePrivateKey');
180
+        $this->session->remove('privateKey');
181
+        $this->session->remove('encryptionInitialized');
182
+        $this->session->remove('decryptAll');
183
+        $this->session->remove('decryptAllKey');
184
+        $this->session->remove('decryptAllUid');
185
+    }
186 186
 
187 187
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Crypto/Encryption.php 1 patch
Indentation   +526 added lines, -526 removed lines patch added patch discarded remove patch
@@ -43,530 +43,530 @@
 block discarded – undo
43 43
 
44 44
 class Encryption implements IEncryptionModule {
45 45
 
46
-	const ID = 'OC_DEFAULT_MODULE';
47
-	const DISPLAY_NAME = 'Default encryption module';
48
-
49
-	/**
50
-	 * @var Crypt
51
-	 */
52
-	private $crypt;
53
-
54
-	/** @var string */
55
-	private $cipher;
56
-
57
-	/** @var string */
58
-	private $path;
59
-
60
-	/** @var string */
61
-	private $user;
62
-
63
-	/** @var string */
64
-	private $fileKey;
65
-
66
-	/** @var string */
67
-	private $writeCache;
68
-
69
-	/** @var KeyManager */
70
-	private $keyManager;
71
-
72
-	/** @var array */
73
-	private $accessList;
74
-
75
-	/** @var boolean */
76
-	private $isWriteOperation;
77
-
78
-	/** @var Util */
79
-	private $util;
80
-
81
-	/** @var  Session */
82
-	private $session;
83
-
84
-	/** @var  ILogger */
85
-	private $logger;
86
-
87
-	/** @var IL10N */
88
-	private $l;
89
-
90
-	/** @var EncryptAll */
91
-	private $encryptAll;
92
-
93
-	/** @var  bool */
94
-	private $useMasterPassword;
95
-
96
-	/** @var DecryptAll  */
97
-	private $decryptAll;
98
-
99
-	/** @var int unencrypted block size if block contains signature */
100
-	private $unencryptedBlockSizeSigned = 6072;
101
-
102
-	/** @var int unencrypted block size */
103
-	private $unencryptedBlockSize = 6126;
104
-
105
-	/** @var int Current version of the file */
106
-	private $version = 0;
107
-
108
-	/** @var array remember encryption signature version */
109
-	private static $rememberVersion = [];
110
-
111
-
112
-	/**
113
-	 *
114
-	 * @param Crypt $crypt
115
-	 * @param KeyManager $keyManager
116
-	 * @param Util $util
117
-	 * @param Session $session
118
-	 * @param EncryptAll $encryptAll
119
-	 * @param DecryptAll $decryptAll
120
-	 * @param ILogger $logger
121
-	 * @param IL10N $il10n
122
-	 */
123
-	public function __construct(Crypt $crypt,
124
-								KeyManager $keyManager,
125
-								Util $util,
126
-								Session $session,
127
-								EncryptAll $encryptAll,
128
-								DecryptAll $decryptAll,
129
-								ILogger $logger,
130
-								IL10N $il10n) {
131
-		$this->crypt = $crypt;
132
-		$this->keyManager = $keyManager;
133
-		$this->util = $util;
134
-		$this->session = $session;
135
-		$this->encryptAll = $encryptAll;
136
-		$this->decryptAll = $decryptAll;
137
-		$this->logger = $logger;
138
-		$this->l = $il10n;
139
-		$this->useMasterPassword = $util->isMasterKeyEnabled();
140
-	}
141
-
142
-	/**
143
-	 * @return string defining the technical unique id
144
-	 */
145
-	public function getId() {
146
-		return self::ID;
147
-	}
148
-
149
-	/**
150
-	 * In comparison to getKey() this function returns a human readable (maybe translated) name
151
-	 *
152
-	 * @return string
153
-	 */
154
-	public function getDisplayName() {
155
-		return self::DISPLAY_NAME;
156
-	}
157
-
158
-	/**
159
-	 * start receiving chunks from a file. This is the place where you can
160
-	 * perform some initial step before starting encrypting/decrypting the
161
-	 * chunks
162
-	 *
163
-	 * @param string $path to the file
164
-	 * @param string $user who read/write the file
165
-	 * @param string $mode php stream open mode
166
-	 * @param array $header contains the header data read from the file
167
-	 * @param array $accessList who has access to the file contains the key 'users' and 'public'
168
-	 *
169
-	 * @return array $header contain data as key-value pairs which should be
170
-	 *                       written to the header, in case of a write operation
171
-	 *                       or if no additional data is needed return a empty array
172
-	 */
173
-	public function begin($path, $user, $mode, array $header, array $accessList) {
174
-		$this->path = $this->getPathToRealFile($path);
175
-		$this->accessList = $accessList;
176
-		$this->user = $user;
177
-		$this->isWriteOperation = false;
178
-		$this->writeCache = '';
179
-
180
-		if($this->session->isReady() === false) {
181
-			// if the master key is enabled we can initialize encryption
182
-			// with a empty password and user name
183
-			if ($this->util->isMasterKeyEnabled()) {
184
-				$this->keyManager->init('', '');
185
-			}
186
-		}
187
-
188
-		if ($this->session->decryptAllModeActivated()) {
189
-			$encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
190
-			$shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
191
-			$this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
192
-				$shareKey,
193
-				$this->session->getDecryptAllKey());
194
-		} else {
195
-			$this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
196
-		}
197
-
198
-		// always use the version from the original file, also part files
199
-		// need to have a correct version number if they get moved over to the
200
-		// final location
201
-		$this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
202
-
203
-		if (
204
-			$mode === 'w'
205
-			|| $mode === 'w+'
206
-			|| $mode === 'wb'
207
-			|| $mode === 'wb+'
208
-		) {
209
-			$this->isWriteOperation = true;
210
-			if (empty($this->fileKey)) {
211
-				$this->fileKey = $this->crypt->generateFileKey();
212
-			}
213
-		} else {
214
-			// if we read a part file we need to increase the version by 1
215
-			// because the version number was also increased by writing
216
-			// the part file
217
-			if(Scanner::isPartialFile($path)) {
218
-				$this->version = $this->version + 1;
219
-			}
220
-		}
221
-
222
-		if ($this->isWriteOperation) {
223
-			$this->cipher = $this->crypt->getCipher();
224
-		} elseif (isset($header['cipher'])) {
225
-			$this->cipher = $header['cipher'];
226
-		} else {
227
-			// if we read a file without a header we fall-back to the legacy cipher
228
-			// which was used in <=oC6
229
-			$this->cipher = $this->crypt->getLegacyCipher();
230
-		}
231
-
232
-		return array('cipher' => $this->cipher, 'signed' => 'true');
233
-	}
234
-
235
-	/**
236
-	 * last chunk received. This is the place where you can perform some final
237
-	 * operation and return some remaining data if something is left in your
238
-	 * buffer.
239
-	 *
240
-	 * @param string $path to the file
241
-	 * @param int $position
242
-	 * @return string remained data which should be written to the file in case
243
-	 *                of a write operation
244
-	 * @throws PublicKeyMissingException
245
-	 * @throws \Exception
246
-	 * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
247
-	 */
248
-	public function end($path, $position = 0) {
249
-		$result = '';
250
-		if ($this->isWriteOperation) {
251
-			$this->keyManager->setVersion($path, $this->version + 1, new View());
252
-			// in case of a part file we remember the new signature versions
253
-			// the version will be set later on update.
254
-			// This way we make sure that other apps listening to the pre-hooks
255
-			// still get the old version which should be the correct value for them
256
-			if (Scanner::isPartialFile($path)) {
257
-				self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
258
-			}
259
-			if (!empty($this->writeCache)) {
260
-				$result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
261
-				$this->writeCache = '';
262
-			}
263
-			$publicKeys = array();
264
-			if ($this->useMasterPassword === true) {
265
-				$publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
266
-			} else {
267
-				foreach ($this->accessList['users'] as $uid) {
268
-					try {
269
-						$publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
270
-					} catch (PublicKeyMissingException $e) {
271
-						$this->logger->warning(
272
-							'no public key found for user "{uid}", user will not be able to read the file',
273
-							['app' => 'encryption', 'uid' => $uid]
274
-						);
275
-						// if the public key of the owner is missing we should fail
276
-						if ($uid === $this->user) {
277
-							throw $e;
278
-						}
279
-					}
280
-				}
281
-			}
282
-
283
-			$publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->user);
284
-			$encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
285
-			$this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
286
-		}
287
-		return $result;
288
-	}
289
-
290
-	/**
291
-	 * encrypt data
292
-	 *
293
-	 * @param string $data you want to encrypt
294
-	 * @param int $position
295
-	 * @return string encrypted data
296
-	 */
297
-	public function encrypt($data, $position = 0) {
298
-		// If extra data is left over from the last round, make sure it
299
-		// is integrated into the next block
300
-		if ($this->writeCache) {
301
-
302
-			// Concat writeCache to start of $data
303
-			$data = $this->writeCache . $data;
304
-
305
-			// Clear the write cache, ready for reuse - it has been
306
-			// flushed and its old contents processed
307
-			$this->writeCache = '';
308
-
309
-		}
310
-
311
-		$encrypted = '';
312
-		// While there still remains some data to be processed & written
313
-		while (strlen($data) > 0) {
314
-
315
-			// Remaining length for this iteration, not of the
316
-			// entire file (may be greater than 8192 bytes)
317
-			$remainingLength = strlen($data);
318
-
319
-			// If data remaining to be written is less than the
320
-			// size of 1 6126 byte block
321
-			if ($remainingLength < $this->unencryptedBlockSizeSigned) {
322
-
323
-				// Set writeCache to contents of $data
324
-				// The writeCache will be carried over to the
325
-				// next write round, and added to the start of
326
-				// $data to ensure that written blocks are
327
-				// always the correct length. If there is still
328
-				// data in writeCache after the writing round
329
-				// has finished, then the data will be written
330
-				// to disk by $this->flush().
331
-				$this->writeCache = $data;
332
-
333
-				// Clear $data ready for next round
334
-				$data = '';
335
-
336
-			} else {
337
-
338
-				// Read the chunk from the start of $data
339
-				$chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
340
-
341
-				$encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
342
-
343
-				// Remove the chunk we just processed from
344
-				// $data, leaving only unprocessed data in $data
345
-				// var, for handling on the next round
346
-				$data = substr($data, $this->unencryptedBlockSizeSigned);
347
-
348
-			}
349
-
350
-		}
351
-
352
-		return $encrypted;
353
-	}
354
-
355
-	/**
356
-	 * decrypt data
357
-	 *
358
-	 * @param string $data you want to decrypt
359
-	 * @param int $position
360
-	 * @return string decrypted data
361
-	 * @throws DecryptionFailedException
362
-	 */
363
-	public function decrypt($data, $position = 0) {
364
-		if (empty($this->fileKey)) {
365
-			$msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
366
-			$hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
367
-			$this->logger->error($msg);
368
-
369
-			throw new DecryptionFailedException($msg, $hint);
370
-		}
371
-
372
-		return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
373
-	}
374
-
375
-	/**
376
-	 * update encrypted file, e.g. give additional users access to the file
377
-	 *
378
-	 * @param string $path path to the file which should be updated
379
-	 * @param string $uid of the user who performs the operation
380
-	 * @param array $accessList who has access to the file contains the key 'users' and 'public'
381
-	 * @return boolean
382
-	 */
383
-	public function update($path, $uid, array $accessList) {
384
-
385
-		if (empty($accessList)) {
386
-			if (isset(self::$rememberVersion[$path])) {
387
-				$this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
388
-				unset(self::$rememberVersion[$path]);
389
-			}
390
-			return;
391
-		}
392
-
393
-		$fileKey = $this->keyManager->getFileKey($path, $uid);
394
-
395
-		if (!empty($fileKey)) {
396
-
397
-			$publicKeys = array();
398
-			if ($this->useMasterPassword === true) {
399
-				$publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
400
-			} else {
401
-				foreach ($accessList['users'] as $user) {
402
-					try {
403
-						$publicKeys[$user] = $this->keyManager->getPublicKey($user);
404
-					} catch (PublicKeyMissingException $e) {
405
-						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
406
-					}
407
-				}
408
-			}
409
-
410
-			$publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid);
411
-
412
-			$encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
413
-
414
-			$this->keyManager->deleteAllFileKeys($path);
415
-
416
-			$this->keyManager->setAllFileKeys($path, $encryptedFileKey);
417
-
418
-		} else {
419
-			$this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
420
-				array('file' => $path, 'app' => 'encryption'));
421
-
422
-			return false;
423
-		}
424
-
425
-		return true;
426
-	}
427
-
428
-	/**
429
-	 * should the file be encrypted or not
430
-	 *
431
-	 * @param string $path
432
-	 * @return boolean
433
-	 */
434
-	public function shouldEncrypt($path) {
435
-		if ($this->util->shouldEncryptHomeStorage() === false) {
436
-			$storage = $this->util->getStorage($path);
437
-			if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
438
-				return false;
439
-			}
440
-		}
441
-		$parts = explode('/', $path);
442
-		if (count($parts) < 4) {
443
-			return false;
444
-		}
445
-
446
-		if ($parts[2] == 'files') {
447
-			return true;
448
-		}
449
-		if ($parts[2] == 'files_versions') {
450
-			return true;
451
-		}
452
-		if ($parts[2] == 'files_trashbin') {
453
-			return true;
454
-		}
455
-
456
-		return false;
457
-	}
458
-
459
-	/**
460
-	 * get size of the unencrypted payload per block.
461
-	 * ownCloud read/write files with a block size of 8192 byte
462
-	 *
463
-	 * @param bool $signed
464
-	 * @return int
465
-	 */
466
-	public function getUnencryptedBlockSize($signed = false) {
467
-		if ($signed === false) {
468
-			return $this->unencryptedBlockSize;
469
-		}
470
-
471
-		return $this->unencryptedBlockSizeSigned;
472
-	}
473
-
474
-	/**
475
-	 * check if the encryption module is able to read the file,
476
-	 * e.g. if all encryption keys exists
477
-	 *
478
-	 * @param string $path
479
-	 * @param string $uid user for whom we want to check if he can read the file
480
-	 * @return bool
481
-	 * @throws DecryptionFailedException
482
-	 */
483
-	public function isReadable($path, $uid) {
484
-		$fileKey = $this->keyManager->getFileKey($path, $uid);
485
-		if (empty($fileKey)) {
486
-			$owner = $this->util->getOwner($path);
487
-			if ($owner !== $uid) {
488
-				// if it is a shared file we throw a exception with a useful
489
-				// error message because in this case it means that the file was
490
-				// shared with the user at a point where the user didn't had a
491
-				// valid private/public key
492
-				$msg = 'Encryption module "' . $this->getDisplayName() .
493
-					'" is not able to read ' . $path;
494
-				$hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
495
-				$this->logger->warning($msg);
496
-				throw new DecryptionFailedException($msg, $hint);
497
-			}
498
-			return false;
499
-		}
500
-
501
-		return true;
502
-	}
503
-
504
-	/**
505
-	 * Initial encryption of all files
506
-	 *
507
-	 * @param InputInterface $input
508
-	 * @param OutputInterface $output write some status information to the terminal during encryption
509
-	 */
510
-	public function encryptAll(InputInterface $input, OutputInterface $output) {
511
-		$this->encryptAll->encryptAll($input, $output);
512
-	}
513
-
514
-	/**
515
-	 * prepare module to perform decrypt all operation
516
-	 *
517
-	 * @param InputInterface $input
518
-	 * @param OutputInterface $output
519
-	 * @param string $user
520
-	 * @return bool
521
-	 */
522
-	public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
523
-		return $this->decryptAll->prepare($input, $output, $user);
524
-	}
525
-
526
-
527
-	/**
528
-	 * @param string $path
529
-	 * @return string
530
-	 */
531
-	protected function getPathToRealFile($path) {
532
-		$realPath = $path;
533
-		$parts = explode('/', $path);
534
-		if ($parts[2] === 'files_versions') {
535
-			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
536
-			$length = strrpos($realPath, '.');
537
-			$realPath = substr($realPath, 0, $length);
538
-		}
539
-
540
-		return $realPath;
541
-	}
542
-
543
-	/**
544
-	 * remove .part file extension and the ocTransferId from the file to get the
545
-	 * original file name
546
-	 *
547
-	 * @param string $path
548
-	 * @return string
549
-	 */
550
-	protected function stripPartFileExtension($path) {
551
-		if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
552
-			$pos = strrpos($path, '.', -6);
553
-			$path = substr($path, 0, $pos);
554
-		}
555
-
556
-		return $path;
557
-	}
558
-
559
-	/**
560
-	 * Check if the module is ready to be used by that specific user.
561
-	 * In case a module is not ready - because e.g. key pairs have not been generated
562
-	 * upon login this method can return false before any operation starts and might
563
-	 * cause issues during operations.
564
-	 *
565
-	 * @param string $user
566
-	 * @return boolean
567
-	 * @since 9.1.0
568
-	 */
569
-	public function isReadyForUser($user) {
570
-		return $this->keyManager->userHasKeys($user);
571
-	}
46
+    const ID = 'OC_DEFAULT_MODULE';
47
+    const DISPLAY_NAME = 'Default encryption module';
48
+
49
+    /**
50
+     * @var Crypt
51
+     */
52
+    private $crypt;
53
+
54
+    /** @var string */
55
+    private $cipher;
56
+
57
+    /** @var string */
58
+    private $path;
59
+
60
+    /** @var string */
61
+    private $user;
62
+
63
+    /** @var string */
64
+    private $fileKey;
65
+
66
+    /** @var string */
67
+    private $writeCache;
68
+
69
+    /** @var KeyManager */
70
+    private $keyManager;
71
+
72
+    /** @var array */
73
+    private $accessList;
74
+
75
+    /** @var boolean */
76
+    private $isWriteOperation;
77
+
78
+    /** @var Util */
79
+    private $util;
80
+
81
+    /** @var  Session */
82
+    private $session;
83
+
84
+    /** @var  ILogger */
85
+    private $logger;
86
+
87
+    /** @var IL10N */
88
+    private $l;
89
+
90
+    /** @var EncryptAll */
91
+    private $encryptAll;
92
+
93
+    /** @var  bool */
94
+    private $useMasterPassword;
95
+
96
+    /** @var DecryptAll  */
97
+    private $decryptAll;
98
+
99
+    /** @var int unencrypted block size if block contains signature */
100
+    private $unencryptedBlockSizeSigned = 6072;
101
+
102
+    /** @var int unencrypted block size */
103
+    private $unencryptedBlockSize = 6126;
104
+
105
+    /** @var int Current version of the file */
106
+    private $version = 0;
107
+
108
+    /** @var array remember encryption signature version */
109
+    private static $rememberVersion = [];
110
+
111
+
112
+    /**
113
+     *
114
+     * @param Crypt $crypt
115
+     * @param KeyManager $keyManager
116
+     * @param Util $util
117
+     * @param Session $session
118
+     * @param EncryptAll $encryptAll
119
+     * @param DecryptAll $decryptAll
120
+     * @param ILogger $logger
121
+     * @param IL10N $il10n
122
+     */
123
+    public function __construct(Crypt $crypt,
124
+                                KeyManager $keyManager,
125
+                                Util $util,
126
+                                Session $session,
127
+                                EncryptAll $encryptAll,
128
+                                DecryptAll $decryptAll,
129
+                                ILogger $logger,
130
+                                IL10N $il10n) {
131
+        $this->crypt = $crypt;
132
+        $this->keyManager = $keyManager;
133
+        $this->util = $util;
134
+        $this->session = $session;
135
+        $this->encryptAll = $encryptAll;
136
+        $this->decryptAll = $decryptAll;
137
+        $this->logger = $logger;
138
+        $this->l = $il10n;
139
+        $this->useMasterPassword = $util->isMasterKeyEnabled();
140
+    }
141
+
142
+    /**
143
+     * @return string defining the technical unique id
144
+     */
145
+    public function getId() {
146
+        return self::ID;
147
+    }
148
+
149
+    /**
150
+     * In comparison to getKey() this function returns a human readable (maybe translated) name
151
+     *
152
+     * @return string
153
+     */
154
+    public function getDisplayName() {
155
+        return self::DISPLAY_NAME;
156
+    }
157
+
158
+    /**
159
+     * start receiving chunks from a file. This is the place where you can
160
+     * perform some initial step before starting encrypting/decrypting the
161
+     * chunks
162
+     *
163
+     * @param string $path to the file
164
+     * @param string $user who read/write the file
165
+     * @param string $mode php stream open mode
166
+     * @param array $header contains the header data read from the file
167
+     * @param array $accessList who has access to the file contains the key 'users' and 'public'
168
+     *
169
+     * @return array $header contain data as key-value pairs which should be
170
+     *                       written to the header, in case of a write operation
171
+     *                       or if no additional data is needed return a empty array
172
+     */
173
+    public function begin($path, $user, $mode, array $header, array $accessList) {
174
+        $this->path = $this->getPathToRealFile($path);
175
+        $this->accessList = $accessList;
176
+        $this->user = $user;
177
+        $this->isWriteOperation = false;
178
+        $this->writeCache = '';
179
+
180
+        if($this->session->isReady() === false) {
181
+            // if the master key is enabled we can initialize encryption
182
+            // with a empty password and user name
183
+            if ($this->util->isMasterKeyEnabled()) {
184
+                $this->keyManager->init('', '');
185
+            }
186
+        }
187
+
188
+        if ($this->session->decryptAllModeActivated()) {
189
+            $encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
190
+            $shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
191
+            $this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
192
+                $shareKey,
193
+                $this->session->getDecryptAllKey());
194
+        } else {
195
+            $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
196
+        }
197
+
198
+        // always use the version from the original file, also part files
199
+        // need to have a correct version number if they get moved over to the
200
+        // final location
201
+        $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
202
+
203
+        if (
204
+            $mode === 'w'
205
+            || $mode === 'w+'
206
+            || $mode === 'wb'
207
+            || $mode === 'wb+'
208
+        ) {
209
+            $this->isWriteOperation = true;
210
+            if (empty($this->fileKey)) {
211
+                $this->fileKey = $this->crypt->generateFileKey();
212
+            }
213
+        } else {
214
+            // if we read a part file we need to increase the version by 1
215
+            // because the version number was also increased by writing
216
+            // the part file
217
+            if(Scanner::isPartialFile($path)) {
218
+                $this->version = $this->version + 1;
219
+            }
220
+        }
221
+
222
+        if ($this->isWriteOperation) {
223
+            $this->cipher = $this->crypt->getCipher();
224
+        } elseif (isset($header['cipher'])) {
225
+            $this->cipher = $header['cipher'];
226
+        } else {
227
+            // if we read a file without a header we fall-back to the legacy cipher
228
+            // which was used in <=oC6
229
+            $this->cipher = $this->crypt->getLegacyCipher();
230
+        }
231
+
232
+        return array('cipher' => $this->cipher, 'signed' => 'true');
233
+    }
234
+
235
+    /**
236
+     * last chunk received. This is the place where you can perform some final
237
+     * operation and return some remaining data if something is left in your
238
+     * buffer.
239
+     *
240
+     * @param string $path to the file
241
+     * @param int $position
242
+     * @return string remained data which should be written to the file in case
243
+     *                of a write operation
244
+     * @throws PublicKeyMissingException
245
+     * @throws \Exception
246
+     * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
247
+     */
248
+    public function end($path, $position = 0) {
249
+        $result = '';
250
+        if ($this->isWriteOperation) {
251
+            $this->keyManager->setVersion($path, $this->version + 1, new View());
252
+            // in case of a part file we remember the new signature versions
253
+            // the version will be set later on update.
254
+            // This way we make sure that other apps listening to the pre-hooks
255
+            // still get the old version which should be the correct value for them
256
+            if (Scanner::isPartialFile($path)) {
257
+                self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
258
+            }
259
+            if (!empty($this->writeCache)) {
260
+                $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
261
+                $this->writeCache = '';
262
+            }
263
+            $publicKeys = array();
264
+            if ($this->useMasterPassword === true) {
265
+                $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
266
+            } else {
267
+                foreach ($this->accessList['users'] as $uid) {
268
+                    try {
269
+                        $publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
270
+                    } catch (PublicKeyMissingException $e) {
271
+                        $this->logger->warning(
272
+                            'no public key found for user "{uid}", user will not be able to read the file',
273
+                            ['app' => 'encryption', 'uid' => $uid]
274
+                        );
275
+                        // if the public key of the owner is missing we should fail
276
+                        if ($uid === $this->user) {
277
+                            throw $e;
278
+                        }
279
+                    }
280
+                }
281
+            }
282
+
283
+            $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->user);
284
+            $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
285
+            $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
286
+        }
287
+        return $result;
288
+    }
289
+
290
+    /**
291
+     * encrypt data
292
+     *
293
+     * @param string $data you want to encrypt
294
+     * @param int $position
295
+     * @return string encrypted data
296
+     */
297
+    public function encrypt($data, $position = 0) {
298
+        // If extra data is left over from the last round, make sure it
299
+        // is integrated into the next block
300
+        if ($this->writeCache) {
301
+
302
+            // Concat writeCache to start of $data
303
+            $data = $this->writeCache . $data;
304
+
305
+            // Clear the write cache, ready for reuse - it has been
306
+            // flushed and its old contents processed
307
+            $this->writeCache = '';
308
+
309
+        }
310
+
311
+        $encrypted = '';
312
+        // While there still remains some data to be processed & written
313
+        while (strlen($data) > 0) {
314
+
315
+            // Remaining length for this iteration, not of the
316
+            // entire file (may be greater than 8192 bytes)
317
+            $remainingLength = strlen($data);
318
+
319
+            // If data remaining to be written is less than the
320
+            // size of 1 6126 byte block
321
+            if ($remainingLength < $this->unencryptedBlockSizeSigned) {
322
+
323
+                // Set writeCache to contents of $data
324
+                // The writeCache will be carried over to the
325
+                // next write round, and added to the start of
326
+                // $data to ensure that written blocks are
327
+                // always the correct length. If there is still
328
+                // data in writeCache after the writing round
329
+                // has finished, then the data will be written
330
+                // to disk by $this->flush().
331
+                $this->writeCache = $data;
332
+
333
+                // Clear $data ready for next round
334
+                $data = '';
335
+
336
+            } else {
337
+
338
+                // Read the chunk from the start of $data
339
+                $chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
340
+
341
+                $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
342
+
343
+                // Remove the chunk we just processed from
344
+                // $data, leaving only unprocessed data in $data
345
+                // var, for handling on the next round
346
+                $data = substr($data, $this->unencryptedBlockSizeSigned);
347
+
348
+            }
349
+
350
+        }
351
+
352
+        return $encrypted;
353
+    }
354
+
355
+    /**
356
+     * decrypt data
357
+     *
358
+     * @param string $data you want to decrypt
359
+     * @param int $position
360
+     * @return string decrypted data
361
+     * @throws DecryptionFailedException
362
+     */
363
+    public function decrypt($data, $position = 0) {
364
+        if (empty($this->fileKey)) {
365
+            $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
366
+            $hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
367
+            $this->logger->error($msg);
368
+
369
+            throw new DecryptionFailedException($msg, $hint);
370
+        }
371
+
372
+        return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
373
+    }
374
+
375
+    /**
376
+     * update encrypted file, e.g. give additional users access to the file
377
+     *
378
+     * @param string $path path to the file which should be updated
379
+     * @param string $uid of the user who performs the operation
380
+     * @param array $accessList who has access to the file contains the key 'users' and 'public'
381
+     * @return boolean
382
+     */
383
+    public function update($path, $uid, array $accessList) {
384
+
385
+        if (empty($accessList)) {
386
+            if (isset(self::$rememberVersion[$path])) {
387
+                $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
388
+                unset(self::$rememberVersion[$path]);
389
+            }
390
+            return;
391
+        }
392
+
393
+        $fileKey = $this->keyManager->getFileKey($path, $uid);
394
+
395
+        if (!empty($fileKey)) {
396
+
397
+            $publicKeys = array();
398
+            if ($this->useMasterPassword === true) {
399
+                $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
400
+            } else {
401
+                foreach ($accessList['users'] as $user) {
402
+                    try {
403
+                        $publicKeys[$user] = $this->keyManager->getPublicKey($user);
404
+                    } catch (PublicKeyMissingException $e) {
405
+                        $this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
406
+                    }
407
+                }
408
+            }
409
+
410
+            $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid);
411
+
412
+            $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
413
+
414
+            $this->keyManager->deleteAllFileKeys($path);
415
+
416
+            $this->keyManager->setAllFileKeys($path, $encryptedFileKey);
417
+
418
+        } else {
419
+            $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
420
+                array('file' => $path, 'app' => 'encryption'));
421
+
422
+            return false;
423
+        }
424
+
425
+        return true;
426
+    }
427
+
428
+    /**
429
+     * should the file be encrypted or not
430
+     *
431
+     * @param string $path
432
+     * @return boolean
433
+     */
434
+    public function shouldEncrypt($path) {
435
+        if ($this->util->shouldEncryptHomeStorage() === false) {
436
+            $storage = $this->util->getStorage($path);
437
+            if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
438
+                return false;
439
+            }
440
+        }
441
+        $parts = explode('/', $path);
442
+        if (count($parts) < 4) {
443
+            return false;
444
+        }
445
+
446
+        if ($parts[2] == 'files') {
447
+            return true;
448
+        }
449
+        if ($parts[2] == 'files_versions') {
450
+            return true;
451
+        }
452
+        if ($parts[2] == 'files_trashbin') {
453
+            return true;
454
+        }
455
+
456
+        return false;
457
+    }
458
+
459
+    /**
460
+     * get size of the unencrypted payload per block.
461
+     * ownCloud read/write files with a block size of 8192 byte
462
+     *
463
+     * @param bool $signed
464
+     * @return int
465
+     */
466
+    public function getUnencryptedBlockSize($signed = false) {
467
+        if ($signed === false) {
468
+            return $this->unencryptedBlockSize;
469
+        }
470
+
471
+        return $this->unencryptedBlockSizeSigned;
472
+    }
473
+
474
+    /**
475
+     * check if the encryption module is able to read the file,
476
+     * e.g. if all encryption keys exists
477
+     *
478
+     * @param string $path
479
+     * @param string $uid user for whom we want to check if he can read the file
480
+     * @return bool
481
+     * @throws DecryptionFailedException
482
+     */
483
+    public function isReadable($path, $uid) {
484
+        $fileKey = $this->keyManager->getFileKey($path, $uid);
485
+        if (empty($fileKey)) {
486
+            $owner = $this->util->getOwner($path);
487
+            if ($owner !== $uid) {
488
+                // if it is a shared file we throw a exception with a useful
489
+                // error message because in this case it means that the file was
490
+                // shared with the user at a point where the user didn't had a
491
+                // valid private/public key
492
+                $msg = 'Encryption module "' . $this->getDisplayName() .
493
+                    '" is not able to read ' . $path;
494
+                $hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
495
+                $this->logger->warning($msg);
496
+                throw new DecryptionFailedException($msg, $hint);
497
+            }
498
+            return false;
499
+        }
500
+
501
+        return true;
502
+    }
503
+
504
+    /**
505
+     * Initial encryption of all files
506
+     *
507
+     * @param InputInterface $input
508
+     * @param OutputInterface $output write some status information to the terminal during encryption
509
+     */
510
+    public function encryptAll(InputInterface $input, OutputInterface $output) {
511
+        $this->encryptAll->encryptAll($input, $output);
512
+    }
513
+
514
+    /**
515
+     * prepare module to perform decrypt all operation
516
+     *
517
+     * @param InputInterface $input
518
+     * @param OutputInterface $output
519
+     * @param string $user
520
+     * @return bool
521
+     */
522
+    public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
523
+        return $this->decryptAll->prepare($input, $output, $user);
524
+    }
525
+
526
+
527
+    /**
528
+     * @param string $path
529
+     * @return string
530
+     */
531
+    protected function getPathToRealFile($path) {
532
+        $realPath = $path;
533
+        $parts = explode('/', $path);
534
+        if ($parts[2] === 'files_versions') {
535
+            $realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
536
+            $length = strrpos($realPath, '.');
537
+            $realPath = substr($realPath, 0, $length);
538
+        }
539
+
540
+        return $realPath;
541
+    }
542
+
543
+    /**
544
+     * remove .part file extension and the ocTransferId from the file to get the
545
+     * original file name
546
+     *
547
+     * @param string $path
548
+     * @return string
549
+     */
550
+    protected function stripPartFileExtension($path) {
551
+        if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
552
+            $pos = strrpos($path, '.', -6);
553
+            $path = substr($path, 0, $pos);
554
+        }
555
+
556
+        return $path;
557
+    }
558
+
559
+    /**
560
+     * Check if the module is ready to be used by that specific user.
561
+     * In case a module is not ready - because e.g. key pairs have not been generated
562
+     * upon login this method can return false before any operation starts and might
563
+     * cause issues during operations.
564
+     *
565
+     * @param string $user
566
+     * @return boolean
567
+     * @since 9.1.0
568
+     */
569
+    public function isReadyForUser($user) {
570
+        return $this->keyManager->userHasKeys($user);
571
+    }
572 572
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Crypto/EncryptAll.php 1 patch
Indentation   +426 added lines, -426 removed lines patch added patch discarded remove patch
@@ -45,431 +45,431 @@
 block discarded – undo
45 45
 
46 46
 class EncryptAll {
47 47
 
48
-	/** @var Setup */
49
-	protected $userSetup;
50
-
51
-	/** @var IUserManager */
52
-	protected $userManager;
53
-
54
-	/** @var View */
55
-	protected $rootView;
56
-
57
-	/** @var KeyManager */
58
-	protected $keyManager;
59
-
60
-	/** @var Util */
61
-	protected $util;
62
-
63
-	/** @var array  */
64
-	protected $userPasswords;
65
-
66
-	/** @var  IConfig */
67
-	protected $config;
68
-
69
-	/** @var IMailer */
70
-	protected $mailer;
71
-
72
-	/** @var  IL10N */
73
-	protected $l;
74
-
75
-	/** @var  QuestionHelper */
76
-	protected $questionHelper;
77
-
78
-	/** @var  OutputInterface */
79
-	protected $output;
80
-
81
-	/** @var  InputInterface */
82
-	protected $input;
83
-
84
-	/** @var ISecureRandom */
85
-	protected $secureRandom;
86
-
87
-	/**
88
-	 * @param Setup $userSetup
89
-	 * @param IUserManager $userManager
90
-	 * @param View $rootView
91
-	 * @param KeyManager $keyManager
92
-	 * @param Util $util
93
-	 * @param IConfig $config
94
-	 * @param IMailer $mailer
95
-	 * @param IL10N $l
96
-	 * @param QuestionHelper $questionHelper
97
-	 * @param ISecureRandom $secureRandom
98
-	 */
99
-	public function __construct(
100
-		Setup $userSetup,
101
-		IUserManager $userManager,
102
-		View $rootView,
103
-		KeyManager $keyManager,
104
-		Util $util,
105
-		IConfig $config,
106
-		IMailer $mailer,
107
-		IL10N $l,
108
-		QuestionHelper $questionHelper,
109
-		ISecureRandom $secureRandom
110
-	) {
111
-		$this->userSetup = $userSetup;
112
-		$this->userManager = $userManager;
113
-		$this->rootView = $rootView;
114
-		$this->keyManager = $keyManager;
115
-		$this->util = $util;
116
-		$this->config = $config;
117
-		$this->mailer = $mailer;
118
-		$this->l = $l;
119
-		$this->questionHelper = $questionHelper;
120
-		$this->secureRandom = $secureRandom;
121
-		// store one time passwords for the users
122
-		$this->userPasswords = array();
123
-	}
124
-
125
-	/**
126
-	 * start to encrypt all files
127
-	 *
128
-	 * @param InputInterface $input
129
-	 * @param OutputInterface $output
130
-	 */
131
-	public function encryptAll(InputInterface $input, OutputInterface $output) {
132
-
133
-		$this->input = $input;
134
-		$this->output = $output;
135
-
136
-		$headline = 'Encrypt all files with the ' . Encryption::DISPLAY_NAME;
137
-		$this->output->writeln("\n");
138
-		$this->output->writeln($headline);
139
-		$this->output->writeln(str_pad('', strlen($headline), '='));
140
-		$this->output->writeln("\n");
141
-
142
-		if ($this->util->isMasterKeyEnabled()) {
143
-			$this->output->writeln('Use master key to encrypt all files.');
144
-			$this->keyManager->validateMasterKey();
145
-		} else {
146
-			//create private/public keys for each user and store the private key password
147
-			$this->output->writeln('Create key-pair for every user');
148
-			$this->output->writeln('------------------------------');
149
-			$this->output->writeln('');
150
-			$this->output->writeln('This module will encrypt all files in the users files folder initially.');
151
-			$this->output->writeln('Already existing versions and files in the trash bin will not be encrypted.');
152
-			$this->output->writeln('');
153
-			$this->createKeyPairs();
154
-		}
155
-
156
-		//setup users file system and encrypt all files one by one (take should encrypt setting of storage into account)
157
-		$this->output->writeln("\n");
158
-		$this->output->writeln('Start to encrypt users files');
159
-		$this->output->writeln('----------------------------');
160
-		$this->output->writeln('');
161
-		$this->encryptAllUsersFiles();
162
-		if ($this->util->isMasterKeyEnabled() === false) {
163
-			//send-out or display password list and write it to a file
164
-			$this->output->writeln("\n");
165
-			$this->output->writeln('Generated encryption key passwords');
166
-			$this->output->writeln('----------------------------------');
167
-			$this->output->writeln('');
168
-			$this->outputPasswords();
169
-		}
170
-		$this->output->writeln("\n");
171
-	}
172
-
173
-	/**
174
-	 * create key-pair for every user
175
-	 */
176
-	protected function createKeyPairs() {
177
-		$this->output->writeln("\n");
178
-		$progress = new ProgressBar($this->output);
179
-		$progress->setFormat(" %message% \n [%bar%]");
180
-		$progress->start();
181
-
182
-		foreach($this->userManager->getBackends() as $backend) {
183
-			$limit = 500;
184
-			$offset = 0;
185
-			do {
186
-				$users = $backend->getUsers('', $limit, $offset);
187
-				foreach ($users as $user) {
188
-					if ($this->keyManager->userHasKeys($user) === false) {
189
-						$progress->setMessage('Create key-pair for ' . $user);
190
-						$progress->advance();
191
-						$this->setupUserFS($user);
192
-						$password = $this->generateOneTimePassword($user);
193
-						$this->userSetup->setupUser($user, $password);
194
-					} else {
195
-						// users which already have a key-pair will be stored with a
196
-						// empty password and filtered out later
197
-						$this->userPasswords[$user] = '';
198
-					}
199
-				}
200
-				$offset += $limit;
201
-			} while(count($users) >= $limit);
202
-		}
203
-
204
-		$progress->setMessage('Key-pair created for all users');
205
-		$progress->finish();
206
-	}
207
-
208
-	/**
209
-	 * iterate over all user and encrypt their files
210
-	 */
211
-	protected function encryptAllUsersFiles() {
212
-		$this->output->writeln("\n");
213
-		$progress = new ProgressBar($this->output);
214
-		$progress->setFormat(" %message% \n [%bar%]");
215
-		$progress->start();
216
-		$numberOfUsers = count($this->userPasswords);
217
-		$userNo = 1;
218
-		if ($this->util->isMasterKeyEnabled()) {
219
-			$this->encryptAllUserFilesWithMasterKey($progress);
220
-		} else {
221
-			foreach ($this->userPasswords as $uid => $password) {
222
-				$userCount = "$uid ($userNo of $numberOfUsers)";
223
-				$this->encryptUsersFiles($uid, $progress, $userCount);
224
-				$userNo++;
225
-			}
226
-		}
227
-		$progress->setMessage("all files encrypted");
228
-		$progress->finish();
229
-
230
-	}
231
-
232
-	/**
233
-	 * encrypt all user files with the master key
234
-	 *
235
-	 * @param ProgressBar $progress
236
-	 */
237
-	protected function encryptAllUserFilesWithMasterKey(ProgressBar $progress) {
238
-		$userNo = 1;
239
-		foreach($this->userManager->getBackends() as $backend) {
240
-			$limit = 500;
241
-			$offset = 0;
242
-			do {
243
-				$users = $backend->getUsers('', $limit, $offset);
244
-				foreach ($users as $user) {
245
-					$userCount = "$user ($userNo)";
246
-					$this->encryptUsersFiles($user, $progress, $userCount);
247
-					$userNo++;
248
-				}
249
-				$offset += $limit;
250
-			} while(count($users) >= $limit);
251
-		}
252
-	}
253
-
254
-	/**
255
-	 * encrypt files from the given user
256
-	 *
257
-	 * @param string $uid
258
-	 * @param ProgressBar $progress
259
-	 * @param string $userCount
260
-	 */
261
-	protected function encryptUsersFiles($uid, ProgressBar $progress, $userCount) {
262
-
263
-		$this->setupUserFS($uid);
264
-		$directories = array();
265
-		$directories[] =  '/' . $uid . '/files';
266
-
267
-		while($root = array_pop($directories)) {
268
-			$content = $this->rootView->getDirectoryContent($root);
269
-			foreach ($content as $file) {
270
-				$path = $root . '/' . $file['name'];
271
-				if ($this->rootView->is_dir($path)) {
272
-					$directories[] = $path;
273
-					continue;
274
-				} else {
275
-					$progress->setMessage("encrypt files for user $userCount: $path");
276
-					$progress->advance();
277
-					if($this->encryptFile($path) === false) {
278
-						$progress->setMessage("encrypt files for user $userCount: $path (already encrypted)");
279
-						$progress->advance();
280
-					}
281
-				}
282
-			}
283
-		}
284
-	}
285
-
286
-	/**
287
-	 * encrypt file
288
-	 *
289
-	 * @param string $path
290
-	 * @return bool
291
-	 */
292
-	protected function encryptFile($path) {
293
-
294
-		$source = $path;
295
-		$target = $path . '.encrypted.' . time();
296
-
297
-		try {
298
-			$this->rootView->copy($source, $target);
299
-			$this->rootView->rename($target, $source);
300
-		} catch (DecryptionFailedException $e) {
301
-			if ($this->rootView->file_exists($target)) {
302
-				$this->rootView->unlink($target);
303
-			}
304
-			return false;
305
-		}
306
-
307
-		return true;
308
-	}
309
-
310
-	/**
311
-	 * output one-time encryption passwords
312
-	 */
313
-	protected function outputPasswords() {
314
-		$table = new Table($this->output);
315
-		$table->setHeaders(array('Username', 'Private key password'));
316
-
317
-		//create rows
318
-		$newPasswords = array();
319
-		$unchangedPasswords = array();
320
-		foreach ($this->userPasswords as $uid => $password) {
321
-			if (empty($password)) {
322
-				$unchangedPasswords[] = $uid;
323
-			} else {
324
-				$newPasswords[] = [$uid, $password];
325
-			}
326
-		}
327
-
328
-		if (empty($newPasswords)) {
329
-			$this->output->writeln("\nAll users already had a key-pair, no further action needed.\n");
330
-			return;
331
-		}
332
-
333
-		$table->setRows($newPasswords);
334
-		$table->render();
335
-
336
-		if (!empty($unchangedPasswords)) {
337
-			$this->output->writeln("\nThe following users already had a key-pair which was reused without setting a new password:\n");
338
-			foreach ($unchangedPasswords as $uid) {
339
-				$this->output->writeln("    $uid");
340
-			}
341
-		}
342
-
343
-		$this->writePasswordsToFile($newPasswords);
344
-
345
-		$this->output->writeln('');
346
-		$question = new ConfirmationQuestion('Do you want to send the passwords directly to the users by mail? (y/n) ', false);
347
-		if ($this->questionHelper->ask($this->input, $this->output, $question)) {
348
-			$this->sendPasswordsByMail();
349
-		}
350
-	}
351
-
352
-	/**
353
-	 * write one-time encryption passwords to a csv file
354
-	 *
355
-	 * @param array $passwords
356
-	 */
357
-	protected function writePasswordsToFile(array $passwords) {
358
-		$fp = $this->rootView->fopen('oneTimeEncryptionPasswords.csv', 'w');
359
-		foreach ($passwords as $pwd) {
360
-			fputcsv($fp, $pwd);
361
-		}
362
-		fclose($fp);
363
-		$this->output->writeln("\n");
364
-		$this->output->writeln('A list of all newly created passwords was written to data/oneTimeEncryptionPasswords.csv');
365
-		$this->output->writeln('');
366
-		$this->output->writeln('Each of these users need to login to the web interface, go to the');
367
-		$this->output->writeln('personal settings section "basic encryption module" and');
368
-		$this->output->writeln('update the private key password to match the login password again by');
369
-		$this->output->writeln('entering the one-time password into the "old log-in password" field');
370
-		$this->output->writeln('and their current login password');
371
-	}
372
-
373
-	/**
374
-	 * setup user file system
375
-	 *
376
-	 * @param string $uid
377
-	 */
378
-	protected function setupUserFS($uid) {
379
-		\OC_Util::tearDownFS();
380
-		\OC_Util::setupFS($uid);
381
-	}
382
-
383
-	/**
384
-	 * generate one time password for the user and store it in a array
385
-	 *
386
-	 * @param string $uid
387
-	 * @return string password
388
-	 */
389
-	protected function generateOneTimePassword($uid) {
390
-		$password = $this->secureRandom->generate(8);
391
-		$this->userPasswords[$uid] = $password;
392
-		return $password;
393
-	}
394
-
395
-	/**
396
-	 * send encryption key passwords to the users by mail
397
-	 */
398
-	protected function sendPasswordsByMail() {
399
-		$noMail = [];
400
-
401
-		$this->output->writeln('');
402
-		$progress = new ProgressBar($this->output, count($this->userPasswords));
403
-		$progress->start();
404
-
405
-		foreach ($this->userPasswords as $uid => $password) {
406
-			$progress->advance();
407
-			if (!empty($password)) {
408
-				$recipient = $this->userManager->get($uid);
409
-				$recipientDisplayName = $recipient->getDisplayName();
410
-				$to = $recipient->getEMailAddress();
411
-
412
-				if ($to === '') {
413
-					$noMail[] = $uid;
414
-					continue;
415
-				}
416
-
417
-				$subject = (string)$this->l->t('one-time password for server-side-encryption');
418
-				list($htmlBody, $textBody) = $this->createMailBody($password);
419
-
420
-				// send it out now
421
-				try {
422
-					$message = $this->mailer->createMessage();
423
-					$message->setSubject($subject);
424
-					$message->setTo([$to => $recipientDisplayName]);
425
-					$message->setHtmlBody($htmlBody);
426
-					$message->setPlainBody($textBody);
427
-					$message->setFrom([
428
-						\OCP\Util::getDefaultEmailAddress('admin-noreply')
429
-					]);
430
-
431
-					$this->mailer->send($message);
432
-				} catch (\Exception $e) {
433
-					$noMail[] = $uid;
434
-				}
435
-			}
436
-		}
437
-
438
-		$progress->finish();
439
-
440
-		if (empty($noMail)) {
441
-			$this->output->writeln("\n\nPassword successfully send to all users");
442
-		} else {
443
-			$table = new Table($this->output);
444
-			$table->setHeaders(array('Username', 'Private key password'));
445
-			$this->output->writeln("\n\nCould not send password to following users:\n");
446
-			$rows = [];
447
-			foreach ($noMail as $uid) {
448
-				$rows[] = [$uid, $this->userPasswords[$uid]];
449
-			}
450
-			$table->setRows($rows);
451
-			$table->render();
452
-		}
453
-
454
-	}
455
-
456
-	/**
457
-	 * create mail body for plain text and html mail
458
-	 *
459
-	 * @param string $password one-time encryption password
460
-	 * @return array an array of the html mail body and the plain text mail body
461
-	 */
462
-	protected function createMailBody($password) {
463
-
464
-		$html = new \OC_Template("encryption", "mail", "");
465
-		$html->assign ('password', $password);
466
-		$htmlMail = $html->fetchPage();
467
-
468
-		$plainText = new \OC_Template("encryption", "altmail", "");
469
-		$plainText->assign ('password', $password);
470
-		$plainTextMail = $plainText->fetchPage();
471
-
472
-		return [$htmlMail, $plainTextMail];
473
-	}
48
+    /** @var Setup */
49
+    protected $userSetup;
50
+
51
+    /** @var IUserManager */
52
+    protected $userManager;
53
+
54
+    /** @var View */
55
+    protected $rootView;
56
+
57
+    /** @var KeyManager */
58
+    protected $keyManager;
59
+
60
+    /** @var Util */
61
+    protected $util;
62
+
63
+    /** @var array  */
64
+    protected $userPasswords;
65
+
66
+    /** @var  IConfig */
67
+    protected $config;
68
+
69
+    /** @var IMailer */
70
+    protected $mailer;
71
+
72
+    /** @var  IL10N */
73
+    protected $l;
74
+
75
+    /** @var  QuestionHelper */
76
+    protected $questionHelper;
77
+
78
+    /** @var  OutputInterface */
79
+    protected $output;
80
+
81
+    /** @var  InputInterface */
82
+    protected $input;
83
+
84
+    /** @var ISecureRandom */
85
+    protected $secureRandom;
86
+
87
+    /**
88
+     * @param Setup $userSetup
89
+     * @param IUserManager $userManager
90
+     * @param View $rootView
91
+     * @param KeyManager $keyManager
92
+     * @param Util $util
93
+     * @param IConfig $config
94
+     * @param IMailer $mailer
95
+     * @param IL10N $l
96
+     * @param QuestionHelper $questionHelper
97
+     * @param ISecureRandom $secureRandom
98
+     */
99
+    public function __construct(
100
+        Setup $userSetup,
101
+        IUserManager $userManager,
102
+        View $rootView,
103
+        KeyManager $keyManager,
104
+        Util $util,
105
+        IConfig $config,
106
+        IMailer $mailer,
107
+        IL10N $l,
108
+        QuestionHelper $questionHelper,
109
+        ISecureRandom $secureRandom
110
+    ) {
111
+        $this->userSetup = $userSetup;
112
+        $this->userManager = $userManager;
113
+        $this->rootView = $rootView;
114
+        $this->keyManager = $keyManager;
115
+        $this->util = $util;
116
+        $this->config = $config;
117
+        $this->mailer = $mailer;
118
+        $this->l = $l;
119
+        $this->questionHelper = $questionHelper;
120
+        $this->secureRandom = $secureRandom;
121
+        // store one time passwords for the users
122
+        $this->userPasswords = array();
123
+    }
124
+
125
+    /**
126
+     * start to encrypt all files
127
+     *
128
+     * @param InputInterface $input
129
+     * @param OutputInterface $output
130
+     */
131
+    public function encryptAll(InputInterface $input, OutputInterface $output) {
132
+
133
+        $this->input = $input;
134
+        $this->output = $output;
135
+
136
+        $headline = 'Encrypt all files with the ' . Encryption::DISPLAY_NAME;
137
+        $this->output->writeln("\n");
138
+        $this->output->writeln($headline);
139
+        $this->output->writeln(str_pad('', strlen($headline), '='));
140
+        $this->output->writeln("\n");
141
+
142
+        if ($this->util->isMasterKeyEnabled()) {
143
+            $this->output->writeln('Use master key to encrypt all files.');
144
+            $this->keyManager->validateMasterKey();
145
+        } else {
146
+            //create private/public keys for each user and store the private key password
147
+            $this->output->writeln('Create key-pair for every user');
148
+            $this->output->writeln('------------------------------');
149
+            $this->output->writeln('');
150
+            $this->output->writeln('This module will encrypt all files in the users files folder initially.');
151
+            $this->output->writeln('Already existing versions and files in the trash bin will not be encrypted.');
152
+            $this->output->writeln('');
153
+            $this->createKeyPairs();
154
+        }
155
+
156
+        //setup users file system and encrypt all files one by one (take should encrypt setting of storage into account)
157
+        $this->output->writeln("\n");
158
+        $this->output->writeln('Start to encrypt users files');
159
+        $this->output->writeln('----------------------------');
160
+        $this->output->writeln('');
161
+        $this->encryptAllUsersFiles();
162
+        if ($this->util->isMasterKeyEnabled() === false) {
163
+            //send-out or display password list and write it to a file
164
+            $this->output->writeln("\n");
165
+            $this->output->writeln('Generated encryption key passwords');
166
+            $this->output->writeln('----------------------------------');
167
+            $this->output->writeln('');
168
+            $this->outputPasswords();
169
+        }
170
+        $this->output->writeln("\n");
171
+    }
172
+
173
+    /**
174
+     * create key-pair for every user
175
+     */
176
+    protected function createKeyPairs() {
177
+        $this->output->writeln("\n");
178
+        $progress = new ProgressBar($this->output);
179
+        $progress->setFormat(" %message% \n [%bar%]");
180
+        $progress->start();
181
+
182
+        foreach($this->userManager->getBackends() as $backend) {
183
+            $limit = 500;
184
+            $offset = 0;
185
+            do {
186
+                $users = $backend->getUsers('', $limit, $offset);
187
+                foreach ($users as $user) {
188
+                    if ($this->keyManager->userHasKeys($user) === false) {
189
+                        $progress->setMessage('Create key-pair for ' . $user);
190
+                        $progress->advance();
191
+                        $this->setupUserFS($user);
192
+                        $password = $this->generateOneTimePassword($user);
193
+                        $this->userSetup->setupUser($user, $password);
194
+                    } else {
195
+                        // users which already have a key-pair will be stored with a
196
+                        // empty password and filtered out later
197
+                        $this->userPasswords[$user] = '';
198
+                    }
199
+                }
200
+                $offset += $limit;
201
+            } while(count($users) >= $limit);
202
+        }
203
+
204
+        $progress->setMessage('Key-pair created for all users');
205
+        $progress->finish();
206
+    }
207
+
208
+    /**
209
+     * iterate over all user and encrypt their files
210
+     */
211
+    protected function encryptAllUsersFiles() {
212
+        $this->output->writeln("\n");
213
+        $progress = new ProgressBar($this->output);
214
+        $progress->setFormat(" %message% \n [%bar%]");
215
+        $progress->start();
216
+        $numberOfUsers = count($this->userPasswords);
217
+        $userNo = 1;
218
+        if ($this->util->isMasterKeyEnabled()) {
219
+            $this->encryptAllUserFilesWithMasterKey($progress);
220
+        } else {
221
+            foreach ($this->userPasswords as $uid => $password) {
222
+                $userCount = "$uid ($userNo of $numberOfUsers)";
223
+                $this->encryptUsersFiles($uid, $progress, $userCount);
224
+                $userNo++;
225
+            }
226
+        }
227
+        $progress->setMessage("all files encrypted");
228
+        $progress->finish();
229
+
230
+    }
231
+
232
+    /**
233
+     * encrypt all user files with the master key
234
+     *
235
+     * @param ProgressBar $progress
236
+     */
237
+    protected function encryptAllUserFilesWithMasterKey(ProgressBar $progress) {
238
+        $userNo = 1;
239
+        foreach($this->userManager->getBackends() as $backend) {
240
+            $limit = 500;
241
+            $offset = 0;
242
+            do {
243
+                $users = $backend->getUsers('', $limit, $offset);
244
+                foreach ($users as $user) {
245
+                    $userCount = "$user ($userNo)";
246
+                    $this->encryptUsersFiles($user, $progress, $userCount);
247
+                    $userNo++;
248
+                }
249
+                $offset += $limit;
250
+            } while(count($users) >= $limit);
251
+        }
252
+    }
253
+
254
+    /**
255
+     * encrypt files from the given user
256
+     *
257
+     * @param string $uid
258
+     * @param ProgressBar $progress
259
+     * @param string $userCount
260
+     */
261
+    protected function encryptUsersFiles($uid, ProgressBar $progress, $userCount) {
262
+
263
+        $this->setupUserFS($uid);
264
+        $directories = array();
265
+        $directories[] =  '/' . $uid . '/files';
266
+
267
+        while($root = array_pop($directories)) {
268
+            $content = $this->rootView->getDirectoryContent($root);
269
+            foreach ($content as $file) {
270
+                $path = $root . '/' . $file['name'];
271
+                if ($this->rootView->is_dir($path)) {
272
+                    $directories[] = $path;
273
+                    continue;
274
+                } else {
275
+                    $progress->setMessage("encrypt files for user $userCount: $path");
276
+                    $progress->advance();
277
+                    if($this->encryptFile($path) === false) {
278
+                        $progress->setMessage("encrypt files for user $userCount: $path (already encrypted)");
279
+                        $progress->advance();
280
+                    }
281
+                }
282
+            }
283
+        }
284
+    }
285
+
286
+    /**
287
+     * encrypt file
288
+     *
289
+     * @param string $path
290
+     * @return bool
291
+     */
292
+    protected function encryptFile($path) {
293
+
294
+        $source = $path;
295
+        $target = $path . '.encrypted.' . time();
296
+
297
+        try {
298
+            $this->rootView->copy($source, $target);
299
+            $this->rootView->rename($target, $source);
300
+        } catch (DecryptionFailedException $e) {
301
+            if ($this->rootView->file_exists($target)) {
302
+                $this->rootView->unlink($target);
303
+            }
304
+            return false;
305
+        }
306
+
307
+        return true;
308
+    }
309
+
310
+    /**
311
+     * output one-time encryption passwords
312
+     */
313
+    protected function outputPasswords() {
314
+        $table = new Table($this->output);
315
+        $table->setHeaders(array('Username', 'Private key password'));
316
+
317
+        //create rows
318
+        $newPasswords = array();
319
+        $unchangedPasswords = array();
320
+        foreach ($this->userPasswords as $uid => $password) {
321
+            if (empty($password)) {
322
+                $unchangedPasswords[] = $uid;
323
+            } else {
324
+                $newPasswords[] = [$uid, $password];
325
+            }
326
+        }
327
+
328
+        if (empty($newPasswords)) {
329
+            $this->output->writeln("\nAll users already had a key-pair, no further action needed.\n");
330
+            return;
331
+        }
332
+
333
+        $table->setRows($newPasswords);
334
+        $table->render();
335
+
336
+        if (!empty($unchangedPasswords)) {
337
+            $this->output->writeln("\nThe following users already had a key-pair which was reused without setting a new password:\n");
338
+            foreach ($unchangedPasswords as $uid) {
339
+                $this->output->writeln("    $uid");
340
+            }
341
+        }
342
+
343
+        $this->writePasswordsToFile($newPasswords);
344
+
345
+        $this->output->writeln('');
346
+        $question = new ConfirmationQuestion('Do you want to send the passwords directly to the users by mail? (y/n) ', false);
347
+        if ($this->questionHelper->ask($this->input, $this->output, $question)) {
348
+            $this->sendPasswordsByMail();
349
+        }
350
+    }
351
+
352
+    /**
353
+     * write one-time encryption passwords to a csv file
354
+     *
355
+     * @param array $passwords
356
+     */
357
+    protected function writePasswordsToFile(array $passwords) {
358
+        $fp = $this->rootView->fopen('oneTimeEncryptionPasswords.csv', 'w');
359
+        foreach ($passwords as $pwd) {
360
+            fputcsv($fp, $pwd);
361
+        }
362
+        fclose($fp);
363
+        $this->output->writeln("\n");
364
+        $this->output->writeln('A list of all newly created passwords was written to data/oneTimeEncryptionPasswords.csv');
365
+        $this->output->writeln('');
366
+        $this->output->writeln('Each of these users need to login to the web interface, go to the');
367
+        $this->output->writeln('personal settings section "basic encryption module" and');
368
+        $this->output->writeln('update the private key password to match the login password again by');
369
+        $this->output->writeln('entering the one-time password into the "old log-in password" field');
370
+        $this->output->writeln('and their current login password');
371
+    }
372
+
373
+    /**
374
+     * setup user file system
375
+     *
376
+     * @param string $uid
377
+     */
378
+    protected function setupUserFS($uid) {
379
+        \OC_Util::tearDownFS();
380
+        \OC_Util::setupFS($uid);
381
+    }
382
+
383
+    /**
384
+     * generate one time password for the user and store it in a array
385
+     *
386
+     * @param string $uid
387
+     * @return string password
388
+     */
389
+    protected function generateOneTimePassword($uid) {
390
+        $password = $this->secureRandom->generate(8);
391
+        $this->userPasswords[$uid] = $password;
392
+        return $password;
393
+    }
394
+
395
+    /**
396
+     * send encryption key passwords to the users by mail
397
+     */
398
+    protected function sendPasswordsByMail() {
399
+        $noMail = [];
400
+
401
+        $this->output->writeln('');
402
+        $progress = new ProgressBar($this->output, count($this->userPasswords));
403
+        $progress->start();
404
+
405
+        foreach ($this->userPasswords as $uid => $password) {
406
+            $progress->advance();
407
+            if (!empty($password)) {
408
+                $recipient = $this->userManager->get($uid);
409
+                $recipientDisplayName = $recipient->getDisplayName();
410
+                $to = $recipient->getEMailAddress();
411
+
412
+                if ($to === '') {
413
+                    $noMail[] = $uid;
414
+                    continue;
415
+                }
416
+
417
+                $subject = (string)$this->l->t('one-time password for server-side-encryption');
418
+                list($htmlBody, $textBody) = $this->createMailBody($password);
419
+
420
+                // send it out now
421
+                try {
422
+                    $message = $this->mailer->createMessage();
423
+                    $message->setSubject($subject);
424
+                    $message->setTo([$to => $recipientDisplayName]);
425
+                    $message->setHtmlBody($htmlBody);
426
+                    $message->setPlainBody($textBody);
427
+                    $message->setFrom([
428
+                        \OCP\Util::getDefaultEmailAddress('admin-noreply')
429
+                    ]);
430
+
431
+                    $this->mailer->send($message);
432
+                } catch (\Exception $e) {
433
+                    $noMail[] = $uid;
434
+                }
435
+            }
436
+        }
437
+
438
+        $progress->finish();
439
+
440
+        if (empty($noMail)) {
441
+            $this->output->writeln("\n\nPassword successfully send to all users");
442
+        } else {
443
+            $table = new Table($this->output);
444
+            $table->setHeaders(array('Username', 'Private key password'));
445
+            $this->output->writeln("\n\nCould not send password to following users:\n");
446
+            $rows = [];
447
+            foreach ($noMail as $uid) {
448
+                $rows[] = [$uid, $this->userPasswords[$uid]];
449
+            }
450
+            $table->setRows($rows);
451
+            $table->render();
452
+        }
453
+
454
+    }
455
+
456
+    /**
457
+     * create mail body for plain text and html mail
458
+     *
459
+     * @param string $password one-time encryption password
460
+     * @return array an array of the html mail body and the plain text mail body
461
+     */
462
+    protected function createMailBody($password) {
463
+
464
+        $html = new \OC_Template("encryption", "mail", "");
465
+        $html->assign ('password', $password);
466
+        $htmlMail = $html->fetchPage();
467
+
468
+        $plainText = new \OC_Template("encryption", "altmail", "");
469
+        $plainText->assign ('password', $password);
470
+        $plainTextMail = $plainText->fetchPage();
471
+
472
+        return [$htmlMail, $plainTextMail];
473
+    }
474 474
 
475 475
 }
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
@@ -54,641 +54,641 @@
 block discarded – undo
54 54
  */
55 55
 class Crypt {
56 56
 
57
-	const DEFAULT_CIPHER = 'AES-256-CTR';
58
-	// default cipher from old ownCloud versions
59
-	const LEGACY_CIPHER = 'AES-128-CFB';
60
-
61
-	// default key format, old ownCloud version encrypted the private key directly
62
-	// with the user password
63
-	const LEGACY_KEY_FORMAT = 'password';
64
-
65
-	const HEADER_START = 'HBEGIN';
66
-	const HEADER_END = 'HEND';
67
-
68
-	/** @var ILogger */
69
-	private $logger;
70
-
71
-	/** @var string */
72
-	private $user;
73
-
74
-	/** @var IConfig */
75
-	private $config;
76
-
77
-	/** @var array */
78
-	private $supportedKeyFormats;
79
-
80
-	/** @var IL10N */
81
-	private $l;
82
-
83
-	/** @var array */
84
-	private $supportedCiphersAndKeySize = [
85
-		'AES-256-CTR' => 32,
86
-		'AES-128-CTR' => 16,
87
-		'AES-256-CFB' => 32,
88
-		'AES-128-CFB' => 16,
89
-	];
90
-
91
-	/**
92
-	 * @param ILogger $logger
93
-	 * @param IUserSession $userSession
94
-	 * @param IConfig $config
95
-	 * @param IL10N $l
96
-	 */
97
-	public function __construct(ILogger $logger, IUserSession $userSession, IConfig $config, IL10N $l) {
98
-		$this->logger = $logger;
99
-		$this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : '"no user given"';
100
-		$this->config = $config;
101
-		$this->l = $l;
102
-		$this->supportedKeyFormats = ['hash', 'password'];
103
-	}
104
-
105
-	/**
106
-	 * create new private/public key-pair for user
107
-	 *
108
-	 * @return array|bool
109
-	 */
110
-	public function createKeyPair() {
111
-
112
-		$log = $this->logger;
113
-		$res = $this->getOpenSSLPKey();
114
-
115
-		if (!$res) {
116
-			$log->error("Encryption Library couldn't generate users key-pair for {$this->user}",
117
-				['app' => 'encryption']);
118
-
119
-			if (openssl_error_string()) {
120
-				$log->error('Encryption library openssl_pkey_new() fails: ' . openssl_error_string(),
121
-					['app' => 'encryption']);
122
-			}
123
-		} elseif (openssl_pkey_export($res,
124
-			$privateKey,
125
-			null,
126
-			$this->getOpenSSLConfig())) {
127
-			$keyDetails = openssl_pkey_get_details($res);
128
-			$publicKey = $keyDetails['key'];
129
-
130
-			return [
131
-				'publicKey' => $publicKey,
132
-				'privateKey' => $privateKey
133
-			];
134
-		}
135
-		$log->error('Encryption library couldn\'t export users private key, please check your servers OpenSSL configuration.' . $this->user,
136
-			['app' => 'encryption']);
137
-		if (openssl_error_string()) {
138
-			$log->error('Encryption Library:' . openssl_error_string(),
139
-				['app' => 'encryption']);
140
-		}
141
-
142
-		return false;
143
-	}
144
-
145
-	/**
146
-	 * Generates a new private key
147
-	 *
148
-	 * @return resource
149
-	 */
150
-	public function getOpenSSLPKey() {
151
-		$config = $this->getOpenSSLConfig();
152
-		return openssl_pkey_new($config);
153
-	}
154
-
155
-	/**
156
-	 * get openSSL Config
157
-	 *
158
-	 * @return array
159
-	 */
160
-	private function getOpenSSLConfig() {
161
-		$config = ['private_key_bits' => 4096];
162
-		$config = array_merge(
163
-			$config,
164
-			$this->config->getSystemValue('openssl', [])
165
-		);
166
-		return $config;
167
-	}
168
-
169
-	/**
170
-	 * @param string $plainContent
171
-	 * @param string $passPhrase
172
-	 * @param int $version
173
-	 * @param int $position
174
-	 * @return false|string
175
-	 * @throws EncryptionFailedException
176
-	 */
177
-	public function symmetricEncryptFileContent($plainContent, $passPhrase, $version, $position) {
178
-
179
-		if (!$plainContent) {
180
-			$this->logger->error('Encryption Library, symmetrical encryption failed no content given',
181
-				['app' => 'encryption']);
182
-			return false;
183
-		}
184
-
185
-		$iv = $this->generateIv();
186
-
187
-		$encryptedContent = $this->encrypt($plainContent,
188
-			$iv,
189
-			$passPhrase,
190
-			$this->getCipher());
191
-
192
-		// Create a signature based on the key as well as the current version
193
-		$sig = $this->createSignature($encryptedContent, $passPhrase.$version.$position);
194
-
195
-		// combine content to encrypt the IV identifier and actual IV
196
-		$catFile = $this->concatIV($encryptedContent, $iv);
197
-		$catFile = $this->concatSig($catFile, $sig);
198
-		$padded = $this->addPadding($catFile);
199
-
200
-		return $padded;
201
-	}
202
-
203
-	/**
204
-	 * generate header for encrypted file
205
-	 *
206
-	 * @param string $keyFormat (can be 'hash' or 'password')
207
-	 * @return string
208
-	 * @throws \InvalidArgumentException
209
-	 */
210
-	public function generateHeader($keyFormat = 'hash') {
211
-
212
-		if (in_array($keyFormat, $this->supportedKeyFormats, true) === false) {
213
-			throw new \InvalidArgumentException('key format "' . $keyFormat . '" is not supported');
214
-		}
215
-
216
-		$cipher = $this->getCipher();
217
-
218
-		$header = self::HEADER_START
219
-			. ':cipher:' . $cipher
220
-			. ':keyFormat:' . $keyFormat
221
-			. ':' . self::HEADER_END;
222
-
223
-		return $header;
224
-	}
225
-
226
-	/**
227
-	 * @param string $plainContent
228
-	 * @param string $iv
229
-	 * @param string $passPhrase
230
-	 * @param string $cipher
231
-	 * @return string
232
-	 * @throws EncryptionFailedException
233
-	 */
234
-	private function encrypt($plainContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) {
235
-		$encryptedContent = openssl_encrypt($plainContent,
236
-			$cipher,
237
-			$passPhrase,
238
-			false,
239
-			$iv);
240
-
241
-		if (!$encryptedContent) {
242
-			$error = 'Encryption (symmetric) of content failed';
243
-			$this->logger->error($error . openssl_error_string(),
244
-				['app' => 'encryption']);
245
-			throw new EncryptionFailedException($error);
246
-		}
247
-
248
-		return $encryptedContent;
249
-	}
250
-
251
-	/**
252
-	 * return Cipher either from config.php or the default cipher defined in
253
-	 * this class
254
-	 *
255
-	 * @return string
256
-	 */
257
-	public function getCipher() {
258
-		$cipher = $this->config->getSystemValue('cipher', self::DEFAULT_CIPHER);
259
-		if (!isset($this->supportedCiphersAndKeySize[$cipher])) {
260
-			$this->logger->warning(
261
-					sprintf(
262
-							'Unsupported cipher (%s) defined in config.php supported. Falling back to %s',
263
-							$cipher,
264
-							self::DEFAULT_CIPHER
265
-					),
266
-				['app' => 'encryption']);
267
-			$cipher = self::DEFAULT_CIPHER;
268
-		}
269
-
270
-		// Workaround for OpenSSL 0.9.8. Fallback to an old cipher that should work.
271
-		if(OPENSSL_VERSION_NUMBER < 0x1000101f) {
272
-			if($cipher === 'AES-256-CTR' || $cipher === 'AES-128-CTR') {
273
-				$cipher = self::LEGACY_CIPHER;
274
-			}
275
-		}
276
-
277
-		return $cipher;
278
-	}
279
-
280
-	/**
281
-	 * get key size depending on the cipher
282
-	 *
283
-	 * @param string $cipher
284
-	 * @return int
285
-	 * @throws \InvalidArgumentException
286
-	 */
287
-	protected function getKeySize($cipher) {
288
-		if(isset($this->supportedCiphersAndKeySize[$cipher])) {
289
-			return $this->supportedCiphersAndKeySize[$cipher];
290
-		}
291
-
292
-		throw new \InvalidArgumentException(
293
-			sprintf(
294
-					'Unsupported cipher (%s) defined.',
295
-					$cipher
296
-			)
297
-		);
298
-	}
299
-
300
-	/**
301
-	 * get legacy cipher
302
-	 *
303
-	 * @return string
304
-	 */
305
-	public function getLegacyCipher() {
306
-		return self::LEGACY_CIPHER;
307
-	}
308
-
309
-	/**
310
-	 * @param string $encryptedContent
311
-	 * @param string $iv
312
-	 * @return string
313
-	 */
314
-	private function concatIV($encryptedContent, $iv) {
315
-		return $encryptedContent . '00iv00' . $iv;
316
-	}
317
-
318
-	/**
319
-	 * @param string $encryptedContent
320
-	 * @param string $signature
321
-	 * @return string
322
-	 */
323
-	private function concatSig($encryptedContent, $signature) {
324
-		return $encryptedContent . '00sig00' . $signature;
325
-	}
326
-
327
-	/**
328
-	 * Note: This is _NOT_ a padding used for encryption purposes. It is solely
329
-	 * used to achieve the PHP stream size. It has _NOTHING_ to do with the
330
-	 * encrypted content and is not used in any crypto primitive.
331
-	 *
332
-	 * @param string $data
333
-	 * @return string
334
-	 */
335
-	private function addPadding($data) {
336
-		return $data . 'xxx';
337
-	}
338
-
339
-	/**
340
-	 * generate password hash used to encrypt the users private key
341
-	 *
342
-	 * @param string $password
343
-	 * @param string $cipher
344
-	 * @param string $uid only used for user keys
345
-	 * @return string
346
-	 */
347
-	protected function generatePasswordHash($password, $cipher, $uid = '') {
348
-		$instanceId = $this->config->getSystemValue('instanceid');
349
-		$instanceSecret = $this->config->getSystemValue('secret');
350
-		$salt = hash('sha256', $uid . $instanceId . $instanceSecret, true);
351
-		$keySize = $this->getKeySize($cipher);
352
-
353
-		$hash = hash_pbkdf2(
354
-			'sha256',
355
-			$password,
356
-			$salt,
357
-			100000,
358
-			$keySize,
359
-			true
360
-		);
361
-
362
-		return $hash;
363
-	}
364
-
365
-	/**
366
-	 * encrypt private key
367
-	 *
368
-	 * @param string $privateKey
369
-	 * @param string $password
370
-	 * @param string $uid for regular users, empty for system keys
371
-	 * @return false|string
372
-	 */
373
-	public function encryptPrivateKey($privateKey, $password, $uid = '') {
374
-		$cipher = $this->getCipher();
375
-		$hash = $this->generatePasswordHash($password, $cipher, $uid);
376
-		$encryptedKey = $this->symmetricEncryptFileContent(
377
-			$privateKey,
378
-			$hash,
379
-			0,
380
-			0
381
-		);
382
-
383
-		return $encryptedKey;
384
-	}
385
-
386
-	/**
387
-	 * @param string $privateKey
388
-	 * @param string $password
389
-	 * @param string $uid for regular users, empty for system keys
390
-	 * @return false|string
391
-	 */
392
-	public function decryptPrivateKey($privateKey, $password = '', $uid = '') {
393
-
394
-		$header = $this->parseHeader($privateKey);
395
-
396
-		if (isset($header['cipher'])) {
397
-			$cipher = $header['cipher'];
398
-		} else {
399
-			$cipher = self::LEGACY_CIPHER;
400
-		}
401
-
402
-		if (isset($header['keyFormat'])) {
403
-			$keyFormat = $header['keyFormat'];
404
-		} else {
405
-			$keyFormat = self::LEGACY_KEY_FORMAT;
406
-		}
407
-
408
-		if ($keyFormat === 'hash') {
409
-			$password = $this->generatePasswordHash($password, $cipher, $uid);
410
-		}
411
-
412
-		// If we found a header we need to remove it from the key we want to decrypt
413
-		if (!empty($header)) {
414
-			$privateKey = substr($privateKey,
415
-				strpos($privateKey,
416
-					self::HEADER_END) + strlen(self::HEADER_END));
417
-		}
418
-
419
-		$plainKey = $this->symmetricDecryptFileContent(
420
-			$privateKey,
421
-			$password,
422
-			$cipher,
423
-			0
424
-		);
425
-
426
-		if ($this->isValidPrivateKey($plainKey) === false) {
427
-			return false;
428
-		}
429
-
430
-		return $plainKey;
431
-	}
432
-
433
-	/**
434
-	 * check if it is a valid private key
435
-	 *
436
-	 * @param string $plainKey
437
-	 * @return bool
438
-	 */
439
-	protected function isValidPrivateKey($plainKey) {
440
-		$res = openssl_get_privatekey($plainKey);
441
-		if (is_resource($res)) {
442
-			$sslInfo = openssl_pkey_get_details($res);
443
-			if (isset($sslInfo['key'])) {
444
-				return true;
445
-			}
446
-		}
447
-
448
-		return false;
449
-	}
450
-
451
-	/**
452
-	 * @param string $keyFileContents
453
-	 * @param string $passPhrase
454
-	 * @param string $cipher
455
-	 * @param int $version
456
-	 * @param int $position
457
-	 * @return string
458
-	 * @throws DecryptionFailedException
459
-	 */
460
-	public function symmetricDecryptFileContent($keyFileContents, $passPhrase, $cipher = self::DEFAULT_CIPHER, $version = 0, $position = 0) {
461
-		$catFile = $this->splitMetaData($keyFileContents, $cipher);
462
-
463
-		if ($catFile['signature'] !== false) {
464
-			$this->checkSignature($catFile['encrypted'], $passPhrase.$version.$position, $catFile['signature']);
465
-		}
466
-
467
-		return $this->decrypt($catFile['encrypted'],
468
-			$catFile['iv'],
469
-			$passPhrase,
470
-			$cipher);
471
-	}
472
-
473
-	/**
474
-	 * check for valid signature
475
-	 *
476
-	 * @param string $data
477
-	 * @param string $passPhrase
478
-	 * @param string $expectedSignature
479
-	 * @throws HintException
480
-	 */
481
-	private function checkSignature($data, $passPhrase, $expectedSignature) {
482
-		$signature = $this->createSignature($data, $passPhrase);
483
-		if (!hash_equals($expectedSignature, $signature)) {
484
-			throw new HintException('Bad Signature', $this->l->t('Bad Signature'));
485
-		}
486
-	}
487
-
488
-	/**
489
-	 * create signature
490
-	 *
491
-	 * @param string $data
492
-	 * @param string $passPhrase
493
-	 * @return string
494
-	 */
495
-	private function createSignature($data, $passPhrase) {
496
-		$passPhrase = hash('sha512', $passPhrase . 'a', true);
497
-		$signature = hash_hmac('sha256', $data, $passPhrase);
498
-		return $signature;
499
-	}
500
-
501
-
502
-	/**
503
-	 * remove padding
504
-	 *
505
-	 * @param string $padded
506
-	 * @param bool $hasSignature did the block contain a signature, in this case we use a different padding
507
-	 * @return string|false
508
-	 */
509
-	private function removePadding($padded, $hasSignature = false) {
510
-		if ($hasSignature === false && substr($padded, -2) === 'xx') {
511
-			return substr($padded, 0, -2);
512
-		} elseif ($hasSignature === true && substr($padded, -3) === 'xxx') {
513
-			return substr($padded, 0, -3);
514
-		}
515
-		return false;
516
-	}
517
-
518
-	/**
519
-	 * split meta data from encrypted file
520
-	 * Note: for now, we assume that the meta data always start with the iv
521
-	 *       followed by the signature, if available
522
-	 *
523
-	 * @param string $catFile
524
-	 * @param string $cipher
525
-	 * @return array
526
-	 */
527
-	private function splitMetaData($catFile, $cipher) {
528
-		if ($this->hasSignature($catFile, $cipher)) {
529
-			$catFile = $this->removePadding($catFile, true);
530
-			$meta = substr($catFile, -93);
531
-			$iv = substr($meta, strlen('00iv00'), 16);
532
-			$sig = substr($meta, 22 + strlen('00sig00'));
533
-			$encrypted = substr($catFile, 0, -93);
534
-		} else {
535
-			$catFile = $this->removePadding($catFile);
536
-			$meta = substr($catFile, -22);
537
-			$iv = substr($meta, -16);
538
-			$sig = false;
539
-			$encrypted = substr($catFile, 0, -22);
540
-		}
541
-
542
-		return [
543
-			'encrypted' => $encrypted,
544
-			'iv' => $iv,
545
-			'signature' => $sig
546
-		];
547
-	}
548
-
549
-	/**
550
-	 * check if encrypted block is signed
551
-	 *
552
-	 * @param string $catFile
553
-	 * @param string $cipher
554
-	 * @return bool
555
-	 * @throws HintException
556
-	 */
557
-	private function hasSignature($catFile, $cipher) {
558
-		$meta = substr($catFile, -93);
559
-		$signaturePosition = strpos($meta, '00sig00');
560
-
561
-		// enforce signature for the new 'CTR' ciphers
562
-		if ($signaturePosition === false && strpos(strtolower($cipher), 'ctr') !== false) {
563
-			throw new HintException('Missing Signature', $this->l->t('Missing Signature'));
564
-		}
565
-
566
-		return ($signaturePosition !== false);
567
-	}
568
-
569
-
570
-	/**
571
-	 * @param string $encryptedContent
572
-	 * @param string $iv
573
-	 * @param string $passPhrase
574
-	 * @param string $cipher
575
-	 * @return string
576
-	 * @throws DecryptionFailedException
577
-	 */
578
-	private function decrypt($encryptedContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) {
579
-		$plainContent = openssl_decrypt($encryptedContent,
580
-			$cipher,
581
-			$passPhrase,
582
-			false,
583
-			$iv);
584
-
585
-		if ($plainContent) {
586
-			return $plainContent;
587
-		} else {
588
-			throw new DecryptionFailedException('Encryption library: Decryption (symmetric) of content failed: ' . openssl_error_string());
589
-		}
590
-	}
591
-
592
-	/**
593
-	 * @param string $data
594
-	 * @return array
595
-	 */
596
-	protected function parseHeader($data) {
597
-		$result = [];
598
-
599
-		if (substr($data, 0, strlen(self::HEADER_START)) === self::HEADER_START) {
600
-			$endAt = strpos($data, self::HEADER_END);
601
-			$header = substr($data, 0, $endAt + strlen(self::HEADER_END));
602
-
603
-			// +1 not to start with an ':' which would result in empty element at the beginning
604
-			$exploded = explode(':',
605
-				substr($header, strlen(self::HEADER_START) + 1));
606
-
607
-			$element = array_shift($exploded);
608
-
609
-			while ($element != self::HEADER_END) {
610
-				$result[$element] = array_shift($exploded);
611
-				$element = array_shift($exploded);
612
-			}
613
-		}
614
-
615
-		return $result;
616
-	}
617
-
618
-	/**
619
-	 * generate initialization vector
620
-	 *
621
-	 * @return string
622
-	 * @throws GenericEncryptionException
623
-	 */
624
-	private function generateIv() {
625
-		return random_bytes(16);
626
-	}
627
-
628
-	/**
629
-	 * Generate a cryptographically secure pseudo-random 256-bit ASCII key, used
630
-	 * as file key
631
-	 *
632
-	 * @return string
633
-	 * @throws \Exception
634
-	 */
635
-	public function generateFileKey() {
636
-		return random_bytes(32);
637
-	}
638
-
639
-	/**
640
-	 * @param $encKeyFile
641
-	 * @param $shareKey
642
-	 * @param $privateKey
643
-	 * @return string
644
-	 * @throws MultiKeyDecryptException
645
-	 */
646
-	public function multiKeyDecrypt($encKeyFile, $shareKey, $privateKey) {
647
-		if (!$encKeyFile) {
648
-			throw new MultiKeyDecryptException('Cannot multikey decrypt empty plain content');
649
-		}
650
-
651
-		if (openssl_open($encKeyFile, $plainContent, $shareKey, $privateKey)) {
652
-			return $plainContent;
653
-		} else {
654
-			throw new MultiKeyDecryptException('multikeydecrypt with share key failed:' . openssl_error_string());
655
-		}
656
-	}
657
-
658
-	/**
659
-	 * @param string $plainContent
660
-	 * @param array $keyFiles
661
-	 * @return array
662
-	 * @throws MultiKeyEncryptException
663
-	 */
664
-	public function multiKeyEncrypt($plainContent, array $keyFiles) {
665
-		// openssl_seal returns false without errors if plaincontent is empty
666
-		// so trigger our own error
667
-		if (empty($plainContent)) {
668
-			throw new MultiKeyEncryptException('Cannot multikeyencrypt empty plain content');
669
-		}
670
-
671
-		// Set empty vars to be set by openssl by reference
672
-		$sealed = '';
673
-		$shareKeys = [];
674
-		$mappedShareKeys = [];
675
-
676
-		if (openssl_seal($plainContent, $sealed, $shareKeys, $keyFiles)) {
677
-			$i = 0;
678
-
679
-			// Ensure each shareKey is labelled with its corresponding key id
680
-			foreach ($keyFiles as $userId => $publicKey) {
681
-				$mappedShareKeys[$userId] = $shareKeys[$i];
682
-				$i++;
683
-			}
684
-
685
-			return [
686
-				'keys' => $mappedShareKeys,
687
-				'data' => $sealed
688
-			];
689
-		} else {
690
-			throw new MultiKeyEncryptException('multikeyencryption failed ' . openssl_error_string());
691
-		}
692
-	}
57
+    const DEFAULT_CIPHER = 'AES-256-CTR';
58
+    // default cipher from old ownCloud versions
59
+    const LEGACY_CIPHER = 'AES-128-CFB';
60
+
61
+    // default key format, old ownCloud version encrypted the private key directly
62
+    // with the user password
63
+    const LEGACY_KEY_FORMAT = 'password';
64
+
65
+    const HEADER_START = 'HBEGIN';
66
+    const HEADER_END = 'HEND';
67
+
68
+    /** @var ILogger */
69
+    private $logger;
70
+
71
+    /** @var string */
72
+    private $user;
73
+
74
+    /** @var IConfig */
75
+    private $config;
76
+
77
+    /** @var array */
78
+    private $supportedKeyFormats;
79
+
80
+    /** @var IL10N */
81
+    private $l;
82
+
83
+    /** @var array */
84
+    private $supportedCiphersAndKeySize = [
85
+        'AES-256-CTR' => 32,
86
+        'AES-128-CTR' => 16,
87
+        'AES-256-CFB' => 32,
88
+        'AES-128-CFB' => 16,
89
+    ];
90
+
91
+    /**
92
+     * @param ILogger $logger
93
+     * @param IUserSession $userSession
94
+     * @param IConfig $config
95
+     * @param IL10N $l
96
+     */
97
+    public function __construct(ILogger $logger, IUserSession $userSession, IConfig $config, IL10N $l) {
98
+        $this->logger = $logger;
99
+        $this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : '"no user given"';
100
+        $this->config = $config;
101
+        $this->l = $l;
102
+        $this->supportedKeyFormats = ['hash', 'password'];
103
+    }
104
+
105
+    /**
106
+     * create new private/public key-pair for user
107
+     *
108
+     * @return array|bool
109
+     */
110
+    public function createKeyPair() {
111
+
112
+        $log = $this->logger;
113
+        $res = $this->getOpenSSLPKey();
114
+
115
+        if (!$res) {
116
+            $log->error("Encryption Library couldn't generate users key-pair for {$this->user}",
117
+                ['app' => 'encryption']);
118
+
119
+            if (openssl_error_string()) {
120
+                $log->error('Encryption library openssl_pkey_new() fails: ' . openssl_error_string(),
121
+                    ['app' => 'encryption']);
122
+            }
123
+        } elseif (openssl_pkey_export($res,
124
+            $privateKey,
125
+            null,
126
+            $this->getOpenSSLConfig())) {
127
+            $keyDetails = openssl_pkey_get_details($res);
128
+            $publicKey = $keyDetails['key'];
129
+
130
+            return [
131
+                'publicKey' => $publicKey,
132
+                'privateKey' => $privateKey
133
+            ];
134
+        }
135
+        $log->error('Encryption library couldn\'t export users private key, please check your servers OpenSSL configuration.' . $this->user,
136
+            ['app' => 'encryption']);
137
+        if (openssl_error_string()) {
138
+            $log->error('Encryption Library:' . openssl_error_string(),
139
+                ['app' => 'encryption']);
140
+        }
141
+
142
+        return false;
143
+    }
144
+
145
+    /**
146
+     * Generates a new private key
147
+     *
148
+     * @return resource
149
+     */
150
+    public function getOpenSSLPKey() {
151
+        $config = $this->getOpenSSLConfig();
152
+        return openssl_pkey_new($config);
153
+    }
154
+
155
+    /**
156
+     * get openSSL Config
157
+     *
158
+     * @return array
159
+     */
160
+    private function getOpenSSLConfig() {
161
+        $config = ['private_key_bits' => 4096];
162
+        $config = array_merge(
163
+            $config,
164
+            $this->config->getSystemValue('openssl', [])
165
+        );
166
+        return $config;
167
+    }
168
+
169
+    /**
170
+     * @param string $plainContent
171
+     * @param string $passPhrase
172
+     * @param int $version
173
+     * @param int $position
174
+     * @return false|string
175
+     * @throws EncryptionFailedException
176
+     */
177
+    public function symmetricEncryptFileContent($plainContent, $passPhrase, $version, $position) {
178
+
179
+        if (!$plainContent) {
180
+            $this->logger->error('Encryption Library, symmetrical encryption failed no content given',
181
+                ['app' => 'encryption']);
182
+            return false;
183
+        }
184
+
185
+        $iv = $this->generateIv();
186
+
187
+        $encryptedContent = $this->encrypt($plainContent,
188
+            $iv,
189
+            $passPhrase,
190
+            $this->getCipher());
191
+
192
+        // Create a signature based on the key as well as the current version
193
+        $sig = $this->createSignature($encryptedContent, $passPhrase.$version.$position);
194
+
195
+        // combine content to encrypt the IV identifier and actual IV
196
+        $catFile = $this->concatIV($encryptedContent, $iv);
197
+        $catFile = $this->concatSig($catFile, $sig);
198
+        $padded = $this->addPadding($catFile);
199
+
200
+        return $padded;
201
+    }
202
+
203
+    /**
204
+     * generate header for encrypted file
205
+     *
206
+     * @param string $keyFormat (can be 'hash' or 'password')
207
+     * @return string
208
+     * @throws \InvalidArgumentException
209
+     */
210
+    public function generateHeader($keyFormat = 'hash') {
211
+
212
+        if (in_array($keyFormat, $this->supportedKeyFormats, true) === false) {
213
+            throw new \InvalidArgumentException('key format "' . $keyFormat . '" is not supported');
214
+        }
215
+
216
+        $cipher = $this->getCipher();
217
+
218
+        $header = self::HEADER_START
219
+            . ':cipher:' . $cipher
220
+            . ':keyFormat:' . $keyFormat
221
+            . ':' . self::HEADER_END;
222
+
223
+        return $header;
224
+    }
225
+
226
+    /**
227
+     * @param string $plainContent
228
+     * @param string $iv
229
+     * @param string $passPhrase
230
+     * @param string $cipher
231
+     * @return string
232
+     * @throws EncryptionFailedException
233
+     */
234
+    private function encrypt($plainContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) {
235
+        $encryptedContent = openssl_encrypt($plainContent,
236
+            $cipher,
237
+            $passPhrase,
238
+            false,
239
+            $iv);
240
+
241
+        if (!$encryptedContent) {
242
+            $error = 'Encryption (symmetric) of content failed';
243
+            $this->logger->error($error . openssl_error_string(),
244
+                ['app' => 'encryption']);
245
+            throw new EncryptionFailedException($error);
246
+        }
247
+
248
+        return $encryptedContent;
249
+    }
250
+
251
+    /**
252
+     * return Cipher either from config.php or the default cipher defined in
253
+     * this class
254
+     *
255
+     * @return string
256
+     */
257
+    public function getCipher() {
258
+        $cipher = $this->config->getSystemValue('cipher', self::DEFAULT_CIPHER);
259
+        if (!isset($this->supportedCiphersAndKeySize[$cipher])) {
260
+            $this->logger->warning(
261
+                    sprintf(
262
+                            'Unsupported cipher (%s) defined in config.php supported. Falling back to %s',
263
+                            $cipher,
264
+                            self::DEFAULT_CIPHER
265
+                    ),
266
+                ['app' => 'encryption']);
267
+            $cipher = self::DEFAULT_CIPHER;
268
+        }
269
+
270
+        // Workaround for OpenSSL 0.9.8. Fallback to an old cipher that should work.
271
+        if(OPENSSL_VERSION_NUMBER < 0x1000101f) {
272
+            if($cipher === 'AES-256-CTR' || $cipher === 'AES-128-CTR') {
273
+                $cipher = self::LEGACY_CIPHER;
274
+            }
275
+        }
276
+
277
+        return $cipher;
278
+    }
279
+
280
+    /**
281
+     * get key size depending on the cipher
282
+     *
283
+     * @param string $cipher
284
+     * @return int
285
+     * @throws \InvalidArgumentException
286
+     */
287
+    protected function getKeySize($cipher) {
288
+        if(isset($this->supportedCiphersAndKeySize[$cipher])) {
289
+            return $this->supportedCiphersAndKeySize[$cipher];
290
+        }
291
+
292
+        throw new \InvalidArgumentException(
293
+            sprintf(
294
+                    'Unsupported cipher (%s) defined.',
295
+                    $cipher
296
+            )
297
+        );
298
+    }
299
+
300
+    /**
301
+     * get legacy cipher
302
+     *
303
+     * @return string
304
+     */
305
+    public function getLegacyCipher() {
306
+        return self::LEGACY_CIPHER;
307
+    }
308
+
309
+    /**
310
+     * @param string $encryptedContent
311
+     * @param string $iv
312
+     * @return string
313
+     */
314
+    private function concatIV($encryptedContent, $iv) {
315
+        return $encryptedContent . '00iv00' . $iv;
316
+    }
317
+
318
+    /**
319
+     * @param string $encryptedContent
320
+     * @param string $signature
321
+     * @return string
322
+     */
323
+    private function concatSig($encryptedContent, $signature) {
324
+        return $encryptedContent . '00sig00' . $signature;
325
+    }
326
+
327
+    /**
328
+     * Note: This is _NOT_ a padding used for encryption purposes. It is solely
329
+     * used to achieve the PHP stream size. It has _NOTHING_ to do with the
330
+     * encrypted content and is not used in any crypto primitive.
331
+     *
332
+     * @param string $data
333
+     * @return string
334
+     */
335
+    private function addPadding($data) {
336
+        return $data . 'xxx';
337
+    }
338
+
339
+    /**
340
+     * generate password hash used to encrypt the users private key
341
+     *
342
+     * @param string $password
343
+     * @param string $cipher
344
+     * @param string $uid only used for user keys
345
+     * @return string
346
+     */
347
+    protected function generatePasswordHash($password, $cipher, $uid = '') {
348
+        $instanceId = $this->config->getSystemValue('instanceid');
349
+        $instanceSecret = $this->config->getSystemValue('secret');
350
+        $salt = hash('sha256', $uid . $instanceId . $instanceSecret, true);
351
+        $keySize = $this->getKeySize($cipher);
352
+
353
+        $hash = hash_pbkdf2(
354
+            'sha256',
355
+            $password,
356
+            $salt,
357
+            100000,
358
+            $keySize,
359
+            true
360
+        );
361
+
362
+        return $hash;
363
+    }
364
+
365
+    /**
366
+     * encrypt private key
367
+     *
368
+     * @param string $privateKey
369
+     * @param string $password
370
+     * @param string $uid for regular users, empty for system keys
371
+     * @return false|string
372
+     */
373
+    public function encryptPrivateKey($privateKey, $password, $uid = '') {
374
+        $cipher = $this->getCipher();
375
+        $hash = $this->generatePasswordHash($password, $cipher, $uid);
376
+        $encryptedKey = $this->symmetricEncryptFileContent(
377
+            $privateKey,
378
+            $hash,
379
+            0,
380
+            0
381
+        );
382
+
383
+        return $encryptedKey;
384
+    }
385
+
386
+    /**
387
+     * @param string $privateKey
388
+     * @param string $password
389
+     * @param string $uid for regular users, empty for system keys
390
+     * @return false|string
391
+     */
392
+    public function decryptPrivateKey($privateKey, $password = '', $uid = '') {
393
+
394
+        $header = $this->parseHeader($privateKey);
395
+
396
+        if (isset($header['cipher'])) {
397
+            $cipher = $header['cipher'];
398
+        } else {
399
+            $cipher = self::LEGACY_CIPHER;
400
+        }
401
+
402
+        if (isset($header['keyFormat'])) {
403
+            $keyFormat = $header['keyFormat'];
404
+        } else {
405
+            $keyFormat = self::LEGACY_KEY_FORMAT;
406
+        }
407
+
408
+        if ($keyFormat === 'hash') {
409
+            $password = $this->generatePasswordHash($password, $cipher, $uid);
410
+        }
411
+
412
+        // If we found a header we need to remove it from the key we want to decrypt
413
+        if (!empty($header)) {
414
+            $privateKey = substr($privateKey,
415
+                strpos($privateKey,
416
+                    self::HEADER_END) + strlen(self::HEADER_END));
417
+        }
418
+
419
+        $plainKey = $this->symmetricDecryptFileContent(
420
+            $privateKey,
421
+            $password,
422
+            $cipher,
423
+            0
424
+        );
425
+
426
+        if ($this->isValidPrivateKey($plainKey) === false) {
427
+            return false;
428
+        }
429
+
430
+        return $plainKey;
431
+    }
432
+
433
+    /**
434
+     * check if it is a valid private key
435
+     *
436
+     * @param string $plainKey
437
+     * @return bool
438
+     */
439
+    protected function isValidPrivateKey($plainKey) {
440
+        $res = openssl_get_privatekey($plainKey);
441
+        if (is_resource($res)) {
442
+            $sslInfo = openssl_pkey_get_details($res);
443
+            if (isset($sslInfo['key'])) {
444
+                return true;
445
+            }
446
+        }
447
+
448
+        return false;
449
+    }
450
+
451
+    /**
452
+     * @param string $keyFileContents
453
+     * @param string $passPhrase
454
+     * @param string $cipher
455
+     * @param int $version
456
+     * @param int $position
457
+     * @return string
458
+     * @throws DecryptionFailedException
459
+     */
460
+    public function symmetricDecryptFileContent($keyFileContents, $passPhrase, $cipher = self::DEFAULT_CIPHER, $version = 0, $position = 0) {
461
+        $catFile = $this->splitMetaData($keyFileContents, $cipher);
462
+
463
+        if ($catFile['signature'] !== false) {
464
+            $this->checkSignature($catFile['encrypted'], $passPhrase.$version.$position, $catFile['signature']);
465
+        }
466
+
467
+        return $this->decrypt($catFile['encrypted'],
468
+            $catFile['iv'],
469
+            $passPhrase,
470
+            $cipher);
471
+    }
472
+
473
+    /**
474
+     * check for valid signature
475
+     *
476
+     * @param string $data
477
+     * @param string $passPhrase
478
+     * @param string $expectedSignature
479
+     * @throws HintException
480
+     */
481
+    private function checkSignature($data, $passPhrase, $expectedSignature) {
482
+        $signature = $this->createSignature($data, $passPhrase);
483
+        if (!hash_equals($expectedSignature, $signature)) {
484
+            throw new HintException('Bad Signature', $this->l->t('Bad Signature'));
485
+        }
486
+    }
487
+
488
+    /**
489
+     * create signature
490
+     *
491
+     * @param string $data
492
+     * @param string $passPhrase
493
+     * @return string
494
+     */
495
+    private function createSignature($data, $passPhrase) {
496
+        $passPhrase = hash('sha512', $passPhrase . 'a', true);
497
+        $signature = hash_hmac('sha256', $data, $passPhrase);
498
+        return $signature;
499
+    }
500
+
501
+
502
+    /**
503
+     * remove padding
504
+     *
505
+     * @param string $padded
506
+     * @param bool $hasSignature did the block contain a signature, in this case we use a different padding
507
+     * @return string|false
508
+     */
509
+    private function removePadding($padded, $hasSignature = false) {
510
+        if ($hasSignature === false && substr($padded, -2) === 'xx') {
511
+            return substr($padded, 0, -2);
512
+        } elseif ($hasSignature === true && substr($padded, -3) === 'xxx') {
513
+            return substr($padded, 0, -3);
514
+        }
515
+        return false;
516
+    }
517
+
518
+    /**
519
+     * split meta data from encrypted file
520
+     * Note: for now, we assume that the meta data always start with the iv
521
+     *       followed by the signature, if available
522
+     *
523
+     * @param string $catFile
524
+     * @param string $cipher
525
+     * @return array
526
+     */
527
+    private function splitMetaData($catFile, $cipher) {
528
+        if ($this->hasSignature($catFile, $cipher)) {
529
+            $catFile = $this->removePadding($catFile, true);
530
+            $meta = substr($catFile, -93);
531
+            $iv = substr($meta, strlen('00iv00'), 16);
532
+            $sig = substr($meta, 22 + strlen('00sig00'));
533
+            $encrypted = substr($catFile, 0, -93);
534
+        } else {
535
+            $catFile = $this->removePadding($catFile);
536
+            $meta = substr($catFile, -22);
537
+            $iv = substr($meta, -16);
538
+            $sig = false;
539
+            $encrypted = substr($catFile, 0, -22);
540
+        }
541
+
542
+        return [
543
+            'encrypted' => $encrypted,
544
+            'iv' => $iv,
545
+            'signature' => $sig
546
+        ];
547
+    }
548
+
549
+    /**
550
+     * check if encrypted block is signed
551
+     *
552
+     * @param string $catFile
553
+     * @param string $cipher
554
+     * @return bool
555
+     * @throws HintException
556
+     */
557
+    private function hasSignature($catFile, $cipher) {
558
+        $meta = substr($catFile, -93);
559
+        $signaturePosition = strpos($meta, '00sig00');
560
+
561
+        // enforce signature for the new 'CTR' ciphers
562
+        if ($signaturePosition === false && strpos(strtolower($cipher), 'ctr') !== false) {
563
+            throw new HintException('Missing Signature', $this->l->t('Missing Signature'));
564
+        }
565
+
566
+        return ($signaturePosition !== false);
567
+    }
568
+
569
+
570
+    /**
571
+     * @param string $encryptedContent
572
+     * @param string $iv
573
+     * @param string $passPhrase
574
+     * @param string $cipher
575
+     * @return string
576
+     * @throws DecryptionFailedException
577
+     */
578
+    private function decrypt($encryptedContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) {
579
+        $plainContent = openssl_decrypt($encryptedContent,
580
+            $cipher,
581
+            $passPhrase,
582
+            false,
583
+            $iv);
584
+
585
+        if ($plainContent) {
586
+            return $plainContent;
587
+        } else {
588
+            throw new DecryptionFailedException('Encryption library: Decryption (symmetric) of content failed: ' . openssl_error_string());
589
+        }
590
+    }
591
+
592
+    /**
593
+     * @param string $data
594
+     * @return array
595
+     */
596
+    protected function parseHeader($data) {
597
+        $result = [];
598
+
599
+        if (substr($data, 0, strlen(self::HEADER_START)) === self::HEADER_START) {
600
+            $endAt = strpos($data, self::HEADER_END);
601
+            $header = substr($data, 0, $endAt + strlen(self::HEADER_END));
602
+
603
+            // +1 not to start with an ':' which would result in empty element at the beginning
604
+            $exploded = explode(':',
605
+                substr($header, strlen(self::HEADER_START) + 1));
606
+
607
+            $element = array_shift($exploded);
608
+
609
+            while ($element != self::HEADER_END) {
610
+                $result[$element] = array_shift($exploded);
611
+                $element = array_shift($exploded);
612
+            }
613
+        }
614
+
615
+        return $result;
616
+    }
617
+
618
+    /**
619
+     * generate initialization vector
620
+     *
621
+     * @return string
622
+     * @throws GenericEncryptionException
623
+     */
624
+    private function generateIv() {
625
+        return random_bytes(16);
626
+    }
627
+
628
+    /**
629
+     * Generate a cryptographically secure pseudo-random 256-bit ASCII key, used
630
+     * as file key
631
+     *
632
+     * @return string
633
+     * @throws \Exception
634
+     */
635
+    public function generateFileKey() {
636
+        return random_bytes(32);
637
+    }
638
+
639
+    /**
640
+     * @param $encKeyFile
641
+     * @param $shareKey
642
+     * @param $privateKey
643
+     * @return string
644
+     * @throws MultiKeyDecryptException
645
+     */
646
+    public function multiKeyDecrypt($encKeyFile, $shareKey, $privateKey) {
647
+        if (!$encKeyFile) {
648
+            throw new MultiKeyDecryptException('Cannot multikey decrypt empty plain content');
649
+        }
650
+
651
+        if (openssl_open($encKeyFile, $plainContent, $shareKey, $privateKey)) {
652
+            return $plainContent;
653
+        } else {
654
+            throw new MultiKeyDecryptException('multikeydecrypt with share key failed:' . openssl_error_string());
655
+        }
656
+    }
657
+
658
+    /**
659
+     * @param string $plainContent
660
+     * @param array $keyFiles
661
+     * @return array
662
+     * @throws MultiKeyEncryptException
663
+     */
664
+    public function multiKeyEncrypt($plainContent, array $keyFiles) {
665
+        // openssl_seal returns false without errors if plaincontent is empty
666
+        // so trigger our own error
667
+        if (empty($plainContent)) {
668
+            throw new MultiKeyEncryptException('Cannot multikeyencrypt empty plain content');
669
+        }
670
+
671
+        // Set empty vars to be set by openssl by reference
672
+        $sealed = '';
673
+        $shareKeys = [];
674
+        $mappedShareKeys = [];
675
+
676
+        if (openssl_seal($plainContent, $sealed, $shareKeys, $keyFiles)) {
677
+            $i = 0;
678
+
679
+            // Ensure each shareKey is labelled with its corresponding key id
680
+            foreach ($keyFiles as $userId => $publicKey) {
681
+                $mappedShareKeys[$userId] = $shareKeys[$i];
682
+                $i++;
683
+            }
684
+
685
+            return [
686
+                'keys' => $mappedShareKeys,
687
+                'data' => $sealed
688
+            ];
689
+        } else {
690
+            throw new MultiKeyEncryptException('multikeyencryption failed ' . openssl_error_string());
691
+        }
692
+    }
693 693
 }
694 694
 
Please login to merge, or discard this patch.
apps/encryption/lib/Crypto/DecryptAll.php 1 patch
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -35,127 +35,127 @@
 block discarded – undo
35 35
 
36 36
 class DecryptAll {
37 37
 
38
-	/** @var Util  */
39
-	protected $util;
40
-
41
-	/** @var QuestionHelper  */
42
-	protected $questionHelper;
43
-
44
-	/** @var  Crypt */
45
-	protected $crypt;
46
-
47
-	/** @var  KeyManager */
48
-	protected $keyManager;
49
-
50
-	/** @var Session  */
51
-	protected $session;
52
-
53
-	/**
54
-	 * @param Util $util
55
-	 * @param KeyManager $keyManager
56
-	 * @param Crypt $crypt
57
-	 * @param Session $session
58
-	 * @param QuestionHelper $questionHelper
59
-	 */
60
-	public function __construct(
61
-		Util $util,
62
-		KeyManager $keyManager,
63
-		Crypt $crypt,
64
-		Session $session,
65
-		QuestionHelper $questionHelper
66
-	) {
67
-		$this->util = $util;
68
-		$this->keyManager = $keyManager;
69
-		$this->crypt = $crypt;
70
-		$this->session = $session;
71
-		$this->questionHelper = $questionHelper;
72
-	}
73
-
74
-	/**
75
-	 * prepare encryption module to decrypt all files
76
-	 *
77
-	 * @param InputInterface $input
78
-	 * @param OutputInterface $output
79
-	 * @param $user
80
-	 * @return bool
81
-	 */
82
-	public function prepare(InputInterface $input, OutputInterface $output, $user) {
83
-
84
-		$question = new Question('Please enter the recovery key password: ');
85
-
86
-		if($this->util->isMasterKeyEnabled()) {
87
-			$output->writeln('Use master key to decrypt all files');
88
-			$user = $this->keyManager->getMasterKeyId();
89
-			$password =$this->keyManager->getMasterKeyPassword();
90
-		} else {
91
-			$recoveryKeyId = $this->keyManager->getRecoveryKeyId();
92
-			if (!empty($user)) {
93
-				$output->writeln('You can only decrypt the users files if you know');
94
-				$output->writeln('the users password or if he activated the recovery key.');
95
-				$output->writeln('');
96
-				$questionUseLoginPassword = new ConfirmationQuestion(
97
-					'Do you want to use the users login password to decrypt all files? (y/n) ',
98
-					false
99
-				);
100
-				$useLoginPassword = $this->questionHelper->ask($input, $output, $questionUseLoginPassword);
101
-				if ($useLoginPassword) {
102
-					$question = new Question('Please enter the user\'s login password: ');
103
-				} else if ($this->util->isRecoveryEnabledForUser($user) === false) {
104
-					$output->writeln('No recovery key available for user ' . $user);
105
-					return false;
106
-				} else {
107
-					$user = $recoveryKeyId;
108
-				}
109
-			} else {
110
-				$output->writeln('You can only decrypt the files of all users if the');
111
-				$output->writeln('recovery key is enabled by the admin and activated by the users.');
112
-				$output->writeln('');
113
-				$user = $recoveryKeyId;
114
-			}
115
-
116
-			$question->setHidden(true);
117
-			$question->setHiddenFallback(false);
118
-			$password = $this->questionHelper->ask($input, $output, $question);
119
-		}
120
-
121
-		$privateKey = $this->getPrivateKey($user, $password);
122
-		if ($privateKey !== false) {
123
-			$this->updateSession($user, $privateKey);
124
-			return true;
125
-		} else {
126
-			$output->writeln('Could not decrypt private key, maybe you entered the wrong password?');
127
-		}
128
-
129
-
130
-		return false;
131
-	}
132
-
133
-	/**
134
-	 * get the private key which will be used to decrypt all files
135
-	 *
136
-	 * @param string $user
137
-	 * @param string $password
138
-	 * @return bool|string
139
-	 * @throws \OCA\Encryption\Exceptions\PrivateKeyMissingException
140
-	 */
141
-	protected function getPrivateKey($user, $password) {
142
-		$recoveryKeyId = $this->keyManager->getRecoveryKeyId();
143
-		$masterKeyId = $this->keyManager->getMasterKeyId();
144
-		if ($user === $recoveryKeyId) {
145
-			$recoveryKey = $this->keyManager->getSystemPrivateKey($recoveryKeyId);
146
-			$privateKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
147
-		} elseif ($user === $masterKeyId) {
148
-			$masterKey = $this->keyManager->getSystemPrivateKey($masterKeyId);
149
-			$privateKey = $this->crypt->decryptPrivateKey($masterKey, $password, $masterKeyId);
150
-		} else {
151
-			$userKey = $this->keyManager->getPrivateKey($user);
152
-			$privateKey = $this->crypt->decryptPrivateKey($userKey, $password, $user);
153
-		}
154
-
155
-		return $privateKey;
156
-	}
157
-
158
-	protected function updateSession($user, $privateKey) {
159
-		$this->session->prepareDecryptAll($user, $privateKey);
160
-	}
38
+    /** @var Util  */
39
+    protected $util;
40
+
41
+    /** @var QuestionHelper  */
42
+    protected $questionHelper;
43
+
44
+    /** @var  Crypt */
45
+    protected $crypt;
46
+
47
+    /** @var  KeyManager */
48
+    protected $keyManager;
49
+
50
+    /** @var Session  */
51
+    protected $session;
52
+
53
+    /**
54
+     * @param Util $util
55
+     * @param KeyManager $keyManager
56
+     * @param Crypt $crypt
57
+     * @param Session $session
58
+     * @param QuestionHelper $questionHelper
59
+     */
60
+    public function __construct(
61
+        Util $util,
62
+        KeyManager $keyManager,
63
+        Crypt $crypt,
64
+        Session $session,
65
+        QuestionHelper $questionHelper
66
+    ) {
67
+        $this->util = $util;
68
+        $this->keyManager = $keyManager;
69
+        $this->crypt = $crypt;
70
+        $this->session = $session;
71
+        $this->questionHelper = $questionHelper;
72
+    }
73
+
74
+    /**
75
+     * prepare encryption module to decrypt all files
76
+     *
77
+     * @param InputInterface $input
78
+     * @param OutputInterface $output
79
+     * @param $user
80
+     * @return bool
81
+     */
82
+    public function prepare(InputInterface $input, OutputInterface $output, $user) {
83
+
84
+        $question = new Question('Please enter the recovery key password: ');
85
+
86
+        if($this->util->isMasterKeyEnabled()) {
87
+            $output->writeln('Use master key to decrypt all files');
88
+            $user = $this->keyManager->getMasterKeyId();
89
+            $password =$this->keyManager->getMasterKeyPassword();
90
+        } else {
91
+            $recoveryKeyId = $this->keyManager->getRecoveryKeyId();
92
+            if (!empty($user)) {
93
+                $output->writeln('You can only decrypt the users files if you know');
94
+                $output->writeln('the users password or if he activated the recovery key.');
95
+                $output->writeln('');
96
+                $questionUseLoginPassword = new ConfirmationQuestion(
97
+                    'Do you want to use the users login password to decrypt all files? (y/n) ',
98
+                    false
99
+                );
100
+                $useLoginPassword = $this->questionHelper->ask($input, $output, $questionUseLoginPassword);
101
+                if ($useLoginPassword) {
102
+                    $question = new Question('Please enter the user\'s login password: ');
103
+                } else if ($this->util->isRecoveryEnabledForUser($user) === false) {
104
+                    $output->writeln('No recovery key available for user ' . $user);
105
+                    return false;
106
+                } else {
107
+                    $user = $recoveryKeyId;
108
+                }
109
+            } else {
110
+                $output->writeln('You can only decrypt the files of all users if the');
111
+                $output->writeln('recovery key is enabled by the admin and activated by the users.');
112
+                $output->writeln('');
113
+                $user = $recoveryKeyId;
114
+            }
115
+
116
+            $question->setHidden(true);
117
+            $question->setHiddenFallback(false);
118
+            $password = $this->questionHelper->ask($input, $output, $question);
119
+        }
120
+
121
+        $privateKey = $this->getPrivateKey($user, $password);
122
+        if ($privateKey !== false) {
123
+            $this->updateSession($user, $privateKey);
124
+            return true;
125
+        } else {
126
+            $output->writeln('Could not decrypt private key, maybe you entered the wrong password?');
127
+        }
128
+
129
+
130
+        return false;
131
+    }
132
+
133
+    /**
134
+     * get the private key which will be used to decrypt all files
135
+     *
136
+     * @param string $user
137
+     * @param string $password
138
+     * @return bool|string
139
+     * @throws \OCA\Encryption\Exceptions\PrivateKeyMissingException
140
+     */
141
+    protected function getPrivateKey($user, $password) {
142
+        $recoveryKeyId = $this->keyManager->getRecoveryKeyId();
143
+        $masterKeyId = $this->keyManager->getMasterKeyId();
144
+        if ($user === $recoveryKeyId) {
145
+            $recoveryKey = $this->keyManager->getSystemPrivateKey($recoveryKeyId);
146
+            $privateKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
147
+        } elseif ($user === $masterKeyId) {
148
+            $masterKey = $this->keyManager->getSystemPrivateKey($masterKeyId);
149
+            $privateKey = $this->crypt->decryptPrivateKey($masterKey, $password, $masterKeyId);
150
+        } else {
151
+            $userKey = $this->keyManager->getPrivateKey($user);
152
+            $privateKey = $this->crypt->decryptPrivateKey($userKey, $password, $user);
153
+        }
154
+
155
+        return $privateKey;
156
+    }
157
+
158
+    protected function updateSession($user, $privateKey) {
159
+        $this->session->prepareDecryptAll($user, $privateKey);
160
+    }
161 161
 }
Please login to merge, or discard this patch.
apps/encryption/lib/HookManager.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -28,38 +28,38 @@
 block discarded – undo
28 28
 
29 29
 class HookManager {
30 30
 
31
-	private $hookInstances = [];
31
+    private $hookInstances = [];
32 32
 
33
-	/**
34
-	 * @param array|IHook $instances
35
-	 *        - This accepts either a single instance of IHook or an array of instances of IHook
36
-	 * @return bool
37
-	 */
38
-	public function registerHook($instances) {
39
-		if (is_array($instances)) {
40
-			foreach ($instances as $instance) {
41
-				if (!$instance instanceof IHook) {
42
-					return false;
43
-				}
44
-				$this->hookInstances[] = $instance;
45
-			}
33
+    /**
34
+     * @param array|IHook $instances
35
+     *        - This accepts either a single instance of IHook or an array of instances of IHook
36
+     * @return bool
37
+     */
38
+    public function registerHook($instances) {
39
+        if (is_array($instances)) {
40
+            foreach ($instances as $instance) {
41
+                if (!$instance instanceof IHook) {
42
+                    return false;
43
+                }
44
+                $this->hookInstances[] = $instance;
45
+            }
46 46
 
47
-		} elseif ($instances instanceof IHook) {
48
-			$this->hookInstances[] = $instances;
49
-		}
50
-		return true;
51
-	}
47
+        } elseif ($instances instanceof IHook) {
48
+            $this->hookInstances[] = $instances;
49
+        }
50
+        return true;
51
+    }
52 52
 
53
-	public function fireHooks() {
54
-		foreach ($this->hookInstances as $instance) {
55
-			/**
56
-			 * Fire off the add hooks method of each instance stored in cache
57
-			 *
58
-			 * @var $instance IHook
59
-			 */
60
-			$instance->addHooks();
61
-		}
53
+    public function fireHooks() {
54
+        foreach ($this->hookInstances as $instance) {
55
+            /**
56
+             * Fire off the add hooks method of each instance stored in cache
57
+             *
58
+             * @var $instance IHook
59
+             */
60
+            $instance->addHooks();
61
+        }
62 62
 
63
-	}
63
+    }
64 64
 
65 65
 }
Please login to merge, or discard this patch.
apps/encryption/appinfo/routes.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -26,36 +26,36 @@
 block discarded – undo
26 26
 
27 27
 (new Application())->registerRoutes($this, array('routes' => array(
28 28
 
29
-	[
30
-		'name' => 'Recovery#adminRecovery',
31
-		'url' => '/ajax/adminRecovery',
32
-		'verb' => 'POST'
33
-	],
34
-	[
35
-		'name' => 'Settings#updatePrivateKeyPassword',
36
-		'url' => '/ajax/updatePrivateKeyPassword',
37
-		'verb' => 'POST'
38
-	],
39
-	[
40
-		'name' => 'Settings#setEncryptHomeStorage',
41
-		'url' => '/ajax/setEncryptHomeStorage',
42
-		'verb' => 'POST'
43
-	],
44
-	[
45
-		'name' => 'Recovery#changeRecoveryPassword',
46
-		'url' => '/ajax/changeRecoveryPassword',
47
-		'verb' => 'POST'
48
-	],
49
-	[
50
-		'name' => 'Recovery#userSetRecovery',
51
-		'url' => '/ajax/userSetRecovery',
52
-		'verb' => 'POST'
53
-	],
54
-	[
55
-		'name' => 'Status#getStatus',
56
-		'url' => '/ajax/getStatus',
57
-		'verb' => 'GET'
58
-	]
29
+    [
30
+        'name' => 'Recovery#adminRecovery',
31
+        'url' => '/ajax/adminRecovery',
32
+        'verb' => 'POST'
33
+    ],
34
+    [
35
+        'name' => 'Settings#updatePrivateKeyPassword',
36
+        'url' => '/ajax/updatePrivateKeyPassword',
37
+        'verb' => 'POST'
38
+    ],
39
+    [
40
+        'name' => 'Settings#setEncryptHomeStorage',
41
+        'url' => '/ajax/setEncryptHomeStorage',
42
+        'verb' => 'POST'
43
+    ],
44
+    [
45
+        'name' => 'Recovery#changeRecoveryPassword',
46
+        'url' => '/ajax/changeRecoveryPassword',
47
+        'verb' => 'POST'
48
+    ],
49
+    [
50
+        'name' => 'Recovery#userSetRecovery',
51
+        'url' => '/ajax/userSetRecovery',
52
+        'verb' => 'POST'
53
+    ],
54
+    [
55
+        'name' => 'Status#getStatus',
56
+        'url' => '/ajax/getStatus',
57
+        'verb' => 'GET'
58
+    ]
59 59
 
60 60
 
61 61
 )));
Please login to merge, or discard this patch.