zerobin.php 13 KB

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