zerobin.php 22 KB

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