PrivateBin.php 17 KB

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