You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

288 lines
7.8 KiB

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