zerobin.php 17 KB

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