PrivateBin.php 17 KB

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