CertificateManager.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 OC\Files\View;
  34. use OCP\ICertificate;
  35. use OCP\ICertificateManager;
  36. use OCP\IConfig;
  37. use OCP\Security\ISecureRandom;
  38. use Psr\Log\LoggerInterface;
  39. /**
  40. * Manage trusted certificates for users
  41. */
  42. class CertificateManager implements ICertificateManager {
  43. private ?string $bundlePath = null;
  44. public function __construct(
  45. protected View $view,
  46. protected IConfig $config,
  47. protected LoggerInterface $logger,
  48. protected ISecureRandom $random,
  49. ) {
  50. }
  51. /**
  52. * Returns all certificates trusted by the user
  53. *
  54. * @return \OCP\ICertificate[]
  55. */
  56. public function listCertificates(): array {
  57. if (!$this->config->getSystemValueBool('installed', false)) {
  58. return [];
  59. }
  60. $path = $this->getPathToCertificates() . 'uploads/';
  61. if (!$this->view->is_dir($path)) {
  62. return [];
  63. }
  64. $result = [];
  65. $handle = $this->view->opendir($path);
  66. if (!is_resource($handle)) {
  67. return [];
  68. }
  69. while (false !== ($file = readdir($handle))) {
  70. if ($file != '.' && $file != '..') {
  71. try {
  72. $content = $this->view->file_get_contents($path . $file);
  73. if ($content !== false) {
  74. $result[] = new Certificate($content, $file);
  75. } else {
  76. $this->logger->error("Failed to read certificate from $path");
  77. }
  78. } catch (\Exception $e) {
  79. $this->logger->error("Failed to read certificate from $path", ['exception' => $e]);
  80. }
  81. }
  82. }
  83. closedir($handle);
  84. return $result;
  85. }
  86. private function hasCertificates(): bool {
  87. if (!$this->config->getSystemValueBool('installed', false)) {
  88. return false;
  89. }
  90. $path = $this->getPathToCertificates() . 'uploads/';
  91. if (!$this->view->is_dir($path)) {
  92. return false;
  93. }
  94. $result = [];
  95. $handle = $this->view->opendir($path);
  96. if (!is_resource($handle)) {
  97. return false;
  98. }
  99. while (false !== ($file = readdir($handle))) {
  100. if ($file !== '.' && $file !== '..') {
  101. return true;
  102. }
  103. }
  104. closedir($handle);
  105. return false;
  106. }
  107. /**
  108. * create the certificate bundle of all trusted certificated
  109. */
  110. public function createCertificateBundle(): void {
  111. $path = $this->getPathToCertificates();
  112. $certs = $this->listCertificates();
  113. if (!$this->view->file_exists($path)) {
  114. $this->view->mkdir($path);
  115. }
  116. $defaultCertificates = file_get_contents(\OC::$SERVERROOT . '/resources/config/ca-bundle.crt');
  117. if (strlen($defaultCertificates) < 1024) { // sanity check to verify that we have some content for our bundle
  118. // log as exception so we have a stacktrace
  119. $e = new \Exception('Shipped ca-bundle is empty, refusing to create certificate bundle');
  120. $this->logger->error($e->getMessage(), ['exception' => $e]);
  121. return;
  122. }
  123. $certPath = $path . 'rootcerts.crt';
  124. $tmpPath = $certPath . '.tmp' . $this->random->generate(10, ISecureRandom::CHAR_DIGITS);
  125. $fhCerts = $this->view->fopen($tmpPath, 'w');
  126. if (!is_resource($fhCerts)) {
  127. throw new \RuntimeException('Unable to open file handler to create certificate bundle "' . $tmpPath . '".');
  128. }
  129. // Write user certificates
  130. foreach ($certs as $cert) {
  131. $file = $path . '/uploads/' . $cert->getName();
  132. $data = $this->view->file_get_contents($file);
  133. if (strpos($data, 'BEGIN CERTIFICATE')) {
  134. fwrite($fhCerts, $data);
  135. fwrite($fhCerts, "\r\n");
  136. }
  137. }
  138. // Append the default certificates
  139. fwrite($fhCerts, $defaultCertificates);
  140. // Append the system certificate bundle
  141. $systemBundle = $this->getCertificateBundle();
  142. if ($systemBundle !== $certPath && $this->view->file_exists($systemBundle)) {
  143. $systemCertificates = $this->view->file_get_contents($systemBundle);
  144. fwrite($fhCerts, $systemCertificates);
  145. }
  146. fclose($fhCerts);
  147. $this->view->rename($tmpPath, $certPath);
  148. }
  149. /**
  150. * Save the certificate and re-generate the certificate bundle
  151. *
  152. * @param string $certificate the certificate data
  153. * @param string $name the filename for the certificate
  154. * @throws \Exception If the certificate could not get added
  155. */
  156. public function addCertificate(string $certificate, string $name): ICertificate {
  157. if (!Filesystem::isValidPath($name) or Filesystem::isFileBlacklisted($name)) {
  158. throw new \Exception('Filename is not valid');
  159. }
  160. $this->bundlePath = null;
  161. $dir = $this->getPathToCertificates() . 'uploads/';
  162. if (!$this->view->file_exists($dir)) {
  163. $this->view->mkdir($dir);
  164. }
  165. try {
  166. $file = $dir . $name;
  167. $certificateObject = new Certificate($certificate, $name);
  168. $this->view->file_put_contents($file, $certificate);
  169. $this->createCertificateBundle();
  170. return $certificateObject;
  171. } catch (\Exception $e) {
  172. throw $e;
  173. }
  174. }
  175. /**
  176. * Remove the certificate and re-generate the certificate bundle
  177. */
  178. public function removeCertificate(string $name): bool {
  179. if (!Filesystem::isValidPath($name)) {
  180. return false;
  181. }
  182. $this->bundlePath = null;
  183. $path = $this->getPathToCertificates() . 'uploads/';
  184. if ($this->view->file_exists($path . $name)) {
  185. $this->view->unlink($path . $name);
  186. $this->createCertificateBundle();
  187. }
  188. return true;
  189. }
  190. /**
  191. * Get the path to the certificate bundle
  192. */
  193. public function getCertificateBundle(): string {
  194. return $this->getPathToCertificates() . 'rootcerts.crt';
  195. }
  196. /**
  197. * Get the full local path to the certificate bundle
  198. * @throws \Exception when getting bundle path fails
  199. */
  200. public function getAbsoluteBundlePath(): string {
  201. try {
  202. if ($this->bundlePath === null) {
  203. if (!$this->hasCertificates()) {
  204. $this->bundlePath = \OC::$SERVERROOT . '/resources/config/ca-bundle.crt';
  205. }
  206. if ($this->needsRebundling()) {
  207. $this->createCertificateBundle();
  208. }
  209. $certificateBundle = $this->getCertificateBundle();
  210. $this->bundlePath = $this->view->getLocalFile($certificateBundle) ?: null;
  211. if ($this->bundlePath === null) {
  212. throw new \RuntimeException('Unable to get certificate bundle "' . $certificateBundle . '".');
  213. }
  214. }
  215. return $this->bundlePath;
  216. } catch (\Exception $e) {
  217. $this->logger->error('Failed to get absolute bundle path. Fallback to default ca-bundle.crt', ['exception' => $e]);
  218. return \OC::$SERVERROOT . '/resources/config/ca-bundle.crt';
  219. }
  220. }
  221. private function getPathToCertificates(): string {
  222. return '/files_external/';
  223. }
  224. /**
  225. * Check if we need to re-bundle the certificates because one of the sources has updated
  226. */
  227. private function needsRebundling(): bool {
  228. $targetBundle = $this->getCertificateBundle();
  229. if (!$this->view->file_exists($targetBundle)) {
  230. return true;
  231. }
  232. $sourceMTime = $this->getFilemtimeOfCaBundle();
  233. return $sourceMTime > $this->view->filemtime($targetBundle);
  234. }
  235. /**
  236. * get mtime of ca-bundle shipped by Nextcloud
  237. */
  238. protected function getFilemtimeOfCaBundle(): int {
  239. return filemtime(\OC::$SERVERROOT . '/resources/config/ca-bundle.crt');
  240. }
  241. }