zerobin.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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.15
  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.15';
  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 zerobin_data
  43. */
  44. private $_model;
  45. /**
  46. * constructor
  47. *
  48. * initializes and runs ZeroBin
  49. *
  50. * @access public
  51. */
  52. public function __construct()
  53. {
  54. if (version_compare(PHP_VERSION, '5.2.6') < 0)
  55. die('ZeroBin requires php 5.2.6 or above to work. Sorry.');
  56. // In case stupid admin has left magic_quotes enabled in php.ini.
  57. if (get_magic_quotes_gpc())
  58. {
  59. $_POST = array_map('filter::stripslashes_deep', $_POST);
  60. $_GET = array_map('filter::stripslashes_deep', $_GET);
  61. $_COOKIE = array_map('filter::stripslashes_deep', $_COOKIE);
  62. }
  63. // Load config from ini file.
  64. $this->_init();
  65. // Create new paste or comment.
  66. if (!empty($_POST['data']))
  67. {
  68. $this->_create();
  69. }
  70. // Display an existing paste.
  71. elseif (!empty($_SERVER['QUERY_STRING']))
  72. {
  73. $this->_read();
  74. }
  75. // Display ZeroBin frontend
  76. $this->_view();
  77. }
  78. /**
  79. * initialize zerobin
  80. *
  81. * @access private
  82. * @return void
  83. */
  84. private function _init()
  85. {
  86. foreach (array('cfg', 'lib') as $dir)
  87. {
  88. if (!is_file(PATH . $dir . '/.htaccess')) file_put_contents(
  89. PATH . $dir . '/.htaccess',
  90. 'Allow from none' . PHP_EOL .
  91. 'Deny from all'. PHP_EOL
  92. );
  93. }
  94. $this->_conf = parse_ini_file(PATH . 'cfg/conf.ini', true);
  95. $this->_model = $this->_conf['model']['class'];
  96. }
  97. /**
  98. * get the model, create one if needed
  99. *
  100. * @access private
  101. * @return zerobin_data
  102. */
  103. private function _model()
  104. {
  105. // if needed, initialize the model
  106. if(is_string($this->_model)) {
  107. $this->_model = forward_static_call(
  108. array($this->_model, 'getInstance'),
  109. $this->_conf['model_options']
  110. );
  111. }
  112. return $this->_model;
  113. }
  114. /**
  115. * Store new paste or comment.
  116. *
  117. * POST contains:
  118. * data (mandatory) = json encoded SJCL encrypted text (containing keys: iv,salt,ct)
  119. *
  120. * All optional data will go to meta information:
  121. * expire (optional) = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:never)
  122. * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
  123. * nickname (optional) = in discussion, encoded SJCL encrypted text nickname of author of comment (containing keys: iv,salt,ct)
  124. * parentid (optional) = in discussion, which comment this comment replies to.
  125. * pasteid (optional) = in discussion, which paste this comment belongs to.
  126. *
  127. * @access private
  128. * @return void
  129. */
  130. private function _create()
  131. {
  132. header('Content-type: application/json');
  133. $error = false;
  134. // Make sure last paste from the IP address was more than X seconds ago.
  135. trafficlimiter::setLimit($this->_conf['traffic']['limit']);
  136. trafficlimiter::setPath($this->_conf['traffic']['dir']);
  137. if (
  138. !trafficlimiter::canPass($_SERVER['REMOTE_ADDR'])
  139. ) $this->_return_message(
  140. 1,
  141. 'Please wait ' .
  142. $this->_conf['traffic']['limit'] .
  143. ' seconds between each post.'
  144. );
  145. // Make sure content is not too big.
  146. $data = $_POST['data'];
  147. if (
  148. strlen($data) > $this->_conf['main']['sizelimit']
  149. ) $this->_return_message(
  150. 1,
  151. 'Paste is limited to ' .
  152. $this->_conf['main']['sizelimit'] .
  153. ' ' .
  154. filter::size_humanreadable($this->_conf['main']['sizelimit']) .
  155. ' of encrypted data.'
  156. );
  157. // Make sure format is correct.
  158. if (!sjcl::isValid($data)) $this->_return_message(1, 'Invalid data.');
  159. // Read additional meta-information.
  160. $meta=array();
  161. // Read expiration date
  162. if (!empty($_POST['expire']))
  163. {
  164. switch ($_POST['expire'])
  165. {
  166. case 'burn':
  167. $meta['burnafterreading'] = true;
  168. break;
  169. case '5min':
  170. $meta['expire_date'] = time()+5*60;
  171. break;
  172. case '10min':
  173. $meta['expire_date'] = time()+10*60;
  174. break;
  175. case '1hour':
  176. $meta['expire_date'] = time()+60*60;
  177. break;
  178. case '1day':
  179. $meta['expire_date'] = time()+24*60*60;
  180. break;
  181. case '1week':
  182. $meta['expire_date'] = time()+7*24*60*60;
  183. break;
  184. case '1month':
  185. $meta['expire_date'] = strtotime('+1 month');
  186. break;
  187. case '1year':
  188. $meta['expire_date'] = strtotime('+1 year');
  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-f\d]{16}/', $pasteid) ||
  246. !preg_match('/[a-f\d]{16}/', $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. // 0 = no error
  283. $this->_return_message(0, $dataid);
  284. }
  285. $this->_return_message(1, 'Server error.');
  286. }
  287. /**
  288. * Read an existing paste or comment.
  289. *
  290. * @access private
  291. * @return void
  292. */
  293. private function _read()
  294. {
  295. $dataid = $_SERVER['QUERY_STRING'];
  296. // Is this a valid paste identifier?
  297. if (preg_match('/[a-f\d]{16}/', $dataid))
  298. {
  299. // Check that paste exists.
  300. if ($this->_model()->exists($dataid))
  301. {
  302. // Get the paste itself.
  303. $paste = $this->_model()->read($dataid);
  304. // See if paste has expired.
  305. if (
  306. isset($paste->meta->expire_date) &&
  307. $paste->meta->expire_date < time()
  308. )
  309. {
  310. // Delete the paste
  311. $this->_model()->delete($dataid);
  312. $this->_error = 'Paste does not exist or has expired.';
  313. }
  314. // If no error, return the paste.
  315. else
  316. {
  317. // We kindly provide the remaining time before expiration (in seconds)
  318. if (
  319. property_exists($paste->meta, 'expire_date')
  320. ) $paste->meta->remaining_time = $paste->meta->expire_date - time();
  321. // The paste itself is the first in the list of encrypted messages.
  322. $messages = array($paste);
  323. // If it's a discussion, get all comments.
  324. if (
  325. property_exists($paste->meta, 'opendiscussion') &&
  326. $paste->meta->opendiscussion
  327. )
  328. {
  329. $messages = array_merge(
  330. $messages,
  331. $this->_model()->readComments($dataid)
  332. );
  333. }
  334. $this->_data = json_encode($messages);
  335. // If the paste was meant to be read only once, delete it.
  336. if (
  337. property_exists($paste->meta, 'burnafterreading') &&
  338. $paste->meta->burnafterreading
  339. ) $this->_model()->delete($dataid);
  340. }
  341. }
  342. else
  343. {
  344. $this->_error = 'Paste does not exist or has expired.';
  345. }
  346. }
  347. }
  348. /**
  349. * Display ZeroBin frontend.
  350. *
  351. * @access private
  352. * @return void
  353. */
  354. private function _view()
  355. {
  356. // set headers to disable caching
  357. $time = gmdate('D, d M Y H:i:s \G\M\T');
  358. header('Cache-Control: no-store, no-cache, must-revalidate');
  359. header('Pragma: no-cache');
  360. header('Expires: ' . $time);
  361. header('Last-Modified: ' . $time);
  362. header('Vary: Accept');
  363. $page = new RainTPL;
  364. // We escape it here because ENT_NOQUOTES can't be used in RainTPL templates.
  365. $page->assign('CIPHERDATA', htmlspecialchars($this->_data, ENT_NOQUOTES));
  366. $page->assign('ERRORMESSAGE', $this->_error);
  367. $page->assign('OPENDISCUSSION', $this->_conf['main']['opendiscussion']);
  368. $page->assign('VERSION', self::VERSION);
  369. $page->draw('page');
  370. }
  371. /**
  372. * return JSON encoded message and exit
  373. *
  374. * @access private
  375. * @param bool $status
  376. * @param string $message
  377. * @return void
  378. */
  379. private function _return_message($status, $message)
  380. {
  381. $result = array('status' => $status);
  382. if ($status)
  383. {
  384. $result['message'] = $message;
  385. }
  386. else
  387. {
  388. $result['id'] = $message;
  389. }
  390. exit(json_encode($result));
  391. }
  392. }