PrivateBin.php 17 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 1.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.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 = $this->_request->getRequestUri();
  161. ServerSalt::setPath($this->_conf->getKey('dir', 'traffic'));
  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::formatHumanReadableSize($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. */
  287. private function _delete($dataid, $deletetoken)
  288. {
  289. try {
  290. $paste = $this->_model->getPaste($dataid);
  291. if ($paste->exists()) {
  292. // accessing this property ensures that the paste would be
  293. // deleted if it has already expired
  294. $burnafterreading = $paste->isBurnafterreading();
  295. if (
  296. ($burnafterreading && $deletetoken == 'burnafterreading') || // either we burn-after it has been read //@TODO: not needed anymore now?
  297. Filter::slowEquals($deletetoken, $paste->getDeleteToken()) // or we manually delete it with this secret token
  298. ) {
  299. // Paste exists and deletion token (if required) is valid: Delete the paste.
  300. $paste->delete();
  301. $this->_status = 'Paste was properly deleted.';
  302. } else {
  303. if (!$burnafterreading && $deletetoken == 'burnafterreading') {
  304. $this->_error = 'Paste is not of burn-after-reading type.';
  305. } else {
  306. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  307. }
  308. }
  309. } else {
  310. $this->_error = self::GENERIC_ERROR;
  311. }
  312. } catch (Exception $e) {
  313. $this->_error = $e->getMessage();
  314. }
  315. if ($this->_request->isJsonApiCall()) {
  316. if (strlen($this->_error)) {
  317. $this->_return_message(1, $this->_error);
  318. } else {
  319. $this->_return_message(0, $dataid);
  320. }
  321. }
  322. }
  323. /**
  324. * Read an existing paste or comment, only allowed via a JSON API call
  325. *
  326. * @access private
  327. * @param string $dataid
  328. */
  329. private function _read($dataid)
  330. {
  331. if (!$this->_request->isJsonApiCall()) {
  332. return;
  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->_return_message(0, $dataid, (array) $data);
  343. } else {
  344. $this->_return_message(1, self::GENERIC_ERROR);
  345. }
  346. } catch (Exception $e) {
  347. $this->_return_message(1, $e->getMessage());
  348. }
  349. }
  350. /**
  351. * Display PrivateBin frontend.
  352. *
  353. * @access private
  354. */
  355. private function _view()
  356. {
  357. // set headers to disable caching
  358. $time = gmdate('D, d M Y H:i:s \G\M\T');
  359. header('Cache-Control: no-store, no-cache, no-transform, must-revalidate');
  360. header('Pragma: no-cache');
  361. header('Expires: ' . $time);
  362. header('Last-Modified: ' . $time);
  363. header('Vary: Accept');
  364. header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
  365. header('X-Xss-Protection: 1; mode=block');
  366. header('X-Frame-Options: DENY');
  367. header('X-Content-Type-Options: nosniff');
  368. // label all the expiration options
  369. $expire = array();
  370. foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
  371. $expire[$time] = ($seconds == 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
  372. }
  373. // translate all the formatter options
  374. $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
  375. // set language cookie if that functionality was enabled
  376. $languageselection = '';
  377. if ($this->_conf->getKey('languageselection')) {
  378. $languageselection = I18n::getLanguage();
  379. setcookie('lang', $languageselection);
  380. }
  381. $page = new View;
  382. $page->assign('NAME', $this->_conf->getKey('name'));
  383. $page->assign('ERROR', I18n::_($this->_error));
  384. $page->assign('STATUS', I18n::_($this->_status));
  385. $page->assign('VERSION', self::VERSION);
  386. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  387. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  388. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  389. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  390. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  391. $page->assign('FORMATTER', $formatters);
  392. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  393. $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
  394. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  395. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  396. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  397. $page->assign('ZEROBINCOMPATIBILITY', $this->_conf->getKey('zerobincompatibility'));
  398. $page->assign('LANGUAGESELECTION', $languageselection);
  399. $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
  400. $page->assign('EXPIRE', $expire);
  401. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  402. $page->assign('EXPIRECLONE', !$this->_doesExpire || ($this->_doesExpire && $this->_conf->getKey('clone', 'expire')));
  403. $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
  404. $page->assign('QRCODE', $this->_conf->getKey('qrcode'));
  405. $page->draw($this->_conf->getKey('template'));
  406. }
  407. /**
  408. * outputs requested JSON-LD context
  409. *
  410. * @access private
  411. * @param string $type
  412. */
  413. private function _jsonld($type)
  414. {
  415. if (
  416. $type !== 'paste' && $type !== 'comment' &&
  417. $type !== 'pastemeta' && $type !== 'commentmeta'
  418. ) {
  419. $type = '';
  420. }
  421. $content = '{}';
  422. $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
  423. if (is_readable($file)) {
  424. $content = str_replace(
  425. '?jsonld=',
  426. $this->_urlBase . '?jsonld=',
  427. file_get_contents($file)
  428. );
  429. }
  430. header('Content-type: application/ld+json');
  431. header('Access-Control-Allow-Origin: *');
  432. header('Access-Control-Allow-Methods: GET');
  433. echo $content;
  434. }
  435. /**
  436. * prepares JSON encoded status message
  437. *
  438. * @access private
  439. * @param int $status
  440. * @param string $message
  441. * @param array $other
  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. }