zerobin.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. require_once PATH . 'lib/filter.php';
  60. $_POST = array_map('filter::stripslashes_deep', $_POST);
  61. $_GET = array_map('filter::stripslashes_deep', $_GET);
  62. $_COOKIE = array_map('filter::stripslashes_deep', $_COOKIE);
  63. }
  64. // Load config from ini file.
  65. $this->_init();
  66. // Create new paste or comment.
  67. if (!empty($_POST['data']))
  68. {
  69. $this->_create();
  70. }
  71. // Display an existing paste.
  72. elseif (!empty($_SERVER['QUERY_STRING']))
  73. {
  74. $this->_read();
  75. }
  76. // Display ZeroBin frontend
  77. $this->_view();
  78. }
  79. /**
  80. * initialize zerobin
  81. *
  82. * @access private
  83. * @return void
  84. */
  85. private function _init()
  86. {
  87. foreach (array('cfg', 'lib') as $dir)
  88. {
  89. if (!is_file(PATH . $dir . '/.htaccess')) file_put_contents(
  90. PATH . $dir . '/.htaccess',
  91. 'Allow from none' . PHP_EOL .
  92. 'Deny from all'. PHP_EOL
  93. );
  94. }
  95. $this->_conf = parse_ini_file(PATH . 'cfg/conf.ini');
  96. $this->_model = $this->_conf['model'];
  97. }
  98. /**
  99. * get the model, create one if needed
  100. *
  101. * @access private
  102. * @return zerobin_data
  103. */
  104. private function _model()
  105. {
  106. // if needed, initialize the model
  107. if(is_string($this->_model)) {
  108. require_once PATH . 'lib/' . $this->_model . '.php';
  109. $this->_model = forward_static_call(array($this->_model, 'getInstance'), $this->_conf['model_options']);
  110. }
  111. return $this->_model;
  112. }
  113. /**
  114. * Store new paste or comment.
  115. *
  116. * POST contains:
  117. * data (mandatory) = json encoded SJCL encrypted text (containing keys: iv,salt,ct)
  118. *
  119. * All optional data will go to meta information:
  120. * expire (optional) = expiration delay (never,10min,1hour,1day,1month,1year,burn) (default:never)
  121. * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
  122. * nickname (optional) = in discussion, encoded SJCL encrypted text nickname of author of comment (containing keys: iv,salt,ct)
  123. * parentid (optional) = in discussion, which comment this comment replies to.
  124. * pasteid (optional) = in discussion, which paste this comment belongs to.
  125. *
  126. * @access private
  127. * @return void
  128. */
  129. private function _create()
  130. {
  131. header('Content-type: application/json');
  132. $error = false;
  133. // Make sure last paste from the IP address was more than 10 seconds ago.
  134. require_once PATH . 'lib/traffic_limiter.php';
  135. traffic_limiter::setLimit($this->_conf['traffic_limit']);
  136. traffic_limiter::setPath($this->_conf['traffic_dir']);
  137. if (
  138. !traffic_limiter::canPass($_SERVER['REMOTE_ADDR'])
  139. ) $this->_return_message(1, 'Please wait 10 seconds between each post.');
  140. // Make sure content is not too big.
  141. $data = $_POST['data'];
  142. if (
  143. strlen($data) > 2000000
  144. ) $this->_return_message(1, 'Paste is limited to 2 MB of encrypted data.');
  145. // Make sure format is correct.
  146. require_once PATH . 'lib/sjcl.php';
  147. if (!sjcl::isValid($data)) $this->_return_message(1, 'Invalid data.');
  148. // Read additional meta-information.
  149. $meta=array();
  150. // Read expiration date
  151. if (!empty($_POST['expire']))
  152. {
  153. switch ($_POST['expire'])
  154. {
  155. case '10min':
  156. $meta['expire_date'] = time()+10*60;
  157. break;
  158. case '1hour':
  159. $meta['expire_date'] = time()+60*60;
  160. break;
  161. case '1day':
  162. $meta['expire_date'] = time()+24*60*60;
  163. break;
  164. case '1month':
  165. $meta['expire_date'] = strtotime('+1 month');
  166. break;
  167. case '1year':
  168. $meta['expire_date'] = strtotime('+1 year');
  169. break;
  170. case 'burn':
  171. $meta['burnafterreading'] = true;
  172. }
  173. }
  174. // Read open discussion flag.
  175. if (!empty($_POST['opendiscussion']))
  176. {
  177. $opendiscussion = $_POST['opendiscussion'];
  178. if ($opendiscussion != 0)
  179. {
  180. if ($opendiscussion != 1) $error = true;
  181. $meta['opendiscussion'] = true;
  182. }
  183. }
  184. // You can't have an open discussion on a "Burn after reading" paste:
  185. if (isset($meta['burnafterreading'])) unset($meta['opendiscussion']);
  186. // Optional nickname for comments
  187. if (!empty($_POST['nickname']))
  188. {
  189. // Generation of the anonymous avatar (Vizhash):
  190. // If a nickname is provided, we generate a Vizhash.
  191. // (We assume that if the user did not enter a nickname, he/she wants
  192. // to be anonymous and we will not generate the vizhash.)
  193. $nick = $_POST['nickname'];
  194. if (!sjcl::isValid($nick))
  195. {
  196. $error = true;
  197. }
  198. else
  199. {
  200. require_once PATH . 'lib/vizhash_gd_zero.php';
  201. $meta['nickname'] = $nick;
  202. $vz = new vizhash16x16();
  203. $pngdata = $vz->generate($_SERVER['REMOTE_ADDR']);
  204. if ($pngdata != '')
  205. {
  206. $meta['vizhash'] = 'data:image/png;base64,' . base64_encode($pngdata);
  207. }
  208. // Once the avatar is generated, we do not keep the IP address, nor its hash.
  209. }
  210. }
  211. if ($error) $this->_return_message(1, 'Invalid data.');
  212. // Add post date to meta.
  213. $meta['postdate'] = time();
  214. // We just want a small hash to avoid collisions:
  215. // Half-MD5 (64 bits) will do the trick
  216. $dataid = substr(hash('md5', $data), 0, 16);
  217. $storage = array('data' => $data);
  218. // Add meta-information only if necessary.
  219. if (count($meta)) $storage['meta'] = $meta;
  220. // The user posts a comment.
  221. if (
  222. !empty($_POST['parentid']) &&
  223. !empty($_POST['pasteid'])
  224. )
  225. {
  226. $pasteid = $_POST['pasteid'];
  227. $parentid = $_POST['parentid'];
  228. if (
  229. !preg_match('/[a-f\d]{16}/', $pasteid) ||
  230. !preg_match('/[a-f\d]{16}/', $parentid)
  231. ) $this->_return_message(1, 'Invalid data.');
  232. // Comments do not expire (it's the paste that expires)
  233. unset($storage['expire_date']);
  234. unset($storage['opendiscussion']);
  235. // Make sure paste exists.
  236. if (
  237. !$this->_model()->exists($pasteid)
  238. ) $this->_return_message(1, 'Invalid data.');
  239. // Make sure the discussion is opened in this paste.
  240. $paste = $this->_model()->read($pasteid);
  241. if (
  242. !$paste->meta->opendiscussion
  243. ) $this->_return_message(1, 'Invalid data.');
  244. // Check for improbable collision.
  245. if (
  246. $this->_model()->existsComment($pasteid, $parentid, $dataid)
  247. ) $this->_return_message(1, 'You are unlucky. Try again.');
  248. // New comment
  249. if (
  250. $this->_model()->createComment($pasteid, $parentid, $dataid, $storage) === false
  251. ) $this->_return_message(1, 'Error saving comment. Sorry.');
  252. // 0 = no error
  253. $this->_return_message(0, $dataid);
  254. }
  255. // The user posts a standard paste.
  256. else
  257. {
  258. // Check for improbable collision.
  259. if (
  260. $this->_model()->exists($dataid)
  261. ) $this->_return_message(1, 'You are unlucky. Try again.');
  262. // New paste
  263. if (
  264. $this->_model()->create($dataid, $storage) === false
  265. ) $this->_return_message(1, 'Error saving paste. Sorry.');
  266. // 0 = no error
  267. $this->_return_message(0, $dataid);
  268. }
  269. $this->_return_message(1, 'Server error.');
  270. }
  271. /**
  272. * Read an existing paste or comment.
  273. *
  274. * @access private
  275. * @return void
  276. */
  277. private function _read()
  278. {
  279. $dataid = $_SERVER['QUERY_STRING'];
  280. // Is this a valid paste identifier?
  281. if (preg_match('/[a-f\d]{16}/', $dataid))
  282. {
  283. // Check that paste exists.
  284. if ($this->_model()->exists($dataid))
  285. {
  286. // Get the paste itself.
  287. $paste = $this->_model()->read($dataid);
  288. // See if paste has expired.
  289. if (
  290. isset($paste->meta->expire_date) &&
  291. $paste->meta->expire_date < time()
  292. )
  293. {
  294. // Delete the paste
  295. $this->_model()->delete($dataid);
  296. $this->_error = 'Paste does not exist or has expired.';
  297. }
  298. // If no error, return the paste.
  299. else
  300. {
  301. // We kindly provide the remaining time before expiration (in seconds)
  302. if (
  303. property_exists($paste->meta, 'expire_date')
  304. ) $paste->meta->remaining_time = $paste->meta->expire_date - time();
  305. // The paste itself is the first in the list of encrypted messages.
  306. $messages = array($paste);
  307. // If it's a discussion, get all comments.
  308. if (
  309. property_exists($paste->meta, 'opendiscussion') &&
  310. $paste->meta->opendiscussion
  311. )
  312. {
  313. $messages = array_merge(
  314. $messages,
  315. $this->_model()->readComments($dataid)
  316. );
  317. }
  318. $this->_data = json_encode($messages);
  319. // If the paste was meant to be read only once, delete it.
  320. if (
  321. property_exists($paste->meta, 'burnafterreading') &&
  322. $paste->meta->burnafterreading
  323. ) $this->_model()->delete($dataid);
  324. }
  325. }
  326. else
  327. {
  328. $this->_error = 'Paste does not exist or has expired.';
  329. }
  330. }
  331. }
  332. /**
  333. * Display ZeroBin frontend.
  334. *
  335. * @access private
  336. * @return void
  337. */
  338. private function _view()
  339. {
  340. require_once PATH . 'lib/rain.tpl.class.php';
  341. header('Content-Type: text/html; charset=utf-8');
  342. $page = new RainTPL;
  343. // We escape it here because ENT_NOQUOTES can't be used in RainTPL templates.
  344. $page->assign('CIPHERDATA', htmlspecialchars($this->_data, ENT_NOQUOTES));
  345. $page->assign('ERRORMESSAGE', $this->_error);
  346. $page->assign('VERSION', self::VERSION);
  347. $page->draw('page');
  348. }
  349. /**
  350. * return JSON encoded message and exit
  351. *
  352. * @access private
  353. * @param bool $status
  354. * @param string $message
  355. * @return void
  356. */
  357. private function _return_message($status, $message)
  358. {
  359. $result = array('status' => $status);
  360. if ($status)
  361. {
  362. $result['message'] = $message;
  363. }
  364. else
  365. {
  366. $result['id'] = $message;
  367. }
  368. exit(json_encode($result));
  369. }
  370. }