Controller.php 19 KB

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