zerobin.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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. $has_attachmentname = $has_attachment && array_key_exists('attachmentname', $_POST) && !empty($_POST['attachmentname']);
  200. $data = array_key_exists('data', $_POST) ? $_POST['data'] : '';
  201. $attachment = $has_attachment ? $_POST['attachment'] : '';
  202. $attachmentname = $has_attachmentname ? $_POST['attachmentname'] : '';
  203. // Make sure last paste from the IP address was more than X seconds ago.
  204. trafficlimiter::setLimit($this->_conf['traffic']['limit']);
  205. trafficlimiter::setPath($this->_conf['traffic']['dir']);
  206. if (!trafficlimiter::canPass($_SERVER['REMOTE_ADDR']))
  207. {
  208. $this->_return_message(
  209. 1,
  210. i18n::_(
  211. 'Please wait %d seconds between each post.',
  212. $this->_conf['traffic']['limit']
  213. )
  214. );
  215. return;
  216. }
  217. // Make sure content is not too big.
  218. $sizelimit = (int) $this->_getMainConfig('sizelimit', 2097152);
  219. if (strlen($data) + strlen($attachment) + strlen($attachmentname) > $sizelimit)
  220. {
  221. $this->_return_message(
  222. 1,
  223. i18n::_(
  224. 'Paste is limited to %s of encrypted data.',
  225. filter::size_humanreadable($sizelimit)
  226. )
  227. );
  228. return;
  229. }
  230. // Make sure format is correct.
  231. if (!sjcl::isValid($data)) return $this->_return_message(1, 'Invalid data.');
  232. // Make sure attachments are enabled and format is correct.
  233. if($has_attachment)
  234. {
  235. if (
  236. !$this->_getMainConfig('fileupload', false) ||
  237. !sjcl::isValid($attachment) ||
  238. !($has_attachmentname && sjcl::isValid($attachmentname))
  239. ) $this->_return_message(1, 'Invalid attachment.');
  240. }
  241. // Read additional meta-information.
  242. $meta = array();
  243. // Read expiration date
  244. if (array_key_exists('expire', $_POST) && !empty($_POST['expire']))
  245. {
  246. $selected_expire = (string) $_POST['expire'];
  247. if (array_key_exists($selected_expire, $this->_conf['expire_options']))
  248. {
  249. $expire = $this->_conf['expire_options'][$selected_expire];
  250. }
  251. else
  252. {
  253. $expire = $this->_conf['expire_options'][$this->_conf['expire']['default']];
  254. }
  255. if ($expire > 0) $meta['expire_date'] = time() + $expire;
  256. }
  257. // Destroy the paste when it is read.
  258. if (array_key_exists('burnafterreading', $_POST) && !empty($_POST['burnafterreading']))
  259. {
  260. $burnafterreading = $_POST['burnafterreading'];
  261. if ($burnafterreading !== '0')
  262. {
  263. if ($burnafterreading !== '1') $error = true;
  264. $meta['burnafterreading'] = true;
  265. }
  266. }
  267. // Read open discussion flag.
  268. if (
  269. $this->_getMainConfig('discussion', true) &&
  270. array_key_exists('opendiscussion', $_POST) &&
  271. !empty($_POST['opendiscussion'])
  272. )
  273. {
  274. $opendiscussion = $_POST['opendiscussion'];
  275. if ($opendiscussion !== '0')
  276. {
  277. if ($opendiscussion !== '1') $error = true;
  278. $meta['opendiscussion'] = true;
  279. }
  280. }
  281. // Read formatter flag.
  282. if (array_key_exists('formatter', $_POST) && !empty($_POST['formatter']))
  283. {
  284. $formatter = $_POST['formatter'];
  285. if (!array_key_exists($formatter, $this->_conf['formatter_options']))
  286. {
  287. $formatter = $this->_getMainConfig('defaultformatter', 'syntaxhighlighting');
  288. }
  289. $meta['formatter'] = $formatter;
  290. }
  291. // You can't have an open discussion on a "Burn after reading" paste:
  292. if (isset($meta['burnafterreading'])) unset($meta['opendiscussion']);
  293. // Optional nickname for comments
  294. if (!empty($_POST['nickname']))
  295. {
  296. // Generation of the anonymous avatar (Vizhash):
  297. // If a nickname is provided, we generate a Vizhash.
  298. // (We assume that if the user did not enter a nickname, he/she wants
  299. // to be anonymous and we will not generate the vizhash.)
  300. $nick = $_POST['nickname'];
  301. if (!sjcl::isValid($nick))
  302. {
  303. $error = true;
  304. }
  305. else
  306. {
  307. $meta['nickname'] = $nick;
  308. $vz = new vizhash16x16();
  309. $pngdata = $vz->generate($_SERVER['REMOTE_ADDR']);
  310. if ($pngdata != '')
  311. {
  312. $meta['vizhash'] = 'data:image/png;base64,' . base64_encode($pngdata);
  313. }
  314. // Once the avatar is generated, we do not keep the IP address, nor its hash.
  315. }
  316. }
  317. if ($error)
  318. {
  319. $this->_return_message(1, 'Invalid data.');
  320. return;
  321. }
  322. // Add post date to meta.
  323. $meta['postdate'] = time();
  324. // We just want a small hash to avoid collisions:
  325. // Half-MD5 (64 bits) will do the trick
  326. $dataid = substr(hash('md5', $data), 0, 16);
  327. $storage = array('data' => $data);
  328. // Add meta-information only if necessary.
  329. if (count($meta)) $storage['meta'] = $meta;
  330. // The user posts a comment.
  331. if (
  332. !empty($_POST['parentid']) &&
  333. !empty($_POST['pasteid'])
  334. )
  335. {
  336. $pasteid = (string) $_POST['pasteid'];
  337. $parentid = (string) $_POST['parentid'];
  338. if (
  339. !filter::is_valid_paste_id($pasteid) ||
  340. !filter::is_valid_paste_id($parentid)
  341. )
  342. {
  343. $this->_return_message(1, 'Invalid data.');
  344. return;
  345. }
  346. // Comments do not expire (it's the paste that expires)
  347. unset($storage['expire_date']);
  348. unset($storage['opendiscussion']);
  349. // Make sure paste exists.
  350. if (
  351. !$this->_model()->exists($pasteid)
  352. )
  353. {
  354. $this->_return_message(1, 'Invalid data.');
  355. return;
  356. }
  357. // Make sure the discussion is opened in this paste.
  358. $paste = $this->_model()->read($pasteid);
  359. if (
  360. !$paste->meta->opendiscussion
  361. )
  362. {
  363. $this->_return_message(1, 'Invalid data.');
  364. return;
  365. }
  366. // Check for improbable collision.
  367. if (
  368. $this->_model()->existsComment($pasteid, $parentid, $dataid)
  369. )
  370. {
  371. $this->_return_message(1, 'You are unlucky. Try again.');
  372. return;
  373. }
  374. // New comment
  375. if (
  376. $this->_model()->createComment($pasteid, $parentid, $dataid, $storage) === false
  377. )
  378. {
  379. $this->_return_message(1, 'Error saving comment. Sorry.');
  380. return;
  381. }
  382. // 0 = no error
  383. $this->_return_message(0, $dataid);
  384. return;
  385. }
  386. // The user posts a standard paste.
  387. else
  388. {
  389. // Check for improbable collision.
  390. if (
  391. $this->_model()->exists($dataid)
  392. )
  393. {
  394. $this->_return_message(1, 'You are unlucky. Try again.');
  395. return;
  396. }
  397. // Add attachment and its name, if one was sent
  398. if ($has_attachment) $storage['attachment'] = $attachment;
  399. if ($has_attachmentname) $storage['attachmentname'] = $attachmentname;
  400. // New paste
  401. if (
  402. $this->_model()->create($dataid, $storage) === false
  403. ) {
  404. $this->_return_message(1, 'Error saving paste. Sorry.');
  405. return;
  406. }
  407. // Generate the "delete" token.
  408. // The token is the hmac of the pasteid signed with the server salt.
  409. // The paste can be delete by calling http://example.com/zerobin/?pasteid=<pasteid>&deletetoken=<deletetoken>
  410. $deletetoken = hash_hmac('sha1', $dataid, serversalt::get());
  411. // 0 = no error
  412. $this->_return_message(0, $dataid, array('deletetoken' => $deletetoken));
  413. return;
  414. }
  415. }
  416. /**
  417. * Delete an existing paste
  418. *
  419. * @access private
  420. * @param string $dataid
  421. * @param string $deletetoken
  422. * @return void
  423. */
  424. private function _delete($dataid, $deletetoken)
  425. {
  426. // Is this a valid paste identifier?
  427. if (!filter::is_valid_paste_id($dataid))
  428. {
  429. $this->_error = 'Invalid paste ID.';
  430. return;
  431. }
  432. // Check that paste exists.
  433. if (!$this->_model()->exists($dataid))
  434. {
  435. $this->_error = self::GENERIC_ERROR;
  436. return;
  437. }
  438. // Get the paste itself.
  439. $paste = $this->_model()->read($dataid);
  440. // See if paste has expired.
  441. if (
  442. isset($paste->meta->expire_date) &&
  443. $paste->meta->expire_date < time()
  444. )
  445. {
  446. // Delete the paste
  447. $this->_model()->delete($dataid);
  448. $this->_error = self::GENERIC_ERROR;
  449. return;
  450. }
  451. if ($deletetoken == 'burnafterreading') {
  452. if (
  453. isset($paste->meta->burnafterreading) &&
  454. $paste->meta->burnafterreading
  455. )
  456. {
  457. // Delete the paste
  458. $this->_model()->delete($dataid);
  459. $this->_return_message(0, $dataid);
  460. }
  461. else
  462. {
  463. $this->_return_message(1, 'Paste is not of burn-after-reading type.');
  464. }
  465. return;
  466. }
  467. // Make sure token is valid.
  468. serversalt::setPath($this->_conf['traffic']['dir']);
  469. if (!filter::slow_equals($deletetoken, hash_hmac('sha1', $dataid, serversalt::get())))
  470. {
  471. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  472. return;
  473. }
  474. // Paste exists and deletion token is valid: Delete the paste.
  475. $this->_model()->delete($dataid);
  476. $this->_status = 'Paste was properly deleted.';
  477. }
  478. /**
  479. * Read an existing paste or comment
  480. *
  481. * @access private
  482. * @param string $dataid
  483. * @return void
  484. */
  485. private function _read($dataid)
  486. {
  487. $isJson = false;
  488. if (($pos = strpos($dataid, '&json')) !== false) {
  489. $isJson = true;
  490. $dataid = substr($dataid, 0, $pos);
  491. }
  492. // Is this a valid paste identifier?
  493. if (!filter::is_valid_paste_id($dataid))
  494. {
  495. $this->_error = 'Invalid paste ID.';
  496. return;
  497. }
  498. // Check that paste exists.
  499. if ($this->_model()->exists($dataid))
  500. {
  501. // Get the paste itself.
  502. $paste = $this->_model()->read($dataid);
  503. // See if paste has expired.
  504. if (
  505. isset($paste->meta->expire_date) &&
  506. $paste->meta->expire_date < time()
  507. )
  508. {
  509. // Delete the paste
  510. $this->_model()->delete($dataid);
  511. $this->_error = self::GENERIC_ERROR;
  512. }
  513. // If no error, return the paste.
  514. else
  515. {
  516. // We kindly provide the remaining time before expiration (in seconds)
  517. if (
  518. property_exists($paste->meta, 'expire_date')
  519. ) $paste->meta->remaining_time = $paste->meta->expire_date - time();
  520. // The paste itself is the first in the list of encrypted messages.
  521. $messages = array($paste);
  522. // If it's a discussion, get all comments.
  523. if (
  524. property_exists($paste->meta, 'opendiscussion') &&
  525. $paste->meta->opendiscussion
  526. )
  527. {
  528. $messages = array_merge(
  529. $messages,
  530. $this->_model()->readComments($dataid)
  531. );
  532. }
  533. // set formatter for for the view.
  534. if (!property_exists($paste->meta, 'formatter'))
  535. {
  536. // support < 0.21 syntax highlighting
  537. if (property_exists($paste->meta, 'syntaxcoloring') && $paste->meta->syntaxcoloring === true)
  538. {
  539. $paste->meta->formatter = 'syntaxhighlighting';
  540. }
  541. else
  542. {
  543. $paste->meta->formatter = $this->_getMainConfig('defaultformatter', 'syntaxhighlighting');
  544. }
  545. }
  546. $this->_data = json_encode($messages);
  547. }
  548. }
  549. else
  550. {
  551. $this->_error = self::GENERIC_ERROR;
  552. }
  553. if ($isJson)
  554. {
  555. if (strlen($this->_error))
  556. {
  557. $this->_return_message(1, $this->_error);
  558. }
  559. else
  560. {
  561. $this->_return_message(0, $dataid, array('messages' => $messages));
  562. }
  563. }
  564. }
  565. /**
  566. * Display ZeroBin frontend.
  567. *
  568. * @access private
  569. * @return void
  570. */
  571. private function _view()
  572. {
  573. // set headers to disable caching
  574. $time = gmdate('D, d M Y H:i:s \G\M\T');
  575. header('Cache-Control: no-store, no-cache, must-revalidate');
  576. header('Pragma: no-cache');
  577. header('Expires: ' . $time);
  578. header('Last-Modified: ' . $time);
  579. header('Vary: Accept');
  580. // label all the expiration options
  581. $expire = array();
  582. foreach ($this->_conf['expire_options'] as $time => $seconds)
  583. {
  584. $expire[$time] = ($seconds == 0) ? i18n::_(ucfirst($time)): filter::time_humanreadable($time);
  585. }
  586. // translate all the formatter options
  587. $formatters = array_map(array('i18n', 'translate'), $this->_conf['formatter_options']);
  588. $page = new RainTPL;
  589. $page::$path_replace = false;
  590. // we escape it here because ENT_NOQUOTES can't be used in RainTPL templates
  591. $page->assign('CIPHERDATA', htmlspecialchars($this->_data, ENT_NOQUOTES));
  592. $page->assign('ERROR', i18n::_($this->_error));
  593. $page->assign('STATUS', i18n::_($this->_status));
  594. $page->assign('VERSION', self::VERSION);
  595. $page->assign('DISCUSSION', $this->_getMainConfig('discussion', true));
  596. $page->assign('OPENDISCUSSION', $this->_getMainConfig('opendiscussion', true));
  597. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  598. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  599. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_getMainConfig('syntaxhighlightingtheme', ''));
  600. $page->assign('FORMATTER', $formatters);
  601. $page->assign('FORMATTERDEFAULT', $this->_getMainConfig('defaultformatter', 'syntaxhighlighting'));
  602. $page->assign('NOTICE', i18n::_($this->_getMainConfig('notice', '')));
  603. $page->assign('BURNAFTERREADINGSELECTED', $this->_getMainConfig('burnafterreadingselected', false));
  604. $page->assign('PASSWORD', $this->_getMainConfig('password', true));
  605. $page->assign('FILEUPLOAD', $this->_getMainConfig('fileupload', false));
  606. $page->assign('BASE64JSVERSION', $this->_getMainConfig('base64version', '2.1.9'));
  607. $page->assign('EXPIRE', $expire);
  608. $page->assign('EXPIREDEFAULT', $this->_conf['expire']['default']);
  609. $page->draw($this->_getMainConfig('template', 'page'));
  610. }
  611. /**
  612. * get configuration option from [main] section, optionally set a default
  613. *
  614. * @access private
  615. * @param string $option
  616. * @param mixed $default (optional)
  617. * @return mixed
  618. */
  619. private function _getMainConfig($option, $default = false)
  620. {
  621. return array_key_exists($option, $this->_conf['main']) ?
  622. $this->_conf['main'][$option] :
  623. $default;
  624. }
  625. /**
  626. * return JSON encoded message and exit
  627. *
  628. * @access private
  629. * @param bool $status
  630. * @param string $message
  631. * @param array $other
  632. * @return void
  633. */
  634. private function _return_message($status, $message, $other = array())
  635. {
  636. $result = array('status' => $status);
  637. if ($status)
  638. {
  639. $result['message'] = i18n::_($message);
  640. }
  641. else
  642. {
  643. $result['id'] = $message;
  644. }
  645. $result += $other;
  646. $this->_json = json_encode($result);
  647. }
  648. }