CertificateManager.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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\Security\ISecureRandom;
  37. use Psr\Log\LoggerInterface;
  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. protected LoggerInterface $logger;
  51. /** @var ISecureRandom */
  52. protected $random;
  53. private ?string $bundlePath = null;
  54. public function __construct(\OC\Files\View $view,
  55. IConfig $config,
  56. LoggerInterface $logger,
  57. ISecureRandom $random) {
  58. $this->view = $view;
  59. $this->config = $config;
  60. $this->logger = $logger;
  61. $this->random = $random;
  62. }
  63. /**
  64. * Returns all certificates trusted by the user
  65. *
  66. * @return \OCP\ICertificate[]
  67. */
  68. public function listCertificates(): array {
  69. if (!$this->config->getSystemValue('installed', false)) {
  70. return [];
  71. }
  72. $path = $this->getPathToCertificates() . 'uploads/';
  73. if (!$this->view->is_dir($path)) {
  74. return [];
  75. }
  76. $result = [];
  77. $handle = $this->view->opendir($path);
  78. if (!is_resource($handle)) {
  79. return [];
  80. }
  81. while (false !== ($file = readdir($handle))) {
  82. if ($file != '.' && $file != '..') {
  83. try {
  84. $result[] = new Certificate($this->view->file_get_contents($path . $file), $file);
  85. } catch (\Exception $e) {
  86. }
  87. }
  88. }
  89. closedir($handle);
  90. return $result;
  91. }
  92. private function hasCertificates(): bool {
  93. if (!$this->config->getSystemValue('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. // Write user certificates
  133. foreach ($certs as $cert) {
  134. $file = $path . '/uploads/' . $cert->getName();
  135. $data = $this->view->file_get_contents($file);
  136. if (strpos($data, 'BEGIN CERTIFICATE')) {
  137. fwrite($fhCerts, $data);
  138. fwrite($fhCerts, "\r\n");
  139. }
  140. }
  141. // Append the default certificates
  142. fwrite($fhCerts, $defaultCertificates);
  143. // Append the system certificate bundle
  144. $systemBundle = $this->getCertificateBundle();
  145. if ($systemBundle !== $certPath && $this->view->file_exists($systemBundle)) {
  146. $systemCertificates = $this->view->file_get_contents($systemBundle);
  147. fwrite($fhCerts, $systemCertificates);
  148. }
  149. fclose($fhCerts);
  150. $this->view->rename($tmpPath, $certPath);
  151. }
  152. /**
  153. * Save the certificate and re-generate the certificate bundle
  154. *
  155. * @param string $certificate the certificate data
  156. * @param string $name the filename for the certificate
  157. * @return \OCP\ICertificate
  158. * @throws \Exception If the certificate could not get added
  159. */
  160. public function addCertificate(string $certificate, string $name): ICertificate {
  161. if (!Filesystem::isValidPath($name) or Filesystem::isFileBlacklisted($name)) {
  162. throw new \Exception('Filename is not valid');
  163. }
  164. $this->bundlePath = null;
  165. $dir = $this->getPathToCertificates() . 'uploads/';
  166. if (!$this->view->file_exists($dir)) {
  167. $this->view->mkdir($dir);
  168. }
  169. try {
  170. $file = $dir . $name;
  171. $certificateObject = new Certificate($certificate, $name);
  172. $this->view->file_put_contents($file, $certificate);
  173. $this->createCertificateBundle();
  174. return $certificateObject;
  175. } catch (\Exception $e) {
  176. throw $e;
  177. }
  178. }
  179. /**
  180. * Remove the certificate and re-generate the certificate bundle
  181. *
  182. * @param string $name
  183. * @return bool
  184. */
  185. public function removeCertificate(string $name): bool {
  186. if (!Filesystem::isValidPath($name)) {
  187. return false;
  188. }
  189. $this->bundlePath = null;
  190. $path = $this->getPathToCertificates() . 'uploads/';
  191. if ($this->view->file_exists($path . $name)) {
  192. $this->view->unlink($path . $name);
  193. $this->createCertificateBundle();
  194. }
  195. return true;
  196. }
  197. /**
  198. * Get the path to the certificate bundle
  199. *
  200. * @return string
  201. */
  202. public function getCertificateBundle(): string {
  203. return $this->getPathToCertificates() . 'rootcerts.crt';
  204. }
  205. /**
  206. * Get the full local path to the certificate bundle
  207. *
  208. * @return string
  209. */
  210. public function getAbsoluteBundlePath(): string {
  211. try {
  212. if (!$this->bundlePath) {
  213. if (!$this->hasCertificates()) {
  214. $this->bundlePath = \OC::$SERVERROOT . '/resources/config/ca-bundle.crt';
  215. }
  216. if ($this->needsRebundling()) {
  217. $this->createCertificateBundle();
  218. }
  219. $this->bundlePath = $this->view->getLocalFile($this->getCertificateBundle());
  220. }
  221. return $this->bundlePath;
  222. } catch (\Exception $e) {
  223. return \OC::$SERVERROOT . '/resources/config/ca-bundle.crt';
  224. }
  225. }
  226. /**
  227. * @return string
  228. */
  229. private function getPathToCertificates(): string {
  230. return '/files_external/';
  231. }
  232. /**
  233. * Check if we need to re-bundle the certificates because one of the sources has updated
  234. *
  235. * @return bool
  236. */
  237. private function needsRebundling(): bool {
  238. $targetBundle = $this->getCertificateBundle();
  239. if (!$this->view->file_exists($targetBundle)) {
  240. return true;
  241. }
  242. $sourceMTime = $this->getFilemtimeOfCaBundle();
  243. return $sourceMTime > $this->view->filemtime($targetBundle);
  244. }
  245. /**
  246. * get mtime of ca-bundle shipped by Nextcloud
  247. *
  248. * @return int
  249. */
  250. protected function getFilemtimeOfCaBundle(): int {
  251. return filemtime(\OC::$SERVERROOT . '/resources/config/ca-bundle.crt');
  252. }
  253. }