zerobin.php 22 KB

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