Completed
Push — master ( b9bcc8...6a0f2f )
by Robin
46:28 queued 32:03
created

CertificateManager   B

Complexity

Total Complexity 38

Size/Duplication

Total Lines 241
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 241
rs 8.3999
wmc 38
lcom 1
cbo 7

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
C listCertificates() 0 26 8
C createCertificateBundle() 0 40 7
B addCertificate() 0 21 5
A removeCertificate() 0 11 3
A getCertificateBundle() 0 6 2
A getAbsoluteBundlePath() 0 14 4
A getPathToCertificates() 0 8 3
A needsRebundling() 0 19 4
A getFilemtimeOfCaBundle() 0 3 1
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Bjoern Schiessle <[email protected]>
6
 * @author Björn Schießle <[email protected]>
7
 * @author Joas Schilling <[email protected]>
8
 * @author Lukas Reschke <[email protected]>
9
 * @author Morris Jobke <[email protected]>
10
 * @author Robin Appelman <[email protected]>
11
 *
12
 * @license AGPL-3.0
13
 *
14
 * This code is free software: you can redistribute it and/or modify
15
 * it under the terms of the GNU Affero General Public License, version 3,
16
 * as published by the Free Software Foundation.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21
 * GNU Affero General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU Affero General Public License, version 3,
24
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
25
 *
26
 */
27
28
namespace OC\Security;
29
30
use OC\Files\Filesystem;
31
use OCP\ICertificateManager;
32
use OCP\IConfig;
33
use OCP\ILogger;
34
35
/**
36
 * Manage trusted certificates for users
37
 */
38
class CertificateManager implements ICertificateManager {
39
	/**
40
	 * @var string
41
	 */
42
	protected $uid;
43
44
	/**
45
	 * @var \OC\Files\View
46
	 */
47
	protected $view;
48
49
	/**
50
	 * @var IConfig
51
	 */
52
	protected $config;
53
54
	/**
55
	 * @var ILogger
56
	 */
57
	protected $logger;
58
59
	/**
60
	 * @param string $uid
61
	 * @param \OC\Files\View $view relative to data/
62
	 * @param IConfig $config
63
	 * @param ILogger $logger
64
	 */
65
	public function __construct($uid, \OC\Files\View $view, IConfig $config, ILogger $logger) {
66
		$this->uid = $uid;
67
		$this->view = $view;
68
		$this->config = $config;
69
		$this->logger = $logger;
70
	}
71
72
	/**
73
	 * Returns all certificates trusted by the user
74
	 *
75
	 * @return \OCP\ICertificate[]
76
	 */
77
	public function listCertificates() {
78
79
		if (!$this->config->getSystemValue('installed', false)) {
80
			return array();
81
		}
82
83
		$path = $this->getPathToCertificates() . 'uploads/';
84
		if (!$this->view->is_dir($path)) {
85
			return array();
86
		}
87
		$result = array();
88
		$handle = $this->view->opendir($path);
89
		if (!is_resource($handle)) {
90
			return array();
91
		}
92
		while (false !== ($file = readdir($handle))) {
93
			if ($file != '.' && $file != '..') {
94
				try {
95
					$result[] = new Certificate($this->view->file_get_contents($path . $file), $file);
96
				} catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
97
				}
98
			}
99
		}
100
		closedir($handle);
101
		return $result;
102
	}
103
104
	/**
105
	 * create the certificate bundle of all trusted certificated
106
	 */
107
	public function createCertificateBundle() {
108
		$path = $this->getPathToCertificates();
109
		$certs = $this->listCertificates();
110
111
		if (!$this->view->file_exists($path)) {
112
			$this->view->mkdir($path);
113
		}
114
115
		$defaultCertificates = file_get_contents(\OC::$SERVERROOT . '/resources/config/ca-bundle.crt');
116
		if (strlen($defaultCertificates) < 1024) { // sanity check to verify that we have some content for our bundle
117
			// log as exception so we have a stacktrace
118
			$this->logger->logException(new \Exception('Shipped ca-bundle is empty, refusing to create certificate bundle'));
119
			return;
120
		}
121
122
		$certPath = $path . 'rootcerts.crt';
123
		$fhCerts = $this->view->fopen($certPath, 'w');
124
125
		// Write user certificates
126
		foreach ($certs as $cert) {
127
			$file = $path . '/uploads/' . $cert->getName();
128
			$data = $this->view->file_get_contents($file);
129
			if (strpos($data, 'BEGIN CERTIFICATE')) {
130
				fwrite($fhCerts, $data);
131
				fwrite($fhCerts, "\r\n");
132
			}
133
		}
134
135
		// Append the default certificates
136
		fwrite($fhCerts, $defaultCertificates);
137
138
		// Append the system certificate bundle
139
		$systemBundle = $this->getCertificateBundle(null);
140
		if ($systemBundle !== $certPath && $this->view->file_exists($systemBundle)) {
141
			$systemCertificates = $this->view->file_get_contents($systemBundle);
142
			fwrite($fhCerts, $systemCertificates);
143
		}
144
145
		fclose($fhCerts);
146
	}
147
148
	/**
149
	 * Save the certificate and re-generate the certificate bundle
150
	 *
151
	 * @param string $certificate the certificate data
152
	 * @param string $name the filename for the certificate
153
	 * @return \OCP\ICertificate
154
	 * @throws \Exception If the certificate could not get added
155
	 */
156
	public function addCertificate($certificate, $name) {
157
		if (!Filesystem::isValidPath($name) or Filesystem::isFileBlacklisted($name)) {
158
			throw new \Exception('Filename is not valid');
159
		}
160
161
		$dir = $this->getPathToCertificates() . 'uploads/';
162
		if (!$this->view->file_exists($dir)) {
163
			$this->view->mkdir($dir);
164
		}
165
166
		try {
167
			$file = $dir . $name;
168
			$certificateObject = new Certificate($certificate, $name);
169
			$this->view->file_put_contents($file, $certificate);
170
			$this->createCertificateBundle();
171
			return $certificateObject;
172
		} catch (\Exception $e) {
173
			throw $e;
174
		}
175
176
	}
177
178
	/**
179
	 * Remove the certificate and re-generate the certificate bundle
180
	 *
181
	 * @param string $name
182
	 * @return bool
183
	 */
184
	public function removeCertificate($name) {
185
		if (!Filesystem::isValidPath($name)) {
186
			return false;
187
		}
188
		$path = $this->getPathToCertificates() . 'uploads/';
189
		if ($this->view->file_exists($path . $name)) {
190
			$this->view->unlink($path . $name);
191
			$this->createCertificateBundle();
192
		}
193
		return true;
194
	}
195
196
	/**
197
	 * Get the path to the certificate bundle for this user
198
	 *
199
	 * @param string $uid (optional) user to get the certificate bundle for, use `null` to get the system bundle
200
	 * @return string
201
	 */
202
	public function getCertificateBundle($uid = '') {
203
		if ($uid === '') {
204
			$uid = $this->uid;
205
		}
206
		return $this->getPathToCertificates($uid) . 'rootcerts.crt';
207
	}
208
209
	/**
210
	 * Get the full local path to the certificate bundle for this user
211
	 *
212
	 * @param string $uid (optional) user to get the certificate bundle for, use `null` to get the system bundle
213
	 * @return string
214
	 */
215
	public function getAbsoluteBundlePath($uid = '') {
216
		if ($uid === '') {
217
			$uid = $this->uid;
218
		}
219
		if ($this->needsRebundling($uid)) {
220
			if (is_null($uid)) {
221
				$manager = new CertificateManager(null, $this->view, $this->config, $this->logger);
222
				$manager->createCertificateBundle();
223
			} else {
224
				$this->createCertificateBundle();
225
			}
226
		}
227
		return $this->view->getLocalFile($this->getCertificateBundle($uid));
228
	}
229
230
	/**
231
	 * @param string $uid (optional) user to get the certificate path for, use `null` to get the system path
232
	 * @return string
233
	 */
234
	private function getPathToCertificates($uid = '') {
235
		if ($uid === '') {
236
			$uid = $this->uid;
237
		}
238
		$path = is_null($uid) ? '/files_external/' : '/' . $uid . '/files_external/';
239
240
		return $path;
241
	}
242
243
	/**
244
	 * Check if we need to re-bundle the certificates because one of the sources has updated
245
	 *
246
	 * @param string $uid (optional) user to get the certificate path for, use `null` to get the system path
247
	 * @return bool
248
	 */
249
	private function needsRebundling($uid = '') {
250
		if ($uid === '') {
251
			$uid = $this->uid;
252
		}
253
		$sourceMTimes = [$this->getFilemtimeOfCaBundle()];
254
		$targetBundle = $this->getCertificateBundle($uid);
255
		if (!$this->view->file_exists($targetBundle)) {
256
			return true;
257
		}
258
259
		if (!is_null($uid)) { // also depend on the system bundle
260
			$sourceMTimes[] = $this->view->filemtime($this->getCertificateBundle(null));
261
		}
262
263
		$sourceMTime = array_reduce($sourceMTimes, function ($max, $mtime) {
264
			return max($max, $mtime);
265
		}, 0);
266
		return $sourceMTime > $this->view->filemtime($targetBundle);
267
	}
268
269
	/**
270
	 * get mtime of ca-bundle shipped by Nextcloud
271
	 *
272
	 * @return int
273
	 */
274
	protected function getFilemtimeOfCaBundle() {
275
		return filemtime(\OC::$SERVERROOT . '/resources/config/ca-bundle.crt');
276
	}
277
278
}
279