Controller.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. <?php declare(strict_types=1);
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. */
  11. namespace PrivateBin;
  12. use Exception;
  13. use PrivateBin\Persistence\ServerSalt;
  14. use PrivateBin\Persistence\TrafficLimiter;
  15. /**
  16. * Controller
  17. *
  18. * Puts it all together.
  19. */
  20. class Controller
  21. {
  22. /**
  23. * version
  24. *
  25. * @const string
  26. */
  27. const VERSION = '1.7.8';
  28. /**
  29. * minimal required PHP version
  30. *
  31. * @const string
  32. */
  33. const MIN_PHP_VERSION = '7.3.0';
  34. /**
  35. * show the same error message if the paste expired or does not exist
  36. *
  37. * @const string
  38. */
  39. const GENERIC_ERROR = 'Paste does not exist, has expired or has been deleted.';
  40. /**
  41. * configuration
  42. *
  43. * @access private
  44. * @var Configuration
  45. */
  46. private $_conf;
  47. /**
  48. * error message
  49. *
  50. * @access private
  51. * @var string
  52. */
  53. private $_error = '';
  54. /**
  55. * status message
  56. *
  57. * @access private
  58. * @var string
  59. */
  60. private $_status = '';
  61. /**
  62. * status message
  63. *
  64. * @access private
  65. * @var bool
  66. */
  67. private $_is_deleted = false;
  68. /**
  69. * JSON message
  70. *
  71. * @access private
  72. * @var string
  73. */
  74. private $_json = '';
  75. /**
  76. * Factory of instance models
  77. *
  78. * @access private
  79. * @var model
  80. */
  81. private $_model;
  82. /**
  83. * request
  84. *
  85. * @access private
  86. * @var request
  87. */
  88. private $_request;
  89. /**
  90. * URL base
  91. *
  92. * @access private
  93. * @var string
  94. */
  95. private $_urlBase;
  96. /**
  97. * constructor
  98. *
  99. * initializes and runs PrivateBin
  100. *
  101. * @param ?Configuration $config
  102. *
  103. * @access public
  104. * @throws Exception
  105. */
  106. public function __construct(?Configuration $config = null)
  107. {
  108. if (version_compare(PHP_VERSION, self::MIN_PHP_VERSION) < 0) {
  109. error_log(I18n::_('%s requires php %s or above to work. Sorry.', I18n::_('PrivateBin'), self::MIN_PHP_VERSION));
  110. return;
  111. }
  112. if (strlen(PATH) < 0 && substr(PATH, -1) !== DIRECTORY_SEPARATOR) {
  113. error_log(I18n::_('%s requires the PATH to end in a "%s". Please update the PATH in your index.php.', I18n::_('PrivateBin'), DIRECTORY_SEPARATOR));
  114. return;
  115. }
  116. // load config (using ini file by default) & initialize required classes
  117. $this->_conf = $config ?? new Configuration();
  118. $this->_init();
  119. switch ($this->_request->getOperation()) {
  120. case 'create':
  121. $this->_create();
  122. break;
  123. case 'delete':
  124. $this->_delete(
  125. $this->_request->getParam('pasteid'),
  126. $this->_request->getParam('deletetoken')
  127. );
  128. break;
  129. case 'read':
  130. $this->_read($this->_request->getParam('pasteid'));
  131. break;
  132. case 'jsonld':
  133. $this->_jsonld($this->_request->getParam('jsonld'));
  134. return;
  135. case 'yourlsproxy':
  136. $this->_yourlsproxy($this->_request->getParam('link'));
  137. break;
  138. }
  139. $this->_setCacheHeaders();
  140. // output JSON or HTML
  141. if ($this->_request->isJsonApiCall()) {
  142. header('Content-type: ' . Request::MIME_JSON);
  143. header('Access-Control-Allow-Origin: *');
  144. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
  145. header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
  146. header('X-Uncompressed-Content-Length: ' . strlen($this->_json));
  147. header('Access-Control-Expose-Headers: X-Uncompressed-Content-Length');
  148. echo $this->_json;
  149. } else {
  150. $this->_view();
  151. }
  152. }
  153. /**
  154. * initialize PrivateBin
  155. *
  156. * @access private
  157. * @throws Exception
  158. */
  159. private function _init()
  160. {
  161. $this->_model = new Model($this->_conf);
  162. $this->_request = new Request;
  163. $this->_urlBase = $this->_request->getRequestUri();
  164. $this->_setDefaultLanguage();
  165. $this->_setDefaultTemplate();
  166. }
  167. /**
  168. * Set default language
  169. *
  170. * @access private
  171. */
  172. private function _setDefaultLanguage()
  173. {
  174. $lang = $this->_conf->getKey('languagedefault');
  175. I18n::setLanguageFallback($lang);
  176. // force default language, if language selection is disabled and a default is set
  177. if (!$this->_conf->getKey('languageselection') && strlen($lang) == 2) {
  178. $_COOKIE['lang'] = $lang;
  179. setcookie('lang', $lang, array('SameSite' => 'Lax', 'Secure' => true));
  180. }
  181. }
  182. /**
  183. * Set default template
  184. *
  185. * @access private
  186. */
  187. private function _setDefaultTemplate()
  188. {
  189. $templates = $this->_conf->getKey('availabletemplates');
  190. $template = $this->_conf->getKey('template');
  191. if (!in_array($template, $templates, true)) {
  192. $templates[] = $template;
  193. }
  194. TemplateSwitcher::setAvailableTemplates($templates);
  195. TemplateSwitcher::setTemplateFallback($template);
  196. // force default template, if template selection is disabled
  197. if (!$this->_conf->getKey('templateselection') && array_key_exists('template', $_COOKIE)) {
  198. unset($_COOKIE['template']); // ensure value is not re-used in template switcher
  199. $expiredInAllTimezones = time() - 86400;
  200. setcookie('template', '', array('expires' => $expiredInAllTimezones, 'SameSite' => 'Lax', 'Secure' => true));
  201. }
  202. }
  203. /**
  204. * Turn off browser caching
  205. *
  206. * @access private
  207. */
  208. private function _setCacheHeaders()
  209. {
  210. // set headers to disable caching
  211. $time = gmdate('D, d M Y H:i:s \G\M\T');
  212. header('Cache-Control: no-store, no-cache, no-transform, must-revalidate');
  213. header('Pragma: no-cache');
  214. header('Expires: ' . $time);
  215. header('Last-Modified: ' . $time);
  216. header('Vary: Accept');
  217. }
  218. /**
  219. * Store new paste or comment
  220. *
  221. * POST contains one or both:
  222. * data = json encoded FormatV2 encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  223. * attachment = json encoded FormatV2 encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  224. *
  225. * All optional data will go to meta information:
  226. * expire (optional) = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:never)
  227. * formatter (optional) = format to display the paste as (plaintext,syntaxhighlighting,markdown) (default:syntaxhighlighting)
  228. * burnafterreading (optional) = if this paste may only viewed once ? (0/1) (default:0)
  229. * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
  230. * attachmentname = json encoded FormatV2 encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  231. * nickname (optional) = in discussion, encoded FormatV2 encrypted text nickname of author of comment (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  232. * parentid (optional) = in discussion, which comment this comment replies to.
  233. * pasteid (optional) = in discussion, which paste this comment belongs to.
  234. *
  235. * @access private
  236. * @return string
  237. */
  238. private function _create()
  239. {
  240. // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
  241. ServerSalt::setStore($this->_model->getStore());
  242. TrafficLimiter::setConfiguration($this->_conf);
  243. TrafficLimiter::setStore($this->_model->getStore());
  244. try {
  245. TrafficLimiter::canPass();
  246. } catch (Exception $e) {
  247. $this->_return_message(1, $e->getMessage());
  248. return;
  249. }
  250. $data = $this->_request->getData();
  251. $isComment = array_key_exists('pasteid', $data) &&
  252. !empty($data['pasteid']) &&
  253. array_key_exists('parentid', $data) &&
  254. !empty($data['parentid']);
  255. if (!FormatV2::isValid($data, $isComment)) {
  256. $this->_return_message(1, I18n::_('Invalid data.'));
  257. return;
  258. }
  259. $sizelimit = $this->_conf->getKey('sizelimit');
  260. // Ensure content is not too big.
  261. if (strlen($data['ct']) > $sizelimit) {
  262. $this->_return_message(
  263. 1,
  264. I18n::_(
  265. 'Paste is limited to %s of encrypted data.',
  266. Filter::formatHumanReadableSize($sizelimit)
  267. )
  268. );
  269. return;
  270. }
  271. // The user posts a comment.
  272. if ($isComment) {
  273. $paste = $this->_model->getPaste($data['pasteid']);
  274. if ($paste->exists()) {
  275. try {
  276. $comment = $paste->getComment($data['parentid']);
  277. $comment->setData($data);
  278. $comment->store();
  279. } catch (Exception $e) {
  280. $this->_return_message(1, $e->getMessage());
  281. return;
  282. }
  283. $this->_return_message(0, $comment->getId());
  284. } else {
  285. $this->_return_message(1, I18n::_('Invalid data.'));
  286. }
  287. }
  288. // The user posts a standard paste.
  289. else {
  290. try {
  291. $this->_model->purge();
  292. } catch (Exception $e) {
  293. error_log('Error purging pastes: ' . $e->getMessage() . PHP_EOL .
  294. 'Use the administration scripts statistics to find ' .
  295. 'damaged paste IDs and either delete them or restore them ' .
  296. 'from backup.');
  297. }
  298. $paste = $this->_model->getPaste();
  299. try {
  300. $paste->setData($data);
  301. $paste->store();
  302. } catch (Exception $e) {
  303. return $this->_return_message(1, $e->getMessage());
  304. }
  305. $this->_return_message(0, $paste->getId(), array('deletetoken' => $paste->getDeleteToken()));
  306. }
  307. }
  308. /**
  309. * Delete an existing paste
  310. *
  311. * @access private
  312. * @param string $dataid
  313. * @param string $deletetoken
  314. */
  315. private function _delete($dataid, $deletetoken)
  316. {
  317. try {
  318. $paste = $this->_model->getPaste($dataid);
  319. if ($paste->exists()) {
  320. // accessing this method ensures that the paste would be
  321. // deleted if it has already expired
  322. $paste->get();
  323. if (hash_equals($paste->getDeleteToken(), $deletetoken)) {
  324. // Paste exists and deletion token is valid: Delete the paste.
  325. $paste->delete();
  326. $this->_status = 'Paste was properly deleted.';
  327. $this->_is_deleted = true;
  328. } else {
  329. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  330. }
  331. } else {
  332. $this->_error = self::GENERIC_ERROR;
  333. }
  334. } catch (Exception $e) {
  335. $this->_error = $e->getMessage();
  336. }
  337. if ($this->_request->isJsonApiCall()) {
  338. if (empty($this->_error)) {
  339. $this->_return_message(0, $dataid);
  340. } else {
  341. $this->_return_message(1, $this->_error);
  342. }
  343. }
  344. }
  345. /**
  346. * Read an existing paste or comment, only allowed via a JSON API call
  347. *
  348. * @access private
  349. * @param string $dataid
  350. */
  351. private function _read($dataid)
  352. {
  353. if (!$this->_request->isJsonApiCall()) {
  354. return;
  355. }
  356. try {
  357. $paste = $this->_model->getPaste($dataid);
  358. if ($paste->exists()) {
  359. $data = $paste->get();
  360. if (array_key_exists('salt', $data['meta'])) {
  361. unset($data['meta']['salt']);
  362. }
  363. $this->_return_message(0, $dataid, (array) $data);
  364. } else {
  365. $this->_return_message(1, self::GENERIC_ERROR);
  366. }
  367. } catch (Exception $e) {
  368. $this->_return_message(1, $e->getMessage());
  369. }
  370. }
  371. /**
  372. * Display frontend.
  373. *
  374. * @access private
  375. */
  376. private function _view()
  377. {
  378. header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
  379. header('Cross-Origin-Resource-Policy: same-origin');
  380. header('Cross-Origin-Embedder-Policy: require-corp');
  381. // disabled, because it prevents links from a paste to the same site to
  382. // be opened. Didn't work with `same-origin-allow-popups` either.
  383. // See issue https://github.com/PrivateBin/PrivateBin/issues/970 for details.
  384. // header('Cross-Origin-Opener-Policy: same-origin');
  385. header('Permissions-Policy: browsing-topics=()');
  386. header('Referrer-Policy: no-referrer');
  387. header('X-Content-Type-Options: nosniff');
  388. header('X-Frame-Options: deny');
  389. header('X-XSS-Protection: 1; mode=block');
  390. // label all the expiration options
  391. $expire = array();
  392. foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
  393. $expire[$time] = ($seconds == 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
  394. }
  395. // translate all the formatter options
  396. $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
  397. // set language cookie if that functionality was enabled
  398. $languageselection = '';
  399. if ($this->_conf->getKey('languageselection')) {
  400. $languageselection = I18n::getLanguage();
  401. setcookie('lang', $languageselection, array('SameSite' => 'Lax', 'Secure' => true));
  402. }
  403. // set template cookie if that functionality was enabled
  404. $templateselection = '';
  405. if ($this->_conf->getKey('templateselection')) {
  406. $templateselection = TemplateSwitcher::getTemplate();
  407. setcookie('template', $templateselection, array('SameSite' => 'Lax', 'Secure' => true));
  408. }
  409. // strip policies that are unsupported in meta tag
  410. $metacspheader = str_replace(
  411. array(
  412. 'frame-ancestors \'none\'; ',
  413. '; sandbox allow-same-origin allow-scripts allow-forms allow-popups allow-modals allow-downloads',
  414. ),
  415. '',
  416. $this->_conf->getKey('cspheader')
  417. );
  418. $page = new View;
  419. $page->assign('CSPHEADER', $metacspheader);
  420. $page->assign('ERROR', I18n::_($this->_error));
  421. $page->assign('NAME', $this->_conf->getKey('name'));
  422. if ($this->_request->getOperation() === 'yourlsproxy') {
  423. $page->assign('SHORTURL', $this->_status);
  424. $page->draw('yourlsproxy');
  425. return;
  426. }
  427. $page->assign('BASEPATH', I18n::_($this->_conf->getKey('basepath')));
  428. $page->assign('STATUS', I18n::_($this->_status));
  429. $page->assign('ISDELETED', I18n::_(json_encode($this->_is_deleted)));
  430. $page->assign('VERSION', self::VERSION);
  431. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  432. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  433. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  434. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  435. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  436. $page->assign('FORMATTER', $formatters);
  437. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  438. $page->assign('INFO', I18n::_(str_replace("'", '"', $this->_conf->getKey('info'))));
  439. $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
  440. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  441. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  442. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  443. $page->assign('ZEROBINCOMPATIBILITY', $this->_conf->getKey('zerobincompatibility'));
  444. $page->assign('LANGUAGESELECTION', $languageselection);
  445. $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
  446. $page->assign('TEMPLATESELECTION', $templateselection);
  447. $page->assign('TEMPLATES', TemplateSwitcher::getAvailableTemplates());
  448. $page->assign('EXPIRE', $expire);
  449. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  450. $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
  451. $page->assign('QRCODE', $this->_conf->getKey('qrcode'));
  452. $page->assign('EMAIL', $this->_conf->getKey('email'));
  453. $page->assign('HTTPWARNING', $this->_conf->getKey('httpwarning'));
  454. $page->assign('HTTPSLINK', 'https://' . $this->_request->getHost() . $this->_request->getRequestUri());
  455. $page->assign('COMPRESSION', $this->_conf->getKey('compression'));
  456. $page->assign('SRI', $this->_conf->getSection('sri'));
  457. $page->draw(TemplateSwitcher::getTemplate());
  458. }
  459. /**
  460. * outputs requested JSON-LD context
  461. *
  462. * @access private
  463. * @param string $type
  464. */
  465. private function _jsonld($type)
  466. {
  467. if (!in_array($type, array(
  468. 'comment',
  469. 'commentmeta',
  470. 'paste',
  471. 'pastemeta',
  472. 'types',
  473. ))) {
  474. $type = '';
  475. }
  476. $content = '{}';
  477. $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
  478. if (is_readable($file)) {
  479. $content = str_replace(
  480. '?jsonld=',
  481. $this->_urlBase . '?jsonld=',
  482. file_get_contents($file)
  483. );
  484. }
  485. if ($type === 'types') {
  486. $content = str_replace(
  487. implode('", "', array_keys($this->_conf->getDefaults()['expire_options'])),
  488. implode('", "', array_keys($this->_conf->getSection('expire_options'))),
  489. $content
  490. );
  491. }
  492. header('Content-type: application/ld+json');
  493. header('Access-Control-Allow-Origin: *');
  494. header('Access-Control-Allow-Methods: GET');
  495. echo $content;
  496. }
  497. /**
  498. * proxies link to YOURLS, updates status or error with response
  499. *
  500. * @access private
  501. * @param string $link
  502. */
  503. private function _yourlsproxy($link)
  504. {
  505. $yourls = new YourlsProxy($this->_conf, $link);
  506. if ($yourls->isError()) {
  507. $this->_error = $yourls->getError();
  508. } else {
  509. $this->_status = $yourls->getUrl();
  510. }
  511. }
  512. /**
  513. * prepares JSON encoded status message
  514. *
  515. * @access private
  516. * @param int $status
  517. * @param string $message
  518. * @param array $other
  519. */
  520. private function _return_message($status, $message, $other = array())
  521. {
  522. $result = array('status' => $status);
  523. if ($status) {
  524. $result['message'] = I18n::_($message);
  525. } else {
  526. $result['id'] = $message;
  527. $result['url'] = $this->_urlBase . '?' . $message;
  528. }
  529. $result += $other;
  530. $this->_json = Json::encode($result);
  531. }
  532. }