zerobin.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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.18';
  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 (array_key_exists($_POST['expire'], $this->_conf['expire_options'])) {
  175. $expire = $this->_conf['expire_options'][$_POST['expire']];
  176. } else {
  177. $expire = $this->_conf['expire_options'][$this->_conf['expire']['default']];
  178. }
  179. if ($expire > 0) $meta['expire_date'] = time() + $expire;
  180. }
  181. // Destroy the paste when it is read.
  182. if (!empty($_POST['burnafterreading']))
  183. {
  184. $burnafterreading = $_POST['burnafterreading'];
  185. if ($burnafterreading != '0')
  186. {
  187. if ($burnafterreading != '1') $error = true;
  188. $meta['burnafterreading'] = true;
  189. }
  190. }
  191. // Read open discussion flag.
  192. if ($this->_conf['main']['opendiscussion'] && !empty($_POST['opendiscussion']))
  193. {
  194. $opendiscussion = $_POST['opendiscussion'];
  195. if ($opendiscussion != 0)
  196. {
  197. if ($opendiscussion != 1) $error = true;
  198. $meta['opendiscussion'] = true;
  199. }
  200. }
  201. // You can't have an open discussion on a "Burn after reading" paste:
  202. if (isset($meta['burnafterreading'])) unset($meta['opendiscussion']);
  203. // Optional nickname for comments
  204. if (!empty($_POST['nickname']))
  205. {
  206. // Generation of the anonymous avatar (Vizhash):
  207. // If a nickname is provided, we generate a Vizhash.
  208. // (We assume that if the user did not enter a nickname, he/she wants
  209. // to be anonymous and we will not generate the vizhash.)
  210. $nick = $_POST['nickname'];
  211. if (!sjcl::isValid($nick))
  212. {
  213. $error = true;
  214. }
  215. else
  216. {
  217. $meta['nickname'] = $nick;
  218. $vz = new vizhash16x16();
  219. $pngdata = $vz->generate($_SERVER['REMOTE_ADDR']);
  220. if ($pngdata != '')
  221. {
  222. $meta['vizhash'] = 'data:image/png;base64,' . base64_encode($pngdata);
  223. }
  224. // Once the avatar is generated, we do not keep the IP address, nor its hash.
  225. }
  226. }
  227. if ($error) $this->_return_message(1, 'Invalid data.');
  228. // Add post date to meta.
  229. $meta['postdate'] = time();
  230. // We just want a small hash to avoid collisions:
  231. // Half-MD5 (64 bits) will do the trick
  232. $dataid = substr(hash('md5', $data), 0, 16);
  233. $storage = array('data' => $data);
  234. // Add meta-information only if necessary.
  235. if (count($meta)) $storage['meta'] = $meta;
  236. // The user posts a comment.
  237. if (
  238. !empty($_POST['parentid']) &&
  239. !empty($_POST['pasteid'])
  240. )
  241. {
  242. $pasteid = $_POST['pasteid'];
  243. $parentid = $_POST['parentid'];
  244. if (
  245. !preg_match('/\A[a-f\d]{16}\z/', $pasteid) ||
  246. !preg_match('/\A[a-f\d]{16}\z/', $parentid)
  247. ) $this->_return_message(1, 'Invalid data.');
  248. // Comments do not expire (it's the paste that expires)
  249. unset($storage['expire_date']);
  250. unset($storage['opendiscussion']);
  251. // Make sure paste exists.
  252. if (
  253. !$this->_model()->exists($pasteid)
  254. ) $this->_return_message(1, 'Invalid data.');
  255. // Make sure the discussion is opened in this paste.
  256. $paste = $this->_model()->read($pasteid);
  257. if (
  258. !$paste->meta->opendiscussion
  259. ) $this->_return_message(1, 'Invalid data.');
  260. // Check for improbable collision.
  261. if (
  262. $this->_model()->existsComment($pasteid, $parentid, $dataid)
  263. ) $this->_return_message(1, 'You are unlucky. Try again.');
  264. // New comment
  265. if (
  266. $this->_model()->createComment($pasteid, $parentid, $dataid, $storage) === false
  267. ) $this->_return_message(1, 'Error saving comment. Sorry.');
  268. // 0 = no error
  269. $this->_return_message(0, $dataid);
  270. }
  271. // The user posts a standard paste.
  272. else
  273. {
  274. // Check for improbable collision.
  275. if (
  276. $this->_model()->exists($dataid)
  277. ) $this->_return_message(1, 'You are unlucky. Try again.');
  278. // New paste
  279. if (
  280. $this->_model()->create($dataid, $storage) === false
  281. ) $this->_return_message(1, 'Error saving paste. Sorry.');
  282. // Generate the "delete" token.
  283. // The token is the hmac of the pasteid signed with the server salt.
  284. // The paste can be delete by calling http://myserver.com/zerobin/?pasteid=<pasteid>&deletetoken=<deletetoken>
  285. $deletetoken = hash_hmac('sha1', $dataid , serversalt::get());
  286. // 0 = no error
  287. $this->_return_message(0, $dataid, array('deletetoken' => $deletetoken));
  288. }
  289. $this->_return_message(1, 'Server error.');
  290. }
  291. /**
  292. * Delete an existing paste
  293. *
  294. * @access private
  295. * @param string $dataid
  296. * @param string $deletetoken
  297. * @return void
  298. */
  299. private function _delete($dataid, $deletetoken)
  300. {
  301. // Is this a valid paste identifier?
  302. if (preg_match('\A[a-f\d]{16}\z', $dataid))
  303. {
  304. // Check that paste exists.
  305. if (!$this->_model()->exists($dataid))
  306. {
  307. $this->_error = 'Paste does not exist, has expired or has been deleted.';
  308. return;
  309. }
  310. }
  311. // Make sure token is valid.
  312. if ($deletetoken != hash_hmac('sha1', $dataid , serversalt::get()))
  313. {
  314. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  315. return;
  316. }
  317. // Paste exists and deletion token is valid: Delete the paste.
  318. $this->_model()->delete($dataid);
  319. $this->_status = 'Paste was properly deleted.';
  320. }
  321. /**
  322. * Read an existing paste or comment
  323. *
  324. * @access private
  325. * @param string $dataid
  326. * @return void
  327. */
  328. private function _read($dataid)
  329. {
  330. // Is this a valid paste identifier?
  331. if (preg_match('#\A[a-f\d]{16}\z#', $dataid))
  332. {
  333. // Check that paste exists.
  334. if ($this->_model()->exists($dataid))
  335. {
  336. // Get the paste itself.
  337. $paste = $this->_model()->read($dataid);
  338. // See if paste has expired.
  339. if (
  340. isset($paste->meta->expire_date) &&
  341. $paste->meta->expire_date < time()
  342. )
  343. {
  344. // Delete the paste
  345. $this->_model()->delete($dataid);
  346. $this->_error = 'Paste does not exist, has expired or has been deleted.';
  347. }
  348. // If no error, return the paste.
  349. else
  350. {
  351. // We kindly provide the remaining time before expiration (in seconds)
  352. if (
  353. property_exists($paste->meta, 'expire_date')
  354. ) $paste->meta->remaining_time = $paste->meta->expire_date - time();
  355. // The paste itself is the first in the list of encrypted messages.
  356. $messages = array($paste);
  357. // If it's a discussion, get all comments.
  358. if (
  359. property_exists($paste->meta, 'opendiscussion') &&
  360. $paste->meta->opendiscussion
  361. )
  362. {
  363. $messages = array_merge(
  364. $messages,
  365. $this->_model()->readComments($dataid)
  366. );
  367. }
  368. $this->_data = json_encode($messages);
  369. // If the paste was meant to be read only once, delete it.
  370. if (
  371. property_exists($paste->meta, 'burnafterreading') &&
  372. $paste->meta->burnafterreading
  373. ) $this->_model()->delete($dataid);
  374. }
  375. }
  376. else
  377. {
  378. $this->_error = 'Paste does not exist or has expired.';
  379. }
  380. }
  381. }
  382. /**
  383. * Display ZeroBin frontend.
  384. *
  385. * @access private
  386. * @return void
  387. */
  388. private function _view()
  389. {
  390. // set headers to disable caching
  391. $time = gmdate('D, d M Y H:i:s \G\M\T');
  392. header('Cache-Control: no-store, no-cache, must-revalidate');
  393. header('Pragma: no-cache');
  394. header('Expires: ' . $time);
  395. header('Last-Modified: ' . $time);
  396. header('Vary: Accept');
  397. // label all the expiration options
  398. $expire = array();
  399. foreach ($this->_conf['expire_options'] as $key => $value) {
  400. $expire[$key] = array_key_exists($key, $this->_conf['expire_labels']) ?
  401. $this->_conf['expire_labels'][$key] :
  402. $key;
  403. }
  404. RainTPL::$path_replace = false;
  405. $page = new RainTPL;
  406. // we escape it here because ENT_NOQUOTES can't be used in RainTPL templates
  407. $page->assign('CIPHERDATA', htmlspecialchars($this->_data, ENT_NOQUOTES));
  408. $page->assign('ERROR', $this->_error);
  409. $page->assign('STATUS', $this->_status);
  410. $page->assign('VERSION', self::VERSION);
  411. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf['main']['burnafterreadingselected']);
  412. $page->assign('OPENDISCUSSION', $this->_conf['main']['opendiscussion']);
  413. $page->assign('SYNTAXHIGHLIGHTING', $this->_conf['main']['syntaxhighlighting']);
  414. $page->assign('EXPIRE', $expire);
  415. $page->assign('EXPIREDEFAULT', $this->_conf['expire']['default']);
  416. $page->draw($this->_conf['main']['template']);
  417. }
  418. /**
  419. * return JSON encoded message and exit
  420. *
  421. * @access private
  422. * @param bool $status
  423. * @param string $message
  424. * @param array $other
  425. * @return void
  426. */
  427. private function _return_message($status, $message, $other = array())
  428. {
  429. $result = array('status' => $status);
  430. if ($status)
  431. {
  432. $result['message'] = $message;
  433. }
  434. else
  435. {
  436. $result['id'] = $message;
  437. }
  438. $result += $other;
  439. exit(json_encode($result));
  440. }
  441. }