zerobin.php 23 KB

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