csp.php 1.29 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
<?php

/**
 * Content-Security-Policy
 *
 * Set Content-Security-Policy headers on all responses.
 *
 * @version 0.1
 * @author Autistici/Inventati
 */

class csp extends rcube_plugin {
  public function init() {
    $this->load_config();
    $this->add_hook('send_page', array($this, 'add_header'));
  }

  public function add_header($content) {
    $rcmail = rcmail::get_instance();
    $host = $_SERVER['HTTP_HOST'];
    $proto = rcube_utils::https_check() ? 'https' : 'http';
    $path = $rcmail->config->get('csp_script_path', '/');
godog's avatar
godog committed
23 24 25 26 27
    $src_sso = "";
    $sso_hostname = $rcmail->config->get('csp_sso_hostname', '');
    if($sso_hostname != '') {
      $src_sso .= "{$sso_hostname}";
    }
ale's avatar
ale committed
28
    $csp_header = (
godog's avatar
godog committed
29 30 31 32
        "default-src 'self' {$src_sso}; " .
        "script-src 'self' {$proto}://{$host}{$path} 'unsafe-inline' 'unsafe-eval' {$src_sso}; " .
        "style-src 'self' 'unsafe-inline' {$src_sso}; " .
        "object-src 'none'");
33 34 35 36 37 38 39 40
    $report_uri = $rcmail->config->get('csp_report_uri', '');
    if($report_uri != '') {
      $csp_header .= '; report-uri ' . $report_uri;
    }
    $report_to = $rcmail->config->get('csp_report_to', '');
    if($report_to != '') {
      $csp_header .= '; report-to ' . $report_to;
    }
ale's avatar
ale committed
41 42 43 44 45
    header("Content-Security-Policy: {$csp_header}");
    return $content;
  }
}