1
0
mirror of https://github.com/e107inc/e107.git synced 2025-03-13 17:09:46 +01:00

Merge pull request #3111 from Deltik/fix-3075

Add NGINX secure_link_md5 URL protection feature to e107 Downloads plugin
This commit is contained in:
Cameron 2018-05-10 10:55:28 -07:00 committed by GitHub
commit 8584c207c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 325 additions and 52 deletions

View File

@ -1,5 +1,6 @@
---
engines:
version: "2"
plugins:
csslint:
enabled: false
duplication:
@ -36,20 +37,25 @@ engines:
config:
file_extensions: "php"
rulesets: "cleancode,unusedcode,codesize"
ratings:
paths:
- "**.css"
- "**.js"
- "**.php"
exclude_paths:
- e107_admin/core_image.php
- e107_plugins/log/js/awesomechart.js
- e107_docs/**/*
- e107_images/**/*
- e107_handlers/hybridauth/**/*
- e107_handlers/jsshrink/**/*
- e107_handlers/phpmailer/**/*
- e107_handlers/phpthumb/**/*
- e107_handlers/xmlrpc/**/*
- e107_web/**/*
exclude_patterns:
- "config/"
- "db/"
- "dist/"
- "features/"
- "**/node_modules/"
- "script/"
- "**/spec/"
- "**/test/"
- "**/tests/"
- "**/vendor/"
- "**/*.d.ts"
- "e107_admin/core_image.php"
- "e107_plugins/log/js/awesomechart.js"
- "e107_docs/**/*"
- "e107_images/**/*"
- "e107_handlers/hybridauth/**/*"
- "e107_handlers/jsshrink/**/*"
- "e107_handlers/phpmailer/**/*"
- "e107_handlers/phpthumb/**/*"
- "e107_handlers/xmlrpc/**/*"
- "e107_web/**/*"

View File

@ -0,0 +1,52 @@
<?php
require_once('SecureLinkDecorator.php');
class NginxSecureLinkMd5Decorator implements SecureLinkDecorator
{
protected $url = null;
protected $prefs = array();
const SUPPORTED_VARIABLES = array(
'$secure_link_expires',
'$uri',
'$remote_addr'
);
static function supported_variables() {
return self::SUPPORTED_VARIABLES;
}
function __construct($url, $preferences)
{
$this->url = $url;
$this->prefs = $preferences;
}
public function decorate()
{
$prefs = $this->prefs;
$url = $this->url;
$expiry = intval($prefs['download_security_link_expiry']);
if ($expiry <= 0)
$expiry = PHP_INT_MAX;
else
$expiry = time() + $expiry;
$url_parts = parse_url($url);
$evaluation = str_replace(
self::supported_variables(),
array(
$expiry,
$url_parts['path'],
$_SERVER['REMOTE_ADDR']
),
$prefs['download_security_expression']
);
$query_string = $url_parts['query'];
parse_str($query_string, $query_args);
$query_args['md5'] = str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode(md5($evaluation, true)));
if (strpos($prefs['download_security_expression'], '$secure_link_expires') !== false)
$query_args['expires'] = $expiry;
require_once(__DIR__ . '/../vendor/shim_http_build_url.php');
return http_build_url($url_parts, array('query' => http_build_query($query_args)));
}
}

View File

@ -0,0 +1,6 @@
<?php
interface SecureLinkDecorator
{
public function decorate();
}

View File

@ -286,7 +286,11 @@ class download_main_admin_ui extends e_admin_ui
//required - default column user prefs
protected $fieldpref = array('checkboxes', 'download_image', 'download_id', 'download_datestamp', 'download_category', 'download_name', 'download_active', 'download_class', 'fb_order', 'options');
//
// Security modes
protected $security_options = array(
'none' => LAN_DL_SECURITY_MODE_NONE,
'nginx-secure_link_md5' => LAN_DL_SECURITY_MODE_NGINX_SECURELINKMD5
);
// optional - required only in case of e.g. tables JOIN. This also could be done with custom model (set it in init())
//protected $editQry = "SELECT * FROM #release WHERE release_id = {ID}";
@ -1133,22 +1137,32 @@ $columnInfo = array(
global $admin_log,$pref;
$tp = e107::getParser();
$expected_params = array(
'download_php', 'download_view', 'download_sort', 'download_order',
'mirror_order', 'recent_download_days', 'agree_flag', 'download_email',
'agree_text', 'download_denied', 'download_reportbroken',
'download_security_mode', 'download_security_expression', 'download_security_link_expiry'
);
$temp = array();
$temp['download_php'] = $_POST['download_php'];
$temp['download_view'] = $_POST['download_view'];
$temp['download_sort'] = $_POST['download_sort'];
$temp['download_order'] = $_POST['download_order'];
$temp['mirror_order'] = $_POST['mirror_order'];
$temp['recent_download_days'] = $_POST['recent_download_days'];
$temp['agree_flag'] = $_POST['agree_flag'];
$temp['download_email'] = $_POST['download_email'];
$temp['agree_text'] = $tp->toDB($_POST['agree_text']);
$temp['download_denied'] = $tp->toDB($_POST['download_denied']);
$temp['download_reportbroken'] = $_POST['download_reportbroken'];
if ($_POST['download_subsub']) $temp['download_subsub'] = '1'; else $temp['download_subsub'] = '0';
if ($_POST['download_incinfo']) $temp['download_incinfo'] = '1'; else $temp['download_incinfo'] = '0';
foreach($expected_params as $expected_param)
{
$temp[$expected_param] = $_POST[$expected_param];
}
$temp['download_subsub'] = $_POST['download_subsub'] ? '1' : '0';
$temp['download_incinfo'] = $_POST['download_incinfo'] ? '1' : '0';
if ($_POST['download_security_mode'] !== 'nginx-secure_link_md5')
{
unset($temp['download_security_mode']);
unset($temp['download_security_expression']);
unset($temp['download_security_link_expiry']);
e107::getConfig('core')->removePref('download_security_mode');
e107::getConfig('core')->removePref('download_security_expression');
e107::getConfig('core')->removePref('download_security_link_expiry');
}
e107::getConfig('core')->setPref($temp)->save(false);
@ -2093,14 +2107,33 @@ $columnInfo = array(
}
}
private function supported_secure_link_variables_html()
{
require_once(__DIR__."/../handlers/NginxSecureLinkMd5Decorator.php");
$supported_secure_link_variables_html = "<ul>";
foreach(NginxSecureLinkMd5Decorator::supported_variables() as $variable)
{
$supported_secure_link_variables_html .= "<li><code>$variable</code></li>";
}
$supported_secure_link_variables_html .= "</ul>";
return $supported_secure_link_variables_html;
}
private function mirror_order_options_html($pref)
{
return ($pref['mirror_order'] == "0" ? "<option value='0' selected='selected'>".DOWLAN_161."</option>" : "<option value='0'>".DOWLAN_161."</option>").
($pref['mirror_order'] == "1" ? "<option value='1' selected='selected'>".LAN_ID."</option>" : "<option value='1'>".LAN_ID."</option>").
($pref['mirror_order'] == "2" ? "<option value='2' selected='selected'>".DOWLAN_12."</option>" : "<option value='2'>".DOWLAN_12."</option>");
}
function show_download_options()
{
global $pref, $ns;
require_once(e_HANDLER."form_handler.php");
$frm = new e_form(true); //enable inner tabindex counter
$agree_flag = $pref['agree_flag'];
require_once(e_HANDLER."form_handler.php");
$frm = new e_form(true); //enable inner tabindex counter
$agree_flag = $pref['agree_flag'];
$agree_text = $pref['agree_text'];
$c = $pref['download_php'] ? " checked = 'checked' " : "";
$sacc = (varset($pref['download_incinfo'],0) == '1') ? " checked = 'checked' " : "";
@ -2115,14 +2148,15 @@ $columnInfo = array(
"ASC" => DOWLAN_62,
"DESC" => DOWLAN_63
);
$text = "
<ul class='nav nav-tabs'>
<li class='active'><a data-toggle='tab' href='#core-download-download1'>".LAN_DL_DOWNLOAD_OPT_GENERAL."</a></li>
<li><a data-toggle='tab' href='#core-download-download2'>".LAN_DL_DOWNLOAD_OPT_BROKEN."</a></li>
<li><a data-toggle='tab' href='#core-download-download3'>".LAN_DL_DOWNLOAD_OPT_AGREE."</a></li>
<li><a data-toggle='tab' href='#core-download-download4'>".LAN_DL_UPLOAD."</a></li>
<li><a data-toggle='tab' href='#core-download-download4'>".LAN_DL_DOWNLOAD_OPT_SECURITY."</a></li>
<li><a data-toggle='tab' href='#core-download-download5'>".LAN_DL_UPLOAD."</a></li>
</ul>
<form method='post' action='".e_SELF."?".e_QUERY."'>\n
@ -2170,10 +2204,7 @@ $columnInfo = array(
<tr>
<td>".DOWLAN_160."</td>
<td>
<select name='mirror_order' class='form-control'>".
($pref['mirror_order'] == "0" ? "<option value='0' selected='selected'>".DOWLAN_161."</option>" : "<option value='0'>".DOWLAN_161."</option>").
($pref['mirror_order'] == "1" ? "<option value='1' selected='selected'>".LAN_ID."</option>" : "<option value='1'>".LAN_ID."</option>").
($pref['mirror_order'] == "2" ? "<option value='2' selected='selected'>".DOWLAN_163."</option>" : "<option value='2'>".DOWLAN_12."</option>")."
<select name='mirror_order' class='form-control'>".$this->mirror_order_options_html($pref)."
</select>
</td>
</tr>
@ -2226,6 +2257,45 @@ $columnInfo = array(
</div>
</div>
<div class='tab-pane' id='core-download-download4'>
<div>
<p style='padding: 8px'>
".LAN_DL_SECURITY_DESCRIPTION."
</p>
<table class='table adminform'>
<colgroup>
<col style='width:30%'/>
<col style='width:70%'/>
</colgroup>
<tr>
<td>".LAN_DL_SECURITY_MODE."</td>
<td>".$frm->select('download_security_mode', $this->security_options, $pref['download_security_mode'])."</td>
</tr>
<tbody id='nginx-secure_link_md5' ".($pref['download_security_mode'] === 'nginx-secure_link_md5' ? "" : "style='display:none'").">
<tr>
<td>".LAN_DL_SECURITY_NGINX_SECURELINKMD5_EXPRESSION."</td>
<td>
".$frm->text('download_security_expression', $pref['download_security_expression'], 1024)."
<div class='field-help'>".LAN_DL_SECURITY_NGINX_SECURELINKMD5_EXPRESSION_HELP."</div>
<small><a href='#' onclick='event.preventDefault();$(\"#supported-nginx-variables\").toggle();this.blur()'>
".LAN_DL_SECURITY_NGINX_SUPPORTED_VARIABLES_TOGGLE."
</a></small>
<div id='supported-nginx-variables' style='display:none'>
".$this->supported_secure_link_variables_html()."
</div>
</td>
</tr>
<tr>
<td>".LAN_DL_SECURITY_LINK_EXPIRY."</td>
<td>
".$frm->text('download_security_link_expiry', $pref['download_security_link_expiry'], 16, array('pattern' => '\d+'))."
<div class='field-help'>".LAN_DL_SECURITY_LINK_EXPIRY_HELP."</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='tab-pane' id='core-download-download5'>
<div>
<table class='table adminform'>
<colgroup>
@ -2246,7 +2316,20 @@ $columnInfo = array(
</div>
</form>
";
// $ns->tablerender(LAN_DL_OPTIONS, $text);
e107::js('footer-inline', "
$('#download-security-mode').on('change', function() {
var mode = $(this).val();
if (mode == 'nginx-secure_link_md5') {
$('#nginx-secure_link_md5').show('slow');
return;
}
$('#nginx-secure_link_md5').hide('slow');
});
");
echo $text;
}

View File

@ -12,6 +12,7 @@ define("LAN_DL_OPTIONS", "Options"); //FIXME Use Generic
define("LAN_DL_DOWNLOAD_OPT_GENERAL", "General");
define("LAN_DL_DOWNLOAD_OPT_BROKEN", "Reporting");
define("LAN_DL_DOWNLOAD_OPT_AGREE", "Agreements");
define("LAN_DL_DOWNLOAD_OPT_SECURITY", "Protection");
define("LAN_DL_UPLOAD", "Upload"); //FIXME Use Generic
define("LAN_DL_USE_PHP", "Use PHP");
define("LAN_DL_USE_PHP_INFO", "Checking this will send all download requests through PHP");
@ -228,4 +229,17 @@ define("DOWLAN_HELP_10", "Help for upload options");
// define("DOWLAN_INSTALL_DONE", "Your download plugin is now installed");
// define("DOWLAN_DESCRIPTION", "This plugin is a fully featured Download system");
// define("DOWLAN_CAPTION", "Configure Download");
?>
define("LAN_DL_SECURITY_DESCRIPTION", "Downloads can make use of server-side URL protection features to prevent hotlinking and/or enforce link expiry. " .
"This section should be configured before the download server is configured to reduce the chance of disruption to downloaders.");
define("LAN_DL_SECURITY_MODE", "URL protection mode");
define("LAN_DL_SECURITY_MODE_NONE", "None (Default)");
define("LAN_DL_SECURITY_MODE_NGINX_SECURELINKMD5", "NGINX secure_link_md5");
define("LAN_DL_SECURITY_NGINX_SUPPORTED_VARIABLES_TOGGLE", "Click to toggle list of supported NGINX variables");
define("LAN_DL_SECURITY_NGINX_SECURELINKMD5_EXPRESSION",
"<a target='_blank' href='https://nginx.org/en/docs/http/ngx_http_secure_link_module.html#secure_link_md5'>NGINX secure_link_md5 expression</a>");
define("LAN_DL_SECURITY_NGINX_SECURELINKMD5_EXPRESSION_HELP", "Same expression as configured on the server");
define("LAN_DL_SECURITY_LINK_EXPIRY", "Duration of validity in seconds");
define("LAN_DL_SECURITY_LINK_EXPIRY_HELP", "Number of seconds the download link should last after being generated. " .
"Only effective if the expression supports expiry time. " .
"Defaults to a very long time if this field is left blank.");

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<e107Plugin name="Downloads" lan="LAN_PLUGIN_DOWNLOAD_NAME" version="1.1" date="2017-04-27" compatibility="2.0" installRequired="true">
<e107Plugin name="Downloads" lan="LAN_PLUGIN_DOWNLOAD_NAME" version="1.2" date="2018-05-01" compatibility="2.0" installRequired="true">
<author name="e107 Inc." url="http://e107.org" />
<description lan="LAN_PLUGIN_DOWNLOAD_DIZ">This plugin is a fully featured File-download system</description>
<description lan="LAN_PLUGIN_DOWNLOAD_DIZ">This plugin is a fully featured file download system</description>
<category>content</category>
<adminLinks>
<link url='admin_download.php' description='LAN_CONFIGURE' icon='images/downloads_32.png' iconSmall='images/downloads_16.png' primary='true' >DOWLAN_CAPTION</link>

View File

@ -72,7 +72,7 @@ if(strstr(e_QUERY, "mirror"))
}
$sql->update("download", "download_requested = download_requested + 1, download_mirror = '{$mstr}' WHERE download_id = '".intval($download_id)."'");
$sql->update("download_mirror", "mirror_count = mirror_count + 1 WHERE mirror_id = '".intval($mirror_id)."'");
header("Location: {$gaddress}");
header("Location: ".decorate_download_location($gaddress));
exit();
}
@ -189,7 +189,7 @@ if ($type == "file")
$sql->update("download", "download_requested = download_requested + 1, download_mirror = '{$mstr}' WHERE download_id = '".intval($download_id)."'");
$sql->update("download_mirror", "mirror_count = mirror_count + 1 WHERE mirror_id = '".intval($mirror_id)."'");
header("Location: ".$gaddress);
header("Location: ".decorate_download_location($gaddress));
exit();
}
@ -217,7 +217,7 @@ if ($type == "file")
if (strstr($download_url, "http://") || strstr($download_url, "ftp://") || strstr($download_url, "https://"))
{
$download_url = e107::getParser()->parseTemplate($download_url,true); // support for shortcode-driven dynamic URLS.
e107::redirect($download_url);
e107::redirect(decorate_download_location($download_url));
// header("Location: {$download_url}");
exit();
}
@ -435,4 +435,12 @@ function check_download_limits()
}
}
?>
function decorate_download_location($url)
{
$pref = e107::getPref();
if ($pref['download_security_mode'] !== 'nginx-secure_link_md5')
return $url;
require_once(__DIR__."/handlers/NginxSecureLinkMd5Decorator.php");
$decorator = new NginxSecureLinkMd5Decorator($url, $pref);
return $decorator->decorate();
}

View File

@ -0,0 +1,104 @@
<?php
if (!function_exists('http_build_url'))
{
define('HTTP_URL_REPLACE', 1); // Replace every part of the first URL when there's one of the second URL
define('HTTP_URL_JOIN_PATH', 2); // Join relative paths
define('HTTP_URL_JOIN_QUERY', 4); // Join query strings
define('HTTP_URL_STRIP_USER', 8); // Strip any user authentication information
define('HTTP_URL_STRIP_PASS', 16); // Strip any password authentication information
define('HTTP_URL_STRIP_AUTH', 32); // Strip any authentication information
define('HTTP_URL_STRIP_PORT', 64); // Strip explicit port numbers
define('HTTP_URL_STRIP_PATH', 128); // Strip complete path
define('HTTP_URL_STRIP_QUERY', 256); // Strip query string
define('HTTP_URL_STRIP_FRAGMENT', 512); // Strip any fragments (#identifier)
define('HTTP_URL_STRIP_ALL', 1024); // Strip anything but scheme and host
// Build an URL
// The parts of the second URL will be merged into the first according to the flags argument.
//
// @param mixed (Part(s) of) an URL in form of a string or associative array like parse_url() returns
// @param mixed Same as the first argument
// @param int A bitmask of binary or'ed HTTP_URL constants (Optional)HTTP_URL_REPLACE is the default
// @param array If set, it will be filled with the parts of the composed url like parse_url() would return
function http_build_url($url, $parts=array(), $flags=HTTP_URL_REPLACE, &$new_url=false)
{
$keys = array('user','pass','port','path','query','fragment');
// HTTP_URL_STRIP_ALL becomes all the HTTP_URL_STRIP_Xs
if ($flags & HTTP_URL_STRIP_ALL)
{
$flags |= HTTP_URL_STRIP_USER;
$flags |= HTTP_URL_STRIP_PASS;
$flags |= HTTP_URL_STRIP_PORT;
$flags |= HTTP_URL_STRIP_PATH;
$flags |= HTTP_URL_STRIP_QUERY;
$flags |= HTTP_URL_STRIP_FRAGMENT;
}
// HTTP_URL_STRIP_AUTH becomes HTTP_URL_STRIP_USER and HTTP_URL_STRIP_PASS
else if ($flags & HTTP_URL_STRIP_AUTH)
{
$flags |= HTTP_URL_STRIP_USER;
$flags |= HTTP_URL_STRIP_PASS;
}
// Parse the original URL
$parse_url = !is_array($url) ? parse_url($url) : $url;
// Scheme and Host are always replaced
if (isset($parts['scheme']))
$parse_url['scheme'] = $parts['scheme'];
if (isset($parts['host']))
$parse_url['host'] = $parts['host'];
// (If applicable) Replace the original URL with it's new parts
if ($flags & HTTP_URL_REPLACE)
{
foreach ($keys as $key)
{
if (isset($parts[$key]))
$parse_url[$key] = $parts[$key];
}
}
else
{
// Join the original URL path with the new path
if (isset($parts['path']) && ($flags & HTTP_URL_JOIN_PATH))
{
if (isset($parse_url['path']))
$parse_url['path'] = rtrim(str_replace(basename($parse_url['path']), '', $parse_url['path']), '/') . '/' . ltrim($parts['path'], '/');
else
$parse_url['path'] = $parts['path'];
}
// Join the original query string with the new query string
if (isset($parts['query']) && ($flags & HTTP_URL_JOIN_QUERY))
{
if (isset($parse_url['query']))
$parse_url['query'] .= '&' . $parts['query'];
else
$parse_url['query'] = $parts['query'];
}
}
// Strips all the applicable sections of the URL
// Note: Scheme and Host are never stripped
foreach ($keys as $key)
{
if ($flags & (int)constant('HTTP_URL_STRIP_' . strtoupper($key)))
unset($parse_url[$key]);
}
$new_url = $parse_url;
return
((isset($parse_url['scheme'])) ? $parse_url['scheme'] . '://' : '')
.((isset($parse_url['user'])) ? $parse_url['user'] . ((isset($parse_url['pass'])) ? ':' . $parse_url['pass'] : '') .'@' : '')
.((isset($parse_url['host'])) ? $parse_url['host'] : '')
.((isset($parse_url['port'])) ? ':' . $parse_url['port'] : '')
.((isset($parse_url['path'])) ? $parse_url['path'] : '')
.((isset($parse_url['query'])) ? '?' . $parse_url['query'] : '')
.((isset($parse_url['fragment'])) ? '#' . $parse_url['fragment'] : '')
;
}
}