1
0

Controller.php 17 KB

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