1
0

Controller.php 16 KB

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