zerobin.php 20 KB

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