1
0

CertificateManager.php 8.1 KB

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