zerobin.php 16 KB

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