zerobin.php 19 KB

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