zerobin.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. <?php
  2. /**
  3. * ZeroBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link http://sebsauvage.net/wiki/doku.php?id=php:zerobin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license http://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 0.21.1
  11. */
  12. /**
  13. * zerobin
  14. *
  15. * Controller, puts it all together.
  16. */
  17. class zerobin
  18. {
  19. /**
  20. * version
  21. *
  22. * @const string
  23. */
  24. const VERSION = '0.21.1';
  25. /**
  26. * show the same error message if the paste expired or does not exist
  27. *
  28. * @const string
  29. */
  30. const GENERIC_ERROR = 'Paste does not exist, has expired or has been deleted.';
  31. /**
  32. * configuration
  33. *
  34. * @access private
  35. * @var configuration
  36. */
  37. private $_conf;
  38. /**
  39. * data
  40. *
  41. * @access private
  42. * @var string
  43. */
  44. private $_data = '';
  45. /**
  46. * formatter
  47. *
  48. * @access private
  49. * @var string
  50. */
  51. private $_formatter = 'plaintext';
  52. /**
  53. * error message
  54. *
  55. * @access private
  56. * @var string
  57. */
  58. private $_error = '';
  59. /**
  60. * status message
  61. *
  62. * @access private
  63. * @var string
  64. */
  65. private $_status = '';
  66. /**
  67. * JSON message
  68. *
  69. * @access private
  70. * @var string
  71. */
  72. private $_json = '';
  73. /**
  74. * data storage model
  75. *
  76. * @access private
  77. * @var zerobin_abstract
  78. */
  79. private $_model;
  80. /**
  81. * constructor
  82. *
  83. * initializes and runs ZeroBin
  84. *
  85. * @access public
  86. * @return void
  87. */
  88. public function __construct()
  89. {
  90. if (version_compare(PHP_VERSION, '5.2.6') < 0)
  91. {
  92. throw new Exception(i18n::_('ZeroBin requires php 5.2.6 or above to work. Sorry.'), 1);
  93. }
  94. // in case stupid admin has left magic_quotes enabled in php.ini
  95. if (get_magic_quotes_gpc())
  96. {
  97. $_POST = array_map('filter::stripslashes_deep', $_POST);
  98. $_GET = array_map('filter::stripslashes_deep', $_GET);
  99. $_COOKIE = array_map('filter::stripslashes_deep', $_COOKIE);
  100. }
  101. // load config from ini file
  102. $this->_init();
  103. // create new paste or comment
  104. if (
  105. (array_key_exists('data', $_POST) && !empty($_POST['data'])) ||
  106. (array_key_exists('attachment', $_POST) && !empty($_POST['attachment']))
  107. )
  108. {
  109. $this->_create();
  110. }
  111. // delete an existing paste
  112. elseif (!empty($_GET['deletetoken']) && !empty($_GET['pasteid']))
  113. {
  114. $this->_delete($_GET['pasteid'], $_GET['deletetoken']);
  115. }
  116. // display an existing paste
  117. elseif (!empty($_SERVER['QUERY_STRING']))
  118. {
  119. $this->_read($_SERVER['QUERY_STRING']);
  120. }
  121. // output JSON or HTML
  122. if (strlen($this->_json))
  123. {
  124. header('Content-type: application/json');
  125. echo $this->_json;
  126. }
  127. else
  128. {
  129. $this->_view();
  130. }
  131. }
  132. /**
  133. * initialize zerobin
  134. *
  135. * @access private
  136. * @return void
  137. */
  138. private function _init()
  139. {
  140. foreach (array('cfg', 'lib') as $dir)
  141. {
  142. if (!is_file(PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess')) file_put_contents(
  143. PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess',
  144. 'Allow from none' . PHP_EOL .
  145. 'Deny from all'. PHP_EOL,
  146. LOCK_EX
  147. );
  148. }
  149. $this->_conf = new configuration;
  150. $this->_model = $this->_conf->getKey('class', 'model');
  151. }
  152. /**
  153. * get the model, create one if needed
  154. *
  155. * @access private
  156. * @return zerobin_abstract
  157. */
  158. private function _model()
  159. {
  160. // if needed, initialize the model
  161. if(is_string($this->_model)) {
  162. $this->_model = forward_static_call(
  163. array($this->_model, 'getInstance'),
  164. $this->_conf->getSection('model_options')
  165. );
  166. }
  167. return $this->_model;
  168. }
  169. /**
  170. * Store new paste or comment
  171. *
  172. * POST contains one or both:
  173. * data = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  174. * attachment = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  175. *
  176. * All optional data will go to meta information:
  177. * expire (optional) = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:never)
  178. * formatter (optional) = format to display the paste as (plaintext,syntaxhighlighting,markdown) (default:syntaxhighlighting)
  179. * burnafterreading (optional) = if this paste may only viewed once ? (0/1) (default:0)
  180. * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
  181. * attachmentname = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  182. * 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)
  183. * parentid (optional) = in discussion, which comment this comment replies to.
  184. * pasteid (optional) = in discussion, which paste this comment belongs to.
  185. *
  186. * @access private
  187. * @return string
  188. */
  189. private function _create()
  190. {
  191. $error = false;
  192. $has_attachment = array_key_exists('attachment', $_POST);
  193. $has_attachmentname = $has_attachment && array_key_exists('attachmentname', $_POST) && !empty($_POST['attachmentname']);
  194. $data = array_key_exists('data', $_POST) ? $_POST['data'] : '';
  195. $attachment = $has_attachment ? $_POST['attachment'] : '';
  196. $attachmentname = $has_attachmentname ? $_POST['attachmentname'] : '';
  197. // Make sure last paste from the IP address was more than X seconds ago.
  198. trafficlimiter::setConfiguration($this->_conf);
  199. if (!trafficlimiter::canPass()) return $this->_return_message(
  200. 1,
  201. i18n::_(
  202. 'Please wait %d seconds between each post.',
  203. $this->_conf->getKey('limit', 'traffic')
  204. )
  205. );
  206. // Make sure content is not too big.
  207. $sizelimit = $this->_conf->getKey('sizelimit');
  208. if (
  209. strlen($data) + strlen($attachment) + strlen($attachmentname) > $sizelimit
  210. ) return $this->_return_message(
  211. 1,
  212. i18n::_(
  213. 'Paste is limited to %s of encrypted data.',
  214. filter::size_humanreadable($sizelimit)
  215. )
  216. );
  217. // Make sure format is correct.
  218. if (!sjcl::isValid($data)) return $this->_return_message(1, 'Invalid data.');
  219. // Make sure attachments are enabled and format is correct.
  220. if($has_attachment)
  221. {
  222. if (
  223. !$this->_conf->getKey('fileupload') ||
  224. !sjcl::isValid($attachment) ||
  225. !($has_attachmentname && sjcl::isValid($attachmentname))
  226. ) return $this->_return_message(1, 'Invalid attachment.');
  227. }
  228. // Read additional meta-information.
  229. $meta = array();
  230. // Read expiration date
  231. if (array_key_exists('expire', $_POST) && !empty($_POST['expire']))
  232. {
  233. $selected_expire = (string) $_POST['expire'];
  234. $expire_options = $this->_conf->getSection('expire_options');
  235. if (array_key_exists($selected_expire, $expire_options))
  236. {
  237. $expire = $expire_options[$selected_expire];
  238. }
  239. else
  240. {
  241. $expire = $this->_conf->getKey($this->_conf->getKey('default', 'expire'), 'expire_options');
  242. }
  243. if ($expire > 0) $meta['expire_date'] = time() + $expire;
  244. }
  245. // Destroy the paste when it is read.
  246. if (array_key_exists('burnafterreading', $_POST) && !empty($_POST['burnafterreading']))
  247. {
  248. $burnafterreading = $_POST['burnafterreading'];
  249. if ($burnafterreading !== '0')
  250. {
  251. if ($burnafterreading !== '1') $error = true;
  252. $meta['burnafterreading'] = true;
  253. }
  254. }
  255. // Read open discussion flag.
  256. if (
  257. $this->_conf->getKey('discussion') &&
  258. array_key_exists('opendiscussion', $_POST) &&
  259. !empty($_POST['opendiscussion'])
  260. )
  261. {
  262. $opendiscussion = $_POST['opendiscussion'];
  263. if ($opendiscussion !== '0')
  264. {
  265. if ($opendiscussion !== '1') $error = true;
  266. $meta['opendiscussion'] = true;
  267. }
  268. }
  269. // Read formatter flag.
  270. if (array_key_exists('formatter', $_POST) && !empty($_POST['formatter']))
  271. {
  272. $formatter = $_POST['formatter'];
  273. if (!array_key_exists($formatter, $this->_conf->getSection('formatter_options')))
  274. {
  275. $formatter = $this->_conf->getKey('defaultformatter');
  276. }
  277. $meta['formatter'] = $formatter;
  278. }
  279. // You can't have an open discussion on a "Burn after reading" paste:
  280. if (isset($meta['burnafterreading'])) unset($meta['opendiscussion']);
  281. // Optional nickname for comments
  282. if (!empty($_POST['nickname']))
  283. {
  284. // Generation of the anonymous avatar (Vizhash):
  285. // If a nickname is provided, we generate a Vizhash.
  286. // (We assume that if the user did not enter a nickname, he/she wants
  287. // to be anonymous and we will not generate the vizhash.)
  288. $nick = $_POST['nickname'];
  289. if (!sjcl::isValid($nick))
  290. {
  291. $error = true;
  292. }
  293. else
  294. {
  295. $meta['nickname'] = $nick;
  296. $vz = new vizhash16x16();
  297. $pngdata = $vz->generate(trafficlimiter::getIp());
  298. if ($pngdata != '')
  299. {
  300. $meta['vizhash'] = 'data:image/png;base64,' . base64_encode($pngdata);
  301. }
  302. // Once the avatar is generated, we do not keep the IP address, nor its hash.
  303. }
  304. }
  305. if ($error) return $this->_return_message(1, 'Invalid data.');
  306. // Add post date to meta.
  307. $meta['postdate'] = time();
  308. // We just want a small hash to avoid collisions:
  309. // Half-MD5 (64 bits) will do the trick
  310. $dataid = substr(hash('md5', $data), 0, 16);
  311. $storage = array('data' => $data);
  312. // Add meta-information only if necessary.
  313. if (count($meta)) $storage['meta'] = $meta;
  314. // The user posts a comment.
  315. if (
  316. !empty($_POST['parentid']) &&
  317. !empty($_POST['pasteid'])
  318. )
  319. {
  320. $pasteid = (string) $_POST['pasteid'];
  321. $parentid = (string) $_POST['parentid'];
  322. if (
  323. !filter::is_valid_paste_id($pasteid) ||
  324. !filter::is_valid_paste_id($parentid)
  325. ) return $this->_return_message(1, 'Invalid data.');
  326. // Comments do not expire (it's the paste that expires)
  327. unset($storage['expire_date']);
  328. unset($storage['opendiscussion']);
  329. // Make sure paste exists.
  330. if (
  331. !$this->_model()->exists($pasteid)
  332. ) return $this->_return_message(1, 'Invalid data.');
  333. // Make sure the discussion is opened in this paste.
  334. $paste = $this->_model()->read($pasteid);
  335. if (
  336. !$paste->meta->opendiscussion
  337. ) return $this->_return_message(1, 'Invalid data.');
  338. // Check for improbable collision.
  339. if (
  340. $this->_model()->existsComment($pasteid, $parentid, $dataid)
  341. ) return $this->_return_message(1, 'You are unlucky. Try again.');
  342. // New comment
  343. if (
  344. $this->_model()->createComment($pasteid, $parentid, $dataid, $storage) === false
  345. ) return $this->_return_message(1, 'Error saving comment. Sorry.');
  346. // 0 = no error
  347. return $this->_return_message(0, $dataid);
  348. }
  349. // The user posts a standard paste.
  350. else
  351. {
  352. // Check for improbable collision.
  353. if (
  354. $this->_model()->exists($dataid)
  355. ) return $this->_return_message(1, 'You are unlucky. Try again.');
  356. // Add attachment and its name, if one was sent
  357. if ($has_attachment) $storage['meta']['attachment'] = $attachment;
  358. if ($has_attachmentname) $storage['meta']['attachmentname'] = $attachmentname;
  359. // New paste
  360. if (
  361. $this->_model()->create($dataid, $storage) === false
  362. ) return $this->_return_message(1, 'Error saving paste. Sorry.');
  363. // Generate the "delete" token.
  364. // The token is the hmac of the pasteid signed with the server salt.
  365. // The paste can be delete by calling http://example.com/zerobin/?pasteid=<pasteid>&deletetoken=<deletetoken>
  366. $deletetoken = hash_hmac('sha1', $dataid, serversalt::get());
  367. // 0 = no error
  368. return $this->_return_message(0, $dataid, array('deletetoken' => $deletetoken));
  369. }
  370. }
  371. /**
  372. * Delete an existing paste
  373. *
  374. * @access private
  375. * @param string $dataid
  376. * @param string $deletetoken
  377. * @return void
  378. */
  379. private function _delete($dataid, $deletetoken)
  380. {
  381. // Is this a valid paste identifier?
  382. if (!filter::is_valid_paste_id($dataid))
  383. {
  384. $this->_error = 'Invalid paste ID.';
  385. return;
  386. }
  387. // Check that paste exists.
  388. if (!$this->_model()->exists($dataid))
  389. {
  390. $this->_error = self::GENERIC_ERROR;
  391. return;
  392. }
  393. // Get the paste itself.
  394. $paste = $this->_model()->read($dataid);
  395. // See if paste has expired.
  396. if (
  397. isset($paste->meta->expire_date) &&
  398. $paste->meta->expire_date < time()
  399. )
  400. {
  401. // Delete the paste
  402. $this->_model()->delete($dataid);
  403. $this->_error = self::GENERIC_ERROR;
  404. return;
  405. }
  406. if ($deletetoken == 'burnafterreading') {
  407. if (
  408. isset($paste->meta->burnafterreading) &&
  409. $paste->meta->burnafterreading
  410. )
  411. {
  412. // Delete the paste
  413. $this->_model()->delete($dataid);
  414. $this->_return_message(0, $dataid);
  415. }
  416. else
  417. {
  418. $this->_return_message(1, 'Paste is not of burn-after-reading type.');
  419. }
  420. return;
  421. }
  422. // Make sure token is valid.
  423. serversalt::setPath($this->_conf->getKey('dir', 'traffic'));
  424. if (!filter::slow_equals($deletetoken, hash_hmac('sha1', $dataid, serversalt::get())))
  425. {
  426. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  427. return;
  428. }
  429. // Paste exists and deletion token is valid: Delete the paste.
  430. $this->_model()->delete($dataid);
  431. $this->_status = 'Paste was properly deleted.';
  432. }
  433. /**
  434. * Read an existing paste or comment
  435. *
  436. * @access private
  437. * @param string $dataid
  438. * @return void
  439. */
  440. private function _read($dataid)
  441. {
  442. $isJson = false;
  443. if (($pos = strpos($dataid, '&json')) !== false) {
  444. $isJson = true;
  445. $dataid = substr($dataid, 0, $pos);
  446. }
  447. // Is this a valid paste identifier?
  448. if (!filter::is_valid_paste_id($dataid))
  449. {
  450. $this->_error = 'Invalid paste ID.';
  451. return;
  452. }
  453. // Check that paste exists.
  454. if ($this->_model()->exists($dataid))
  455. {
  456. // Get the paste itself.
  457. $paste = $this->_model()->read($dataid);
  458. // See if paste has expired.
  459. if (
  460. isset($paste->meta->expire_date) &&
  461. $paste->meta->expire_date < time()
  462. )
  463. {
  464. // Delete the paste
  465. $this->_model()->delete($dataid);
  466. $this->_error = self::GENERIC_ERROR;
  467. }
  468. // If no error, return the paste.
  469. else
  470. {
  471. // We kindly provide the remaining time before expiration (in seconds)
  472. if (
  473. property_exists($paste->meta, 'expire_date')
  474. ) $paste->meta->remaining_time = $paste->meta->expire_date - time();
  475. // The paste itself is the first in the list of encrypted messages.
  476. $messages = array($paste);
  477. // If it's a discussion, get all comments.
  478. if (
  479. property_exists($paste->meta, 'opendiscussion') &&
  480. $paste->meta->opendiscussion
  481. )
  482. {
  483. $messages = array_merge(
  484. $messages,
  485. $this->_model()->readComments($dataid)
  486. );
  487. }
  488. // set formatter for for the view.
  489. if (!property_exists($paste->meta, 'formatter'))
  490. {
  491. // support < 0.21 syntax highlighting
  492. if (property_exists($paste->meta, 'syntaxcoloring') && $paste->meta->syntaxcoloring === true)
  493. {
  494. $paste->meta->formatter = 'syntaxhighlighting';
  495. }
  496. else
  497. {
  498. $paste->meta->formatter = $this->_conf->getKey('defaultformatter');
  499. }
  500. }
  501. $this->_data = json_encode($messages);
  502. }
  503. }
  504. else
  505. {
  506. $this->_error = self::GENERIC_ERROR;
  507. }
  508. if ($isJson)
  509. {
  510. if (strlen($this->_error))
  511. {
  512. $this->_return_message(1, $this->_error);
  513. }
  514. else
  515. {
  516. $this->_return_message(0, $dataid, array('messages' => $messages));
  517. }
  518. }
  519. }
  520. /**
  521. * Display ZeroBin frontend.
  522. *
  523. * @access private
  524. * @return void
  525. */
  526. private function _view()
  527. {
  528. // set headers to disable caching
  529. $time = gmdate('D, d M Y H:i:s \G\M\T');
  530. header('Cache-Control: no-store, no-cache, must-revalidate');
  531. header('Pragma: no-cache');
  532. header('Expires: ' . $time);
  533. header('Last-Modified: ' . $time);
  534. header('Vary: Accept');
  535. // label all the expiration options
  536. $expire = array();
  537. foreach ($this->_conf->getSection('expire_options') as $time => $seconds)
  538. {
  539. $expire[$time] = ($seconds == 0) ? i18n::_(ucfirst($time)): filter::time_humanreadable($time);
  540. }
  541. // translate all the formatter options
  542. $formatters = array_map(array('i18n', 'translate'), $this->_conf->getSection('formatter_options'));
  543. // set language cookie if that functionality was enabled
  544. $languageselection = '';
  545. if ($this->_conf->getKey('languageselection'))
  546. {
  547. $languageselection = i18n::getLanguage();
  548. setcookie('lang', $languageselection);
  549. }
  550. $page = new RainTPL;
  551. $page::$path_replace = false;
  552. // we escape it here because ENT_NOQUOTES can't be used in RainTPL templates
  553. $page->assign('CIPHERDATA', htmlspecialchars($this->_data, ENT_NOQUOTES));
  554. $page->assign('ERROR', i18n::_($this->_error));
  555. $page->assign('STATUS', i18n::_($this->_status));
  556. $page->assign('VERSION', self::VERSION);
  557. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  558. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  559. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  560. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  561. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  562. $page->assign('FORMATTER', $formatters);
  563. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  564. $page->assign('NOTICE', i18n::_($this->_conf->getKey('notice')));
  565. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  566. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  567. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  568. $page->assign('BASE64JSVERSION', $this->_conf->getKey('base64version'));
  569. $page->assign('LANGUAGESELECTION', $languageselection);
  570. $page->assign('LANGUAGES', i18n::getLanguageLabels(i18n::getAvailableLanguages()));
  571. $page->assign('EXPIRE', $expire);
  572. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  573. $page->draw($this->_conf->getKey('template'));
  574. }
  575. /**
  576. * return JSON encoded message and exit
  577. *
  578. * @access private
  579. * @param bool $status
  580. * @param string $message
  581. * @param array $other
  582. * @return void
  583. */
  584. private function _return_message($status, $message, $other = array())
  585. {
  586. $result = array('status' => $status);
  587. if ($status)
  588. {
  589. $result['message'] = i18n::_($message);
  590. }
  591. else
  592. {
  593. $result['id'] = $message;
  594. }
  595. $result += $other;
  596. $this->_json = json_encode($result);
  597. }
  598. }