1
0

PrivateBin.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 0.22
  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 = '0.22';
  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. * @return void
  104. */
  105. public function __construct()
  106. {
  107. if (version_compare(PHP_VERSION, '5.3.0') < 0) {
  108. throw new Exception(I18n::_('PrivateBin requires php 5.3.0 or above to work. Sorry.'), 1);
  109. }
  110. // load config from ini file, initialize required classes
  111. $this->_init();
  112. switch ($this->_request->getOperation()) {
  113. case 'create':
  114. $this->_create();
  115. break;
  116. case 'delete':
  117. $this->_delete(
  118. $this->_request->getParam('pasteid'),
  119. $this->_request->getParam('deletetoken')
  120. );
  121. break;
  122. case 'read':
  123. $this->_read($this->_request->getParam('pasteid'));
  124. break;
  125. case 'jsonld':
  126. $this->_jsonld($this->_request->getParam('jsonld'));
  127. return;
  128. }
  129. // output JSON or HTML
  130. if ($this->_request->isJsonApiCall()) {
  131. header('Content-type: ' . Request::MIME_JSON);
  132. header('Access-Control-Allow-Origin: *');
  133. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
  134. header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
  135. echo $this->_json;
  136. } else {
  137. $this->_view();
  138. }
  139. }
  140. /**
  141. * initialize privatebin
  142. *
  143. * @access private
  144. * @return void
  145. */
  146. private function _init()
  147. {
  148. foreach (array('cfg', 'lib') as $dir) {
  149. if (!is_file(PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess')) {
  150. file_put_contents(
  151. PATH . $dir . DIRECTORY_SEPARATOR . '.htaccess',
  152. 'Allow from none' . PHP_EOL .
  153. 'Deny from all' . PHP_EOL,
  154. LOCK_EX
  155. );
  156. }
  157. }
  158. $this->_conf = new Configuration;
  159. $this->_model = new Model($this->_conf);
  160. $this->_request = new Request;
  161. $this->_urlBase = array_key_exists('REQUEST_URI', $_SERVER) ?
  162. htmlspecialchars($_SERVER['REQUEST_URI']) : '/';
  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. * @return void
  288. */
  289. private function _delete($dataid, $deletetoken)
  290. {
  291. try {
  292. $paste = $this->_model->getPaste($dataid);
  293. if ($paste->exists()) {
  294. // accessing this property ensures that the paste would be
  295. // deleted if it has already expired
  296. $burnafterreading = $paste->isBurnafterreading();
  297. if ($deletetoken == 'burnafterreading') {
  298. if ($burnafterreading) {
  299. $paste->delete();
  300. $this->_return_message(0, $dataid);
  301. } else {
  302. $this->_return_message(1, 'Paste is not of burn-after-reading type.');
  303. }
  304. } else {
  305. // Make sure the token is valid.
  306. if (Filter::slowEquals($deletetoken, $paste->getDeleteToken())) {
  307. // Paste exists and deletion token is valid: Delete the paste.
  308. $paste->delete();
  309. $this->_status = 'Paste was properly deleted.';
  310. } else {
  311. $this->_error = 'Wrong deletion token. Paste was not deleted.';
  312. }
  313. }
  314. } else {
  315. $this->_error = self::GENERIC_ERROR;
  316. }
  317. } catch (Exception $e) {
  318. $this->_error = $e->getMessage();
  319. }
  320. }
  321. /**
  322. * Read an existing paste or comment
  323. *
  324. * @access private
  325. * @param string $dataid
  326. * @return void
  327. */
  328. private function _read($dataid)
  329. {
  330. try {
  331. $paste = $this->_model->getPaste($dataid);
  332. if ($paste->exists()) {
  333. $data = $paste->get();
  334. $this->_doesExpire = property_exists($data, 'meta') && property_exists($data->meta, 'expire_date');
  335. if (property_exists($data->meta, 'salt')) {
  336. unset($data->meta->salt);
  337. }
  338. $this->_data = json_encode($data);
  339. } else {
  340. $this->_error = self::GENERIC_ERROR;
  341. }
  342. } catch (Exception $e) {
  343. $this->_error = $e->getMessage();
  344. }
  345. if ($this->_request->isJsonApiCall()) {
  346. if (strlen($this->_error)) {
  347. $this->_return_message(1, $this->_error);
  348. } else {
  349. $this->_return_message(0, $dataid, json_decode($this->_data, true));
  350. }
  351. }
  352. }
  353. /**
  354. * Display PrivateBin frontend.
  355. *
  356. * @access private
  357. * @return void
  358. */
  359. private function _view()
  360. {
  361. // set headers to disable caching
  362. $time = gmdate('D, d M Y H:i:s \G\M\T');
  363. header('Cache-Control: no-store, no-cache, must-revalidate');
  364. header('Pragma: no-cache');
  365. header('Expires: ' . $time);
  366. header('Last-Modified: ' . $time);
  367. header('Vary: Accept');
  368. header('Content-Security-Policy: ' . $this->_conf->getKey('cspheader'));
  369. // label all the expiration options
  370. $expire = array();
  371. foreach ($this->_conf->getSection('expire_options') as $time => $seconds) {
  372. $expire[$time] = ($seconds == 0) ? I18n::_(ucfirst($time)) : Filter::formatHumanReadableTime($time);
  373. }
  374. // translate all the formatter options
  375. $formatters = array_map('PrivateBin\\I18n::_', $this->_conf->getSection('formatter_options'));
  376. // set language cookie if that functionality was enabled
  377. $languageselection = '';
  378. if ($this->_conf->getKey('languageselection')) {
  379. $languageselection = I18n::getLanguage();
  380. setcookie('lang', $languageselection);
  381. }
  382. $page = new View;
  383. $page->assign('CIPHERDATA', $this->_data);
  384. $page->assign('ERROR', I18n::_($this->_error));
  385. $page->assign('STATUS', I18n::_($this->_status));
  386. $page->assign('VERSION', self::VERSION);
  387. $page->assign('DISCUSSION', $this->_conf->getKey('discussion'));
  388. $page->assign('OPENDISCUSSION', $this->_conf->getKey('opendiscussion'));
  389. $page->assign('MARKDOWN', array_key_exists('markdown', $formatters));
  390. $page->assign('SYNTAXHIGHLIGHTING', array_key_exists('syntaxhighlighting', $formatters));
  391. $page->assign('SYNTAXHIGHLIGHTINGTHEME', $this->_conf->getKey('syntaxhighlightingtheme'));
  392. $page->assign('FORMATTER', $formatters);
  393. $page->assign('FORMATTERDEFAULT', $this->_conf->getKey('defaultformatter'));
  394. $page->assign('NOTICE', I18n::_($this->_conf->getKey('notice')));
  395. $page->assign('BURNAFTERREADINGSELECTED', $this->_conf->getKey('burnafterreadingselected'));
  396. $page->assign('PASSWORD', $this->_conf->getKey('password'));
  397. $page->assign('FILEUPLOAD', $this->_conf->getKey('fileupload'));
  398. $page->assign('ZEROBINCOMPATIBILITY', $this->_conf->getKey('zerobincompatibility'));
  399. $page->assign('LANGUAGESELECTION', $languageselection);
  400. $page->assign('LANGUAGES', I18n::getLanguageLabels(I18n::getAvailableLanguages()));
  401. $page->assign('EXPIRE', $expire);
  402. $page->assign('EXPIREDEFAULT', $this->_conf->getKey('default', 'expire'));
  403. $page->assign('EXPIRECLONE', !$this->_doesExpire || ($this->_doesExpire && $this->_conf->getKey('clone', 'expire')));
  404. $page->assign('URLSHORTENER', $this->_conf->getKey('urlshortener'));
  405. $page->draw($this->_conf->getKey('template'));
  406. }
  407. /**
  408. * outputs requested JSON-LD context
  409. *
  410. * @access private
  411. * @param string $type
  412. * @return void
  413. */
  414. private function _jsonld($type)
  415. {
  416. if (
  417. $type !== 'paste' && $type !== 'comment' &&
  418. $type !== 'pastemeta' && $type !== 'commentmeta'
  419. ) {
  420. $type = '';
  421. }
  422. $content = '{}';
  423. $file = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . $type . '.jsonld';
  424. if (is_readable($file)) {
  425. $content = str_replace(
  426. '?jsonld=',
  427. $this->_urlBase . '?jsonld=',
  428. file_get_contents($file)
  429. );
  430. }
  431. header('Content-type: application/ld+json');
  432. header('Access-Control-Allow-Origin: *');
  433. header('Access-Control-Allow-Methods: GET');
  434. echo $content;
  435. }
  436. /**
  437. * prepares JSON encoded status message
  438. *
  439. * @access private
  440. * @param int $status
  441. * @param string $message
  442. * @param array $other
  443. * @return void
  444. */
  445. private function _return_message($status, $message, $other = array())
  446. {
  447. $result = array('status' => $status);
  448. if ($status) {
  449. $result['message'] = I18n::_($message);
  450. } else {
  451. $result['id'] = $message;
  452. $result['url'] = $this->_urlBase . '?' . $message;
  453. }
  454. $result += $other;
  455. $this->_json = json_encode($result);
  456. }
  457. }