PrivateBin.php 17 KB

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