1
0

privatebin.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. <?php
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 0.22
  11. */
  12. namespace PrivateBin;
  13. use Exception;
  14. /**
  15. * privatebin
  16. *
  17. * Controller, puts it all together.
  18. */
  19. class privatebin
  20. {
  21. /**
  22. * version
  23. *
  24. * @const string
  25. */
  26. const VERSION = '0.22';
  27. /**
  28. * show the same error message if the paste expired or does not exist
  29. *
  30. * @const string
  31. */
  32. const GENERIC_ERROR = 'Paste does not exist, has expired or has been deleted.';
  33. /**
  34. * configuration
  35. *
  36. * @access private
  37. * @var configuration
  38. */
  39. private $_conf;
  40. /**
  41. * data
  42. *
  43. * @access private
  44. * @var string
  45. */
  46. private $_data = '';
  47. /**
  48. * does the paste expire
  49. *
  50. * @access private
  51. * @var bool
  52. */
  53. private $_doesExpire = false;
  54. /**
  55. * error message
  56. *
  57. * @access private
  58. * @var string
  59. */
  60. private $_error = '';
  61. /**
  62. * status message
  63. *
  64. * @access private
  65. * @var string
  66. */
  67. private $_status = '';
  68. /**
  69. * JSON message
  70. *
  71. * @access private
  72. * @var string
  73. */
  74. private $_json = '';
  75. /**
  76. * Factory of instance models
  77. *
  78. * @access private
  79. * @var model
  80. */
  81. private $_model;
  82. /**
  83. * request
  84. *
  85. * @access private
  86. * @var request
  87. */
  88. private $_request;
  89. /**
  90. * URL base
  91. *
  92. * @access private
  93. * @var string
  94. */
  95. private $_urlbase;
  96. /**
  97. * constructor
  98. *
  99. * initializes and runs PrivateBin
  100. *
  101. * @access public
  102. * @return void
  103. */
  104. public function __construct()
  105. {
  106. if (version_compare(PHP_VERSION, '5.3.0') < 0) {
  107. throw new Exception(i18n::_('PrivateBin requires php 5.3.0 or above to work. Sorry.'), 1);
  108. }
  109. // load config from ini file
  110. $this->_init();
  111. switch ($this->_request->getOperation()) {
  112. case 'create':
  113. $this->_create();
  114. break;
  115. case 'delete':
  116. $this->_delete(
  117. $this->_request->getParam('pasteid'),
  118. $this->_request->getParam('deletetoken')
  119. );
  120. break;
  121. case 'read':
  122. $this->_read($this->_request->getParam('pasteid'));
  123. break;
  124. case 'jsonld':
  125. $this->_jsonld($this->_request->getParam('jsonld'));
  126. return;
  127. }
  128. // output JSON or HTML
  129. if ($this->_request->isJsonApiCall()) {
  130. header('Content-type: ' . request::MIME_JSON);
  131. header('Access-Control-Allow-Origin: *');
  132. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
  133. header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
  134. echo $this->_json;
  135. } else {
  136. $this->_view();
  137. }
  138. }
  139. /**
  140. * initialize privatebin
  141. *
  142. * @access private
  143. * @return void
  144. */
  145. private function _init()
  146. {
  147. foreach (array('cfg', 'lib') as $dir) {
  148. if (!is_file(PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess')) {
  149. file_put_contents(
  150. PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess',
  151. 'Allow from none' . PHP_EOL .
  152. 'Deny from all'. PHP_EOL,
  153. LOCK_EX
  154. );
  155. }
  156. }
  157. $this->_conf = new configuration;
  158. $this->_model = new model($this->_conf);
  159. $this->_request = new request;
  160. $this->_urlbase = array_key_exists('REQUEST_URI', $_SERVER) ?
  161. htmlspecialchars($_SERVER['REQUEST_URI']) : '/';
  162. // set default language
  163. $lang = $this->_conf->getKey('languagedefault');
  164. i18n::setLanguageFallback($lang);
  165. // force default language, if language selection is disabled and a default is set
  166. if (!$this->_conf->getKey('languageselection') && strlen($lang) == 2) {
  167. $_COOKIE['lang'] = $lang;
  168. setcookie('lang', $lang);
  169. }
  170. }
  171. /**
  172. * Store new paste or comment
  173. *
  174. * POST contains one or both:
  175. * data = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  176. * attachment = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  177. *
  178. * All optional data will go to meta information:
  179. * expire (optional) = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:never)
  180. * formatter (optional) = format to display the paste as (plaintext,syntaxhighlighting,markdown) (default:syntaxhighlighting)
  181. * burnafterreading (optional) = if this paste may only viewed once ? (0/1) (default:0)
  182. * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
  183. * attachmentname = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  184. * nickname (optional) = in discussion, encoded SJCL encrypted text nickname of author of comment (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  185. * parentid (optional) = in discussion, which comment this comment replies to.
  186. * pasteid (optional) = in discussion, which paste this comment belongs to.
  187. *
  188. * @access private
  189. * @return string
  190. */
  191. private function _create()
  192. {
  193. // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
  194. trafficlimiter::setConfiguration($this->_conf);
  195. if (!trafficlimiter::canPass()) {
  196. return $this->_return_message(
  197. 1, i18n::_(
  198. 'Please wait %d seconds between each post.',
  199. $this->_conf->getKey('limit', 'traffic')
  200. )
  201. );
  202. }
  203. $data = $this->_request->getParam('data');
  204. $attachment = $this->_request->getParam('attachment');
  205. $attachmentname = $this->_request->getParam('attachmentname');
  206. // Ensure content is not too big.
  207. $sizelimit = $this->_conf->getKey('sizelimit');
  208. if (
  209. strlen($data) + strlen($attachment) + strlen($attachmentname) > $sizelimit
  210. ) {
  211. return $this->_return_message(
  212. 1,
  213. i18n::_(
  214. 'Paste is limited to %s of encrypted data.',
  215. filter::size_humanreadable($sizelimit)
  216. )
  217. );
  218. }
  219. // Ensure attachment did not get lost due to webserver limits or Suhosin
  220. if (strlen($attachmentname) > 0 && strlen($attachment) == 0) {
  221. return $this->_return_message(1, 'Attachment missing in data received by server. Please check your webserver or suhosin configuration for maximum POST parameter limitations.');
  222. }
  223. // The user posts a comment.
  224. $pasteid = $this->_request->getParam('pasteid');
  225. $parentid = $this->_request->getParam('parentid');
  226. if (!empty($pasteid) && !empty($parentid)) {
  227. $paste = $this->_model->getPaste($pasteid);
  228. if ($paste->exists()) {
  229. try {
  230. $comment = $paste->getComment($parentid);
  231. $nickname = $this->_request->getParam('nickname');
  232. if (!empty($nickname)) {
  233. $comment->setNickname($nickname);
  234. }
  235. $comment->setData($data);
  236. $comment->store();
  237. } catch (Exception $e) {
  238. return $this->_return_message(1, $e->getMessage());
  239. }
  240. $this->_return_message(0, $comment->getId());
  241. } else {
  242. $this->_return_message(1, 'Invalid data.');
  243. }
  244. }
  245. // The user posts a standard paste.
  246. else {
  247. $this->_model->purge();
  248. $paste = $this->_model->getPaste();
  249. try {
  250. $paste->setData($data);
  251. if (!empty($attachment)) {
  252. $paste->setAttachment($attachment);
  253. if (!empty($attachmentname)) {
  254. $paste->setAttachmentName($attachmentname);
  255. }
  256. }
  257. $expire = $this->_request->getParam('expire');
  258. if (!empty($expire)) {
  259. $paste->setExpiration($expire);
  260. }
  261. $burnafterreading = $this->_request->getParam('burnafterreading');
  262. if (!empty($burnafterreading)) {
  263. $paste->setBurnafterreading($burnafterreading);
  264. }
  265. $opendiscussion = $this->_request->getParam('opendiscussion');
  266. if (!empty($opendiscussion)) {
  267. $paste->setOpendiscussion($opendiscussion);
  268. }
  269. $formatter = $this->_request->getParam('formatter');
  270. if (!empty($formatter)) {
  271. $paste->setFormatter($formatter);
  272. }
  273. $paste->store();
  274. } catch (Exception $e) {
  275. return $this->_return_message(1, $e->getMessage());
  276. }
  277. $this->_return_message(0, $paste->getId(), array('deletetoken' => $paste->getDeleteToken()));
  278. }
  279. }
  280. /**
  281. * Delete an existing paste
  282. *
  283. * @access private
  284. * @param string $dataid
  285. * @param string $deletetoken
  286. * @return void
  287. */
  288. private function _delete($dataid, $deletetoken)
  289. {
  290. try {
  291. $paste = $this->_model->getPaste($dataid);
  292. if ($paste->exists()) {
  293. // accessing this property ensures that the paste would be
  294. // deleted if it has already expired
  295. $burnafterreading = $paste->isBurnafterreading();
  296. if ($deletetoken == 'burnafterreading') {
  297. if ($burnafterreading) {
  298. $paste->delete();
  299. $this->_return_message(0, $dataid);
  300. } else {
  301. $this->_return_message(1, 'Paste is not of burn-after-reading type.');
  302. }
  303. } else {
  304. // Make sure the token is valid.
  305. if (filter::slow_equals($deletetoken, $paste->getDeleteToken())) {
  306. // Paste exists and deletion token is valid: Delete the paste.
  307. $paste->delete();
  308. $this->_status = 'Paste was properly deleted.';
  309. } else {
  310. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  311. }
  312. }
  313. } else {
  314. $this->_error = self::GENERIC_ERROR;
  315. }
  316. } catch (Exception $e) {
  317. $this->_error = $e->getMessage();
  318. }
  319. }
  320. /**
  321. * Read an existing paste or comment
  322. *
  323. * @access private
  324. * @param string $dataid
  325. * @return void
  326. */
  327. private function _read($dataid)
  328. {
  329. try {
  330. $paste = $this->_model->getPaste($dataid);
  331. if ($paste->exists()) {
  332. $data = $paste->get();
  333. $this->_doesExpire = property_exists($data, 'meta') && property_exists($data->meta, 'expire_date');
  334. if (property_exists($data->meta, 'salt')) {
  335. unset($data->meta->salt);
  336. }
  337. $this->_data = json_encode($data);
  338. } else {
  339. $this->_error = self::GENERIC_ERROR;
  340. }
  341. } catch (Exception $e) {
  342. $this->_error = $e->getMessage();
  343. }
  344. if ($this->_request->isJsonApiCall()) {
  345. if (strlen($this->_error)) {
  346. $this->_return_message(1, $this->_error);
  347. } else {
  348. $this->_return_message(0, $dataid, json_decode($this->_data, true));
  349. }
  350. }
  351. }
  352. /**
  353. * Display PrivateBin frontend.
  354. *
  355. * @access private
  356. * @return void
  357. */
  358. private function _view()
  359. {
  360. // set headers to disable caching
  361. $time = gmdate('D, d M Y H:i:s \G\M\T');
  362. header('Cache-Control: no-store, no-cache, must-revalidate');
  363. header('Pragma: no-cache');
  364. header('Expires: ' . $time);
  365. header('Last-Modified: ' . $time);
  366. header('Vary: Accept');
  367. // label all the expiration options
  368. $expire = array();
  369. foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
  370. $expire[$time] = ($seconds == 0) ? i18n::_(ucfirst($time)): filter::time_humanreadable($time);
  371. }
  372. // translate all the formatter options
  373. $formatters = array_map(array('PrivateBin\\i18n', 'translate'), $this->_conf->getSection('formatter_options'));
  374. // set language cookie if that functionality was enabled
  375. $languageselection = '';
  376. if ($this->_conf->getKey('languageselection')) {
  377. $languageselection = i18n::getLanguage();
  378. setcookie('lang', $languageselection);
  379. }
  380. $page = new view;
  381. $page->assign('CIPHERDATA', $this->_data);
  382. $page->assign('ERROR', i18n::_($this->_error));
  383. $page->assign('STATUS', i18n::_($this->_status));
  384. $page->assign('VERSION', self::VERSION);
  385. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  386. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  387. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  388. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  389. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  390. $page->assign('FORMATTER', $formatters);
  391. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  392. $page->assign('NOTICE', i18n::_($this->_conf->getKey('notice')));
  393. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  394. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  395. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  396. $page->assign('BASE64JSVERSION', $this->_conf->getKey('zerobincompatibility') ? '1.7' : '2.1.9');
  397. $page->assign('LANGUAGESELECTION', $languageselection);
  398. $page->assign('LANGUAGES', i18n::getLanguageLabels(i18n::getAvailableLanguages()));
  399. $page->assign('EXPIRE', $expire);
  400. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  401. $page->assign('EXPIRECLONE', !$this->_doesExpire || ($this->_doesExpire && $this->_conf->getKey('clone', 'expire')));
  402. $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
  403. $page->draw($this->_conf->getKey('template'));
  404. }
  405. /**
  406. * outputs requested JSON-LD context
  407. *
  408. * @access private
  409. * @param string $type
  410. * @return void
  411. */
  412. private function _jsonld($type)
  413. {
  414. if (
  415. $type !== 'paste' && $type !== 'comment' &&
  416. $type !== 'pastemeta' && $type !== 'commentmeta'
  417. ) {
  418. $type = '';
  419. }
  420. $content = '{}';
  421. $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
  422. if (is_readable($file)) {
  423. $content = str_replace(
  424. '?jsonld=',
  425. $this->_urlbase . '?jsonld=',
  426. file_get_contents($file)
  427. );
  428. }
  429. header('Content-type: application/ld+json');
  430. header('Access-Control-Allow-Origin: *');
  431. header('Access-Control-Allow-Methods: GET');
  432. echo $content;
  433. }
  434. /**
  435. * prepares JSON encoded status message
  436. *
  437. * @access private
  438. * @param int $status
  439. * @param string $message
  440. * @param array $other
  441. * @return void
  442. */
  443. private function _return_message($status, $message, $other = array())
  444. {
  445. $result = array('status' => $status);
  446. if ($status) {
  447. $result['message'] = i18n::_($message);
  448. } else {
  449. $result['id'] = $message;
  450. $result['url'] = $this->_urlbase . '?' . $message;
  451. }
  452. $result += $other;
  453. $this->_json = json_encode($result);
  454. }
  455. }