PrivateBin.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. */
  112. public function __construct()
  113. {
  114. if (version_compare(PHP_VERSION, self::MIN_PHP_VERSION) < 0) {
  115. throw new Exception(I18n::_('%s requires php %s or above to work. Sorry.', I18n::_('PrivateBin'), self::MIN_PHP_VERSION), 1);
  116. }
  117. if (strlen(PATH) < 0 && substr(PATH, -1) !== DIRECTORY_SEPARATOR) {
  118. 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);
  119. }
  120. // load config from ini file, initialize required classes
  121. $this->_init();
  122. switch ($this->_request->getOperation()) {
  123. case 'create':
  124. $this->_create();
  125. break;
  126. case 'delete':
  127. $this->_delete(
  128. $this->_request->getParam('pasteid'),
  129. $this->_request->getParam('deletetoken')
  130. );
  131. break;
  132. case 'read':
  133. $this->_read($this->_request->getParam('pasteid'));
  134. break;
  135. case 'jsonld':
  136. $this->_jsonld($this->_request->getParam('jsonld'));
  137. return;
  138. }
  139. // output JSON or HTML
  140. if ($this->_request->isJsonApiCall()) {
  141. header('Content-type: ' . Request::MIME_JSON);
  142. header('Access-Control-Allow-Origin: *');
  143. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
  144. header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
  145. echo $this->_json;
  146. } else {
  147. $this->_view();
  148. }
  149. }
  150. /**
  151. * initialize privatebin
  152. *
  153. * @access private
  154. */
  155. private function _init()
  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. ServerSalt::setPath($this->_conf->getKey('dir', 'traffic'));
  163. // set default language
  164. $lang = $this->_conf->getKey('languagedefault');
  165. I18n::setLanguageFallback($lang);
  166. // force default language, if language selection is disabled and a default is set
  167. if (!$this->_conf->getKey('languageselection') && strlen($lang) == 2) {
  168. $_COOKIE['lang'] = $lang;
  169. setcookie('lang', $lang);
  170. }
  171. }
  172. /**
  173. * Store new paste or comment
  174. *
  175. * POST contains one or both:
  176. * data = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  177. * attachment = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  178. *
  179. * All optional data will go to meta information:
  180. * expire (optional) = expiration delay (never,5min,10min,1hour,1day,1week,1month,1year,burn) (default:never)
  181. * formatter (optional) = format to display the paste as (plaintext,syntaxhighlighting,markdown) (default:syntaxhighlighting)
  182. * burnafterreading (optional) = if this paste may only viewed once ? (0/1) (default:0)
  183. * opendiscusssion (optional) = is the discussion allowed on this paste ? (0/1) (default:0)
  184. * attachmentname = json encoded SJCL encrypted text (containing keys: iv,v,iter,ks,ts,mode,adata,cipher,salt,ct)
  185. * 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)
  186. * parentid (optional) = in discussion, which comment this comment replies to.
  187. * pasteid (optional) = in discussion, which paste this comment belongs to.
  188. *
  189. * @access private
  190. * @return string
  191. */
  192. private function _create()
  193. {
  194. // Ensure last paste from visitors IP address was more than configured amount of seconds ago.
  195. TrafficLimiter::setConfiguration($this->_conf);
  196. if (!TrafficLimiter::canPass()) {
  197. return $this->_return_message(
  198. 1, I18n::_(
  199. 'Please wait %d seconds between each post.',
  200. $this->_conf->getKey('limit', 'traffic')
  201. )
  202. );
  203. }
  204. $data = $this->_request->getParam('data');
  205. $attachment = $this->_request->getParam('attachment');
  206. $attachmentname = $this->_request->getParam('attachmentname');
  207. // Ensure content is not too big.
  208. $sizelimit = $this->_conf->getKey('sizelimit');
  209. if (
  210. strlen($data) + strlen($attachment) + strlen($attachmentname) > $sizelimit
  211. ) {
  212. return $this->_return_message(
  213. 1,
  214. I18n::_(
  215. 'Paste is limited to %s of encrypted data.',
  216. Filter::formatHumanReadableSize($sizelimit)
  217. )
  218. );
  219. }
  220. // Ensure attachment did not get lost due to webserver limits or Suhosin
  221. if (strlen($attachmentname) > 0 && strlen($attachment) == 0) {
  222. return $this->_return_message(1, 'Attachment missing in data received by server. Please check your webserver or suhosin configuration for maximum POST parameter limitations.');
  223. }
  224. // The user posts a comment.
  225. $pasteid = $this->_request->getParam('pasteid');
  226. $parentid = $this->_request->getParam('parentid');
  227. if (!empty($pasteid) && !empty($parentid)) {
  228. $paste = $this->_model->getPaste($pasteid);
  229. if ($paste->exists()) {
  230. try {
  231. $comment = $paste->getComment($parentid);
  232. $nickname = $this->_request->getParam('nickname');
  233. if (!empty($nickname)) {
  234. $comment->setNickname($nickname);
  235. }
  236. $comment->setData($data);
  237. $comment->store();
  238. } catch (Exception $e) {
  239. return $this->_return_message(1, $e->getMessage());
  240. }
  241. $this->_return_message(0, $comment->getId());
  242. } else {
  243. $this->_return_message(1, 'Invalid data.');
  244. }
  245. }
  246. // The user posts a standard paste.
  247. else {
  248. $this->_model->purge();
  249. $paste = $this->_model->getPaste();
  250. try {
  251. $paste->setData($data);
  252. if (!empty($attachment)) {
  253. $paste->setAttachment($attachment);
  254. if (!empty($attachmentname)) {
  255. $paste->setAttachmentName($attachmentname);
  256. }
  257. }
  258. $expire = $this->_request->getParam('expire');
  259. if (!empty($expire)) {
  260. $paste->setExpiration($expire);
  261. }
  262. $burnafterreading = $this->_request->getParam('burnafterreading');
  263. if (!empty($burnafterreading)) {
  264. $paste->setBurnafterreading($burnafterreading);
  265. }
  266. $opendiscussion = $this->_request->getParam('opendiscussion');
  267. if (!empty($opendiscussion)) {
  268. $paste->setOpendiscussion($opendiscussion);
  269. }
  270. $formatter = $this->_request->getParam('formatter');
  271. if (!empty($formatter)) {
  272. $paste->setFormatter($formatter);
  273. }
  274. $paste->store();
  275. } catch (Exception $e) {
  276. return $this->_return_message(1, $e->getMessage());
  277. }
  278. $this->_return_message(0, $paste->getId(), array('deletetoken' => $paste->getDeleteToken()));
  279. }
  280. }
  281. /**
  282. * Delete an existing paste
  283. *
  284. * @access private
  285. * @param string $dataid
  286. * @param string $deletetoken
  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 (
  297. ($burnafterreading && $deletetoken == 'burnafterreading') ||
  298. Filter::slowEquals($deletetoken, $paste->getDeleteToken())
  299. ) {
  300. // Paste exists and deletion token is valid: Delete the paste.
  301. $paste->delete();
  302. $this->_status = 'Paste was properly deleted.';
  303. } else {
  304. if (!$burnafterreading && $deletetoken == 'burnafterreading') {
  305. $this->_error = 'Paste is not of burn-after-reading type.';
  306. } else {
  307. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  308. }
  309. }
  310. } else {
  311. $this->_error = self::GENERIC_ERROR;
  312. }
  313. } catch (Exception $e) {
  314. $this->_error = $e->getMessage();
  315. }
  316. if ($this->_request->isJsonApiCall()) {
  317. if (strlen($this->_error)) {
  318. $this->_return_message(1, $this->_error);
  319. } else {
  320. $this->_return_message(0, $dataid);
  321. }
  322. }
  323. }
  324. /**
  325. * Read an existing paste or comment
  326. *
  327. * @access private
  328. * @param string $dataid
  329. */
  330. private function _read($dataid)
  331. {
  332. try {
  333. $paste = $this->_model->getPaste($dataid);
  334. if ($paste->exists()) {
  335. $data = $paste->get();
  336. $this->_doesExpire = property_exists($data, 'meta') && property_exists($data->meta, 'expire_date');
  337. if (property_exists($data->meta, 'salt')) {
  338. unset($data->meta->salt);
  339. }
  340. $this->_data = json_encode($data);
  341. } else {
  342. $this->_error = self::GENERIC_ERROR;
  343. }
  344. } catch (Exception $e) {
  345. $this->_error = $e->getMessage();
  346. }
  347. if ($this->_request->isJsonApiCall()) {
  348. if (strlen($this->_error)) {
  349. $this->_return_message(1, $this->_error);
  350. } else {
  351. $this->_return_message(0, $dataid, json_decode($this->_data, true));
  352. }
  353. }
  354. }
  355. /**
  356. * Display PrivateBin frontend.
  357. *
  358. * @access private
  359. */
  360. private function _view()
  361. {
  362. // set headers to disable caching
  363. $time = gmdate('D, d M Y H:i:s \G\M\T');
  364. header('Cache-Control: no-store, no-cache, no-transform, must-revalidate');
  365. header('Pragma: no-cache');
  366. header('Expires: ' . $time);
  367. header('Last-Modified: ' . $time);
  368. header('Vary: Accept');
  369. header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
  370. header('X-Xss-Protection: 1; mode=block');
  371. header('X-Frame-Options: DENY');
  372. header('X-Content-Type-Options: nosniff');
  373. // label all the expiration options
  374. $expire = array();
  375. foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
  376. $expire[$time] = ($seconds == 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
  377. }
  378. // translate all the formatter options
  379. $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
  380. // set language cookie if that functionality was enabled
  381. $languageselection = '';
  382. if ($this->_conf->getKey('languageselection')) {
  383. $languageselection = I18n::getLanguage();
  384. setcookie('lang', $languageselection);
  385. }
  386. $page = new View;
  387. $page->assign('NAME', $this->_conf->getKey('name'));
  388. $page->assign('CIPHERDATA', $this->_data);
  389. $page->assign('ERROR', I18n::_($this->_error));
  390. $page->assign('STATUS', I18n::_($this->_status));
  391. $page->assign('VERSION', self::VERSION);
  392. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  393. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  394. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  395. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  396. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  397. $page->assign('FORMATTER', $formatters);
  398. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  399. $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
  400. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  401. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  402. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  403. $page->assign('ZEROBINCOMPATIBILITY', $this->_conf->getKey('zerobincompatibility'));
  404. $page->assign('LANGUAGESELECTION', $languageselection);
  405. $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
  406. $page->assign('EXPIRE', $expire);
  407. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  408. $page->assign('EXPIRECLONE', !$this->_doesExpire || ($this->_doesExpire && $this->_conf->getKey('clone', 'expire')));
  409. $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
  410. $page->draw($this->_conf->getKey('template'));
  411. }
  412. /**
  413. * outputs requested JSON-LD context
  414. *
  415. * @access private
  416. * @param string $type
  417. */
  418. private function _jsonld($type)
  419. {
  420. if (
  421. $type !== 'paste' && $type !== 'comment' &&
  422. $type !== 'pastemeta' && $type !== 'commentmeta'
  423. ) {
  424. $type = '';
  425. }
  426. $content = '{}';
  427. $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
  428. if (is_readable($file)) {
  429. $content = str_replace(
  430. '?jsonld=',
  431. $this->_urlBase . '?jsonld=',
  432. file_get_contents($file)
  433. );
  434. }
  435. header('Content-type: application/ld+json');
  436. header('Access-Control-Allow-Origin: *');
  437. header('Access-Control-Allow-Methods: GET');
  438. echo $content;
  439. }
  440. /**
  441. * prepares JSON encoded status message
  442. *
  443. * @access private
  444. * @param int $status
  445. * @param string $message
  446. * @param array $other
  447. */
  448. private function _return_message($status, $message, $other = array())
  449. {
  450. $result = array('status' => $status);
  451. if ($status) {
  452. $result['message'] = I18n::_($message);
  453. } else {
  454. $result['id'] = $message;
  455. $result['url'] = $this->_urlBase . '?' . $message;
  456. }
  457. $result += $other;
  458. $this->_json = json_encode($result);
  459. }
  460. }