zerobin.php 19 KB

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