CertificateManager.php 7.6 KB

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