1
0

CertificateManager.php 7.8 KB

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