zerobin.php 17 KB

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