PrivateBin.php 17 KB

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