Controller.php 17 KB

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