zerobin.php 15 KB

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