zerobin.php 18 KB

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