zerobin.php 12 KB

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