PrivateBin.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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.1
  11. */
  12. namespace PrivateBin;
  13. use Exception;
  14. use PrivateBin\Persistence\ServerSalt;
  15. use PrivateBin\Persistence\TrafficLimiter;
  16. /**
  17. * PrivateBin
  18. *
  19. * Controller, puts it all together.
  20. */
  21. class PrivateBin
  22. {
  23. /**
  24. * version
  25. *
  26. * @const string
  27. */
  28. const VERSION = '1.1';
  29. /**
  30. * minimal required PHP version
  31. *
  32. * @const string
  33. */
  34. const MIN_PHP_VERSION = '5.4.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. * data
  50. *
  51. * @access private
  52. * @var string
  53. */
  54. private $_data = '';
  55. /**
  56. * does the paste expire
  57. *
  58. * @access private
  59. * @var bool
  60. */
  61. private $_doesExpire = false;
  62. /**
  63. * error message
  64. *
  65. * @access private
  66. * @var string
  67. */
  68. private $_error = '';
  69. /**
  70. * status message
  71. *
  72. * @access private
  73. * @var string
  74. */
  75. private $_status = '';
  76. /**
  77. * JSON message
  78. *
  79. * @access private
  80. * @var string
  81. */
  82. private $_json = '';
  83. /**
  84. * Factory of instance models
  85. *
  86. * @access private
  87. * @var model
  88. */
  89. private $_model;
  90. /**
  91. * request
  92. *
  93. * @access private
  94. * @var request
  95. */
  96. private $_request;
  97. /**
  98. * URL base
  99. *
  100. * @access private
  101. * @var string
  102. */
  103. private $_urlBase;
  104. /**
  105. * constructor
  106. *
  107. * initializes and runs PrivateBin
  108. *
  109. * @access public
  110. * @throws Exception
  111. * @return void
  112. */
  113. public function __construct()
  114. {
  115. if (version_compare(PHP_VERSION, self::MIN_PHP_VERSION) < 0) {
  116. throw new Exception(I18n::_('%s requires php %s or above to work. Sorry.', I18n::_('PrivateBin'), self::MIN_PHP_VERSION), 1);
  117. }
  118. if (strlen(PATH) < 0 && substr(PATH, -1) !== DIRECTORY_SEPARATOR) {
  119. 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);
  120. }
  121. // load config from ini file, initialize required classes
  122. $this->_init();
  123. switch ($this->_request->getOperation()) {
  124. case 'create':
  125. $this->_create();
  126. break;
  127. case 'delete':
  128. $this->_delete(
  129. $this->_request->getParam('pasteid'),
  130. $this->_request->getParam('deletetoken')
  131. );
  132. break;
  133. case 'read':
  134. $this->_read($this->_request->getParam('pasteid'));
  135. break;
  136. case 'jsonld':
  137. $this->_jsonld($this->_request->getParam('jsonld'));
  138. return;
  139. }
  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. echo $this->_json;
  147. } else {
  148. $this->_view();
  149. }
  150. }
  151. /**
  152. * initialize privatebin
  153. *
  154. * @access private
  155. * @return void
  156. */
  157. private function _init()
  158. {
  159. foreach (array('cfg', 'lib') as $dir) {
  160. if (!is_file(PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess')) {
  161. file_put_contents(
  162. PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess',
  163. 'Allow from none' . PHP_EOL .
  164. 'Deny from all' . PHP_EOL,
  165. LOCK_EX
  166. );
  167. }
  168. }
  169. $this->_conf = new Configuration;
  170. $this->_model = new Model($this->_conf);
  171. $this->_request = new Request;
  172. $this->_urlBase = array_key_exists('REQUEST_URI', $_SERVER) ?
  173. htmlspecialchars($_SERVER['REQUEST_URI']) : '/';
  174. ServerSalt::setPath($this->_conf->getKey('dir', 'traffic'));
  175. // set default language
  176. $lang = $this->_conf->getKey('languagedefault');
  177. I18n::setLanguageFallback($lang);
  178. // force default language, if language selection is disabled and a default is set
  179. if (!$this->_conf->getKey('languageselection') && strlen($lang) == 2) {
  180. $_COOKIE['lang'] = $lang;
  181. setcookie('lang', $lang);
  182. }
  183. }
  184. /**
  185. * Store new paste or comment
  186. *
  187. * POST contains one or both:
  188. * data = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  189. * attachment = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  190. *
  191. * All optional data will go to meta information:
  192. * expire (optional) = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:never)
  193. * formatter (optional) = format to display the paste as (plaintext,syntaxhighlighting,markdown) (default:syntaxhighlighting)
  194. * burnafterreading (optional) = if this paste may only viewed once ? (0/1) (default:0)
  195. * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
  196. * attachmentname = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  197. * nickname (optional) = in discussion, encoded SJCL encrypted text nickname of author of comment (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  198. * parentid (optional) = in discussion, which comment this comment replies to.
  199. * pasteid (optional) = in discussion, which paste this comment belongs to.
  200. *
  201. * @access private
  202. * @return string
  203. */
  204. private function _create()
  205. {
  206. // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
  207. TrafficLimiter::setConfiguration($this->_conf);
  208. if (!TrafficLimiter::canPass()) {
  209. return $this->_return_message(
  210. 1, I18n::_(
  211. 'Please wait %d seconds between each post.',
  212. $this->_conf->getKey('limit', 'traffic')
  213. )
  214. );
  215. }
  216. $data = $this->_request->getParam('data');
  217. $attachment = $this->_request->getParam('attachment');
  218. $attachmentname = $this->_request->getParam('attachmentname');
  219. // Ensure content is not too big.
  220. $sizelimit = $this->_conf->getKey('sizelimit');
  221. if (
  222. strlen($data) + strlen($attachment) + strlen($attachmentname) > $sizelimit
  223. ) {
  224. return $this->_return_message(
  225. 1,
  226. I18n::_(
  227. 'Paste is limited to %s of encrypted data.',
  228. Filter::formatHumanReadableSize($sizelimit)
  229. )
  230. );
  231. }
  232. // Ensure attachment did not get lost due to webserver limits or Suhosin
  233. if (strlen($attachmentname) > 0 && strlen($attachment) == 0) {
  234. return $this->_return_message(1, 'Attachment missing in data received by server. Please check your webserver or suhosin configuration for maximum POST parameter limitations.');
  235. }
  236. // The user posts a comment.
  237. $pasteid = $this->_request->getParam('pasteid');
  238. $parentid = $this->_request->getParam('parentid');
  239. if (!empty($pasteid) && !empty($parentid)) {
  240. $paste = $this->_model->getPaste($pasteid);
  241. if ($paste->exists()) {
  242. try {
  243. $comment = $paste->getComment($parentid);
  244. $nickname = $this->_request->getParam('nickname');
  245. if (!empty($nickname)) {
  246. $comment->setNickname($nickname);
  247. }
  248. $comment->setData($data);
  249. $comment->store();
  250. } catch (Exception $e) {
  251. return $this->_return_message(1, $e->getMessage());
  252. }
  253. $this->_return_message(0, $comment->getId());
  254. } else {
  255. $this->_return_message(1, 'Invalid data.');
  256. }
  257. }
  258. // The user posts a standard paste.
  259. else {
  260. $this->_model->purge();
  261. $paste = $this->_model->getPaste();
  262. try {
  263. $paste->setData($data);
  264. if (!empty($attachment)) {
  265. $paste->setAttachment($attachment);
  266. if (!empty($attachmentname)) {
  267. $paste->setAttachmentName($attachmentname);
  268. }
  269. }
  270. $expire = $this->_request->getParam('expire');
  271. if (!empty($expire)) {
  272. $paste->setExpiration($expire);
  273. }
  274. $burnafterreading = $this->_request->getParam('burnafterreading');
  275. if (!empty($burnafterreading)) {
  276. $paste->setBurnafterreading($burnafterreading);
  277. }
  278. $opendiscussion = $this->_request->getParam('opendiscussion');
  279. if (!empty($opendiscussion)) {
  280. $paste->setOpendiscussion($opendiscussion);
  281. }
  282. $formatter = $this->_request->getParam('formatter');
  283. if (!empty($formatter)) {
  284. $paste->setFormatter($formatter);
  285. }
  286. $paste->store();
  287. } catch (Exception $e) {
  288. return $this->_return_message(1, $e->getMessage());
  289. }
  290. $this->_return_message(0, $paste->getId(), array('deletetoken' => $paste->getDeleteToken()));
  291. }
  292. }
  293. /**
  294. * Delete an existing paste
  295. *
  296. * @access private
  297. * @param string $dataid
  298. * @param string $deletetoken
  299. * @return void
  300. */
  301. private function _delete($dataid, $deletetoken)
  302. {
  303. try {
  304. $paste = $this->_model->getPaste($dataid);
  305. if ($paste->exists()) {
  306. // accessing this property ensures that the paste would be
  307. // deleted if it has already expired
  308. $burnafterreading = $paste->isBurnafterreading();
  309. if (
  310. ($burnafterreading && $deletetoken == 'burnafterreading') ||
  311. Filter::slowEquals($deletetoken, $paste->getDeleteToken())
  312. ) {
  313. // Paste exists and deletion token is valid: Delete the paste.
  314. $paste->delete();
  315. $this->_status = 'Paste was properly deleted.';
  316. } else {
  317. if (!$burnafterreading && $deletetoken == 'burnafterreading') {
  318. $this->_error = 'Paste is not of burn-after-reading type.';
  319. } else {
  320. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  321. }
  322. }
  323. } else {
  324. $this->_error = self::GENERIC_ERROR;
  325. }
  326. } catch (Exception $e) {
  327. $this->_error = $e->getMessage();
  328. }
  329. if ($this->_request->isJsonApiCall()) {
  330. if (strlen($this->_error)) {
  331. $this->_return_message(1, $this->_error);
  332. } else {
  333. $this->_return_message(0, $dataid);
  334. }
  335. }
  336. }
  337. /**
  338. * Read an existing paste or comment
  339. *
  340. * @access private
  341. * @param string $dataid
  342. * @return void
  343. */
  344. private function _read($dataid)
  345. {
  346. try {
  347. $paste = $this->_model->getPaste($dataid);
  348. if ($paste->exists()) {
  349. $data = $paste->get();
  350. $this->_doesExpire = property_exists($data, 'meta') && property_exists($data->meta, 'expire_date');
  351. if (property_exists($data->meta, 'salt')) {
  352. unset($data->meta->salt);
  353. }
  354. $this->_data = json_encode($data);
  355. } else {
  356. $this->_error = self::GENERIC_ERROR;
  357. }
  358. } catch (Exception $e) {
  359. $this->_error = $e->getMessage();
  360. }
  361. if ($this->_request->isJsonApiCall()) {
  362. if (strlen($this->_error)) {
  363. $this->_return_message(1, $this->_error);
  364. } else {
  365. $this->_return_message(0, $dataid, json_decode($this->_data, true));
  366. }
  367. }
  368. }
  369. /**
  370. * Display PrivateBin frontend.
  371. *
  372. * @access private
  373. * @return void
  374. */
  375. private function _view()
  376. {
  377. // set headers to disable caching
  378. $time = gmdate('D, d M Y H:i:s \G\M\T');
  379. header('Cache-Control: no-store, no-cache, no-transform, must-revalidate');
  380. header('Pragma: no-cache');
  381. header('Expires: ' . $time);
  382. header('Last-Modified: ' . $time);
  383. header('Vary: Accept');
  384. header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
  385. header('X-Xss-Protection: 1; mode=block');
  386. header('X-Frame-Options: DENY');
  387. header('X-Content-Type-Options: nosniff');
  388. // label all the expiration options
  389. $expire = array();
  390. foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
  391. $expire[$time] = ($seconds == 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
  392. }
  393. // translate all the formatter options
  394. $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
  395. // set language cookie if that functionality was enabled
  396. $languageselection = '';
  397. if ($this->_conf->getKey('languageselection')) {
  398. $languageselection = I18n::getLanguage();
  399. setcookie('lang', $languageselection);
  400. }
  401. $page = new View;
  402. $page->assign('NAME', $this->_conf->getKey('name'));
  403. $page->assign('CIPHERDATA', $this->_data);
  404. $page->assign('ERROR', I18n::_($this->_error));
  405. $page->assign('STATUS', I18n::_($this->_status));
  406. $page->assign('VERSION', self::VERSION);
  407. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  408. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  409. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  410. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  411. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  412. $page->assign('FORMATTER', $formatters);
  413. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  414. $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
  415. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  416. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  417. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  418. $page->assign('ZEROBINCOMPATIBILITY', $this->_conf->getKey('zerobincompatibility'));
  419. $page->assign('LANGUAGESELECTION', $languageselection);
  420. $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
  421. $page->assign('EXPIRE', $expire);
  422. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  423. $page->assign('EXPIRECLONE', !$this->_doesExpire || ($this->_doesExpire && $this->_conf->getKey('clone', 'expire')));
  424. $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
  425. $page->draw($this->_conf->getKey('template'));
  426. }
  427. /**
  428. * outputs requested JSON-LD context
  429. *
  430. * @access private
  431. * @param string $type
  432. * @return void
  433. */
  434. private function _jsonld($type)
  435. {
  436. if (
  437. $type !== 'paste' && $type !== 'comment' &&
  438. $type !== 'pastemeta' && $type !== 'commentmeta'
  439. ) {
  440. $type = '';
  441. }
  442. $content = '{}';
  443. $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
  444. if (is_readable($file)) {
  445. $content = str_replace(
  446. '?jsonld=',
  447. $this->_urlBase . '?jsonld=',
  448. file_get_contents($file)
  449. );
  450. }
  451. header('Content-type: application/ld+json');
  452. header('Access-Control-Allow-Origin: *');
  453. header('Access-Control-Allow-Methods: GET');
  454. echo $content;
  455. }
  456. /**
  457. * prepares JSON encoded status message
  458. *
  459. * @access private
  460. * @param int $status
  461. * @param string $message
  462. * @param array $other
  463. * @return void
  464. */
  465. private function _return_message($status, $message, $other = array())
  466. {
  467. $result = array('status' => $status);
  468. if ($status) {
  469. $result['message'] = I18n::_($message);
  470. } else {
  471. $result['id'] = $message;
  472. $result['url'] = $this->_urlBase . '?' . $message;
  473. }
  474. $result += $other;
  475. $this->_json = json_encode($result);
  476. }
  477. }