Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/goodbye-captcha/assets/public/scripts/gdbc-client-new.js.php
+++ b/goodbye-captcha/assets/public/scripts/gdbc-client-new.js.php
@@ -1,163 +0,0 @@
-<?php
-
-defined( 'ABSPATH' ) || exit;
-
-add_filter('nocache_headers', function($arrHeaders){
- $arrHeaders['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
- $arrHeaders['Content-Type'] = 'application/javascript; charset=utf-8';
-
- return $arrHeaders;
-}, 1);
-
-nocache_headers();
-
-
-if(null === ($settingsModuleInstance = GdbcModulesController::getPublicModuleInstance(GdbcModulesController::MODULE_SETTINGS))){
- exit;
-}
-
-$hiddenInputName = $settingsModuleInstance->getOption(GdbcSettingsAdminModule::OPTION_HIDDEN_INPUT_NAME);
-
-
-?>
-
-(function() {'use strict';
- if (!Array.isArray){Array.isArray = function(arg){return Object.prototype.toString.call(arg) === '[object Array]';};}
- if (!String.prototype.trim){String.prototype.trim = function () {return this.replace(/^[suFEFFxA0]+|[suFEFFxA0]+$/g, '');};}
-
- var WPBruiserClient = function(){
- var browserInfo = new Array();
- function init(){
- var w=window,d=document,e=0,f=0;e|=w.ActiveXObject?1:0;e|=w.opera?2:0;e|=w.chrome?4:0;
- e|='getBoxObjectFor' in d || 'mozInnerScreenX' in w?8:0;e|=('WebKitCSSMatrix' in w||'WebKitPoint' in w||'webkitStorageInfo' in w||'webkitURL' in w)?16:0;
- e|=(e&16&&({}.toString).toString().indexOf("n")===-1)?32:0;f|='sandbox' in d.createElement('iframe')?1:0;f|='WebSocket' in w?2:0;
- f|=w.Worker?4:0;f|=w.applicationCache?8:0;f|=w.history && history.pushState?16:0;f|=d.documentElement.webkitRequestFullScreen?32:0;f|='FileReader' in w?64:0;
-
- var ua = navigator.userAgent.toLowerCase();
- var regex = /compatible; ([w.+]+)[ /]([w.+]*)|([w .+]+)[: /]([w.+]+)|([w.+]+)/g;
- var match = regex.exec(ua);
- browserInfo = {screenWidth:screen.width,screenHeight:screen.height,engine:e,features:f};
- while (match !== null) {
- var prop = {};
- if (match[1]) {
- prop.type = match[1];
- prop.version = match[2];
- } else if (match[3]) {
- prop.type = match[3];
- prop.version = match[4];
- } else {
- prop.type = match[5];
- }
- prop.type = (prop.type).trim().replace('.','').replace(' ','_');
- var value = prop.version ? prop.version : true;
- if (browserInfo[prop.type]) {
- !Array.isArray(browserInfo[prop.type])?browserInfo[prop.type]=new Array(browserInfo[prop.type]):'';
- browserInfo[prop.type].push(value);
- }
- else browserInfo[prop.type] = value;
- match = regex.exec(ua);
- }
- };
-
- var requestTokens = function(){for(var i = 0; i < document.forms.length; ++i){retrieveToken(document.forms[i]);}};
-
- function retrieveToken(formElement){
-
- var requestObj = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
-
- var formFieldElm = formElement.querySelector('input[name="<?php echo $hiddenInputName; ?>"]');
- if(!requestObj || !formFieldElm) return;
- var ajaxData = {};
-
- ajaxData[<?php echo "'$hiddenInputName'"; ?>] = '<?php echo GdbcAjaxController::getAjaxNonce(); ?>';
- ajaxData['action'] = '<?php echo GdbcAjaxController::ACTION_RETRIEVE_TOKEN ?>';
- ajaxData['requestTime'] = (new Date()).getTime();
- ajaxData['browserInfo'] = JSON.stringify(browserInfo);
-
- requestObj.open('POST', '<?php echo MchGdbcWpUtils::getAjaxUrl() ?>', true);
- requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
- requestObj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
- requestObj.setRequestHeader('Accept',"application/json, text/javascript, */*; q=0.01");
- requestObj.send(serializeObject(ajaxData));
-
- requestObj.onreadystatechange = function () {
- if (4 === requestObj.readyState && 200 === requestObj.status)
- {
- try
- {
- var rs = JSON.parse(requestObj.responseText);
- if(rs.data === 'undefined')
- return;
-
- var tokens = {};
-
- for(var p in rs.data)
- {
- if(p=='token')
- {
- formFieldElm.value = rs.data[p];
- tokens[formFieldElm.name] = null;
- }
- else
- {
- var value = '', arrValues = rs.data[p].split('|');
- for (var i = 0; i < arrValues.length; ++i) {
- if (browserInfo.hasOwnProperty(arrValues[i]))
- value += browserInfo[arrValues[i]];
- }
-
- var elm = document.createElement("input");elm.name = p;elm.value=value;elm.type='hidden';formElement.appendChild(elm);
- tokens[elm.name] = null;
-
- if((' ' + formElement.className + ' ').indexOf(' mailpoet_form ') > -1){
- elm.name = 'data[' + p + ']';formFieldElm.name = 'data[' + formFieldElm.name + ']';
- }
- }
- }
-
- window.jQuery && jQuery.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
-
- if(!formElement.querySelector('.nf-element'))
- return;
- console.log(options);console.log(originalOptions);
-
- if( !isObject(options) || !isObject(originalOptions) || !('data' in originalOptions) || !isObject(originalOptions.data))
- return;
-
- if( !('action' in originalOptions.data) || originalOptions.data.action !== 'nf_ajax_submit')
- return;
-
- for(var token in tokens){
- tokens[token] = formElement.querySelector('input[name="'+token+'"]');
- tokens[token] && (tokens[token] = tokens[token].value );
- }
-
- options.data = jQuery.param(jQuery.extend(originalOptions.data||{}, tokens));
-
- });
-
-
- }
- catch(e){console.log(e.message);}
- }
- }
- }
-
- init();
-
- function isObject(a) {return (!!a) && (a.constructor === Object);}
-
- function serializeObject(obj) {
- var str = [];
- for(var p in obj)
- if (obj.hasOwnProperty(p)) {
- str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
- }
- return str.join("&");
- }
- return {requestTokens : requestTokens};
- }
-
- window.WPBruiserClient = new WPBruiserClient();window.WPBruiserClient.requestTokens();
-
-})();
No newline at end of file
--- a/goodbye-captcha/assets/public/scripts/gdbc-client.js.php
+++ b/goodbye-captcha/assets/public/scripts/gdbc-client.js.php
@@ -1,172 +0,0 @@
-<?php
-
-defined( 'ABSPATH' ) || exit;
-
-add_filter('nocache_headers', function($arrHeaders){
- $arrHeaders['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
- $arrHeaders['Content-Type'] = 'application/javascript; charset=utf-8';
-
- return $arrHeaders;
-}, 1);
-
-nocache_headers();
-
-if(null === ($settingsModuleInstance = GdbcModulesController::getPublicModuleInstance(GdbcModulesController::MODULE_SETTINGS))){
- exit;
-}
-
-$arrPlaceHolders = array(
- '__INPUT_NAME__' => $settingsModuleInstance->getOption(GdbcSettingsAdminModule::OPTION_HIDDEN_INPUT_NAME),
- '__AJAX_URL__' => MchGdbcWpUtils::getAjaxUrl(),
- '__AJAX_NONCE__' => GdbcAjaxController::getAjaxNonce(),
- '__AJAX_ACTION__' => GdbcAjaxController::ACTION_RETRIEVE_TOKEN,
-
-);
-
-$scriptOutput = <<<Output
-(function() {'use strict';
- if (!Array.isArray){Array.isArray = function(arg){return Object.prototype.toString.call(arg) === '[object Array]';};}
- if (!String.prototype.trim){String.prototype.trim = function () {return this.replace(/^[suFEFFxA0]+|[suFEFFxA0]+$/g, '');};}
-
- var WPBruiserClient = function(){
- var browserInfo = new Array();
- function init(){
- var w=window,d=document,e=0,f=0;e|=w.ActiveXObject?1:0;e|=w.opera?2:0;e|=w.chrome?4:0;
- e|='getBoxObjectFor' in d || 'mozInnerScreenX' in w?8:0;e|=('WebKitCSSMatrix' in w||'WebKitPoint' in w||'webkitStorageInfo' in w||'webkitURL' in w)?16:0;
- e|=(e&16&&({}.toString).toString().indexOf("\n")===-1)?32:0;f|='sandbox' in d.createElement('iframe')?1:0;f|='WebSocket' in w?2:0;
- f|=w.Worker?4:0;f|=w.applicationCache?8:0;f|=w.history && history.pushState?16:0;f|=d.documentElement.webkitRequestFullScreen?32:0;f|='FileReader' in w?64:0;
-
- var ua = navigator.userAgent.toLowerCase();
- var regex = /compatible; ([w.+]+)[ /]([w.+]*)|([w .+]+)[: /]([w.+]+)|([w.+]+)/g;
- var match = regex.exec(ua);
- browserInfo = {screenWidth:screen.width,screenHeight:screen.height,engine:e,features:f};
- while (match !== null) {
- var prop = {};
- if (match[1]) {
- prop.type = match[1];
- prop.version = match[2];
- } else if (match[3]) {
- prop.type = match[3];
- prop.version = match[4];
- } else {
- prop.type = match[5];
- }
- prop.type = (prop.type).trim().replace('.','').replace(' ','_');
- var value = prop.version ? prop.version : true;
- if (browserInfo[prop.type]) {
- !Array.isArray(browserInfo[prop.type])?browserInfo[prop.type]=new Array(browserInfo[prop.type]):'';
- browserInfo[prop.type].push(value);
- }
- else browserInfo[prop.type] = value;
- match = regex.exec(ua);
- }
- };
-
-
- var requestTokens = function(){for(var i = 0; i < document.forms.length; ++i){retrieveToken(document.forms[i]);}};
-
- function retrieveToken(formElement){
-
- var requestObj = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
-
- var formFieldElm = formElement.querySelector('input[name="__INPUT_NAME__"]');
- if(!requestObj || !formFieldElm) return;
- var ajaxData = [];
-
- ajaxData['__INPUT_NAME__'] = '__AJAX_NONCE__';
- ajaxData['action'] = '__AJAX_ACTION__';
- ajaxData['requestTime'] = (new Date()).getTime();
- ajaxData['browserInfo'] = JSON.stringify(browserInfo);
-
- requestObj.open('POST', '__AJAX_URL__', true);
- requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
- requestObj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
- requestObj.setRequestHeader('Accept',"application/json, text/javascript, */*; q=0.01");
- requestObj.send(serializeObject(ajaxData));
-
- requestObj.onreadystatechange = function () {
- if (4 === requestObj.readyState && 200 === requestObj.status)
- {
- try
- {
- var rs = JSON.parse(requestObj.responseText);
- if(rs.data === 'undefined')
- return;
-
- var tokens = {};
-
- for(var p in rs.data)
- {
- if(p=='token')
- {
- formFieldElm.value = rs.data[p];
- tokens[formFieldElm.name] = null;
- }
- else
- {
- var value = '', arrValues = rs.data[p].split('|');
- for (var i = 0; i < arrValues.length; ++i) {
- if (browserInfo.hasOwnProperty(arrValues[i]))
- value += browserInfo[arrValues[i]];
- }
-
- var elm = document.createElement("input");elm.name = p;elm.value=value;elm.type='hidden';formElement.appendChild(elm);
- tokens[elm.name] = null;
-
- if((' ' + formElement.className + ' ').indexOf(' mailpoet_form ') > -1){
- elm.name = 'data[' + p + ']';formFieldElm.name = 'data[' + formFieldElm.name + ']';
- }
- }
- }
-
- window.jQuery && jQuery.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
-
- if( ! ('action' in originalOptions.data) || originalOptions.data.action !== 'nf_ajax_submit')
- return;
-
- for(var token in tokens){
- tokens[token] = formElement.querySelector('input[name="'+token+'"]');
- tokens[token] && (tokens[token] = tokens[token].value );
- }
-
- options.data = jQuery.param(jQuery.extend(originalOptions.data||{}, tokens));
-
- });
-
-
-
- }
- catch(e){console.log(e.message);}
- }
- }
- }
-
- init();
-
- function serializeObject(obj) {
- var str = [];
- for(var p in obj)
- if (obj.hasOwnProperty(p)) {
- str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
- }
- return str.join("&");
- }
- return {requestTokens : requestTokens};
- }
-
- window.WPBruiserClient = new WPBruiserClient();window.WPBruiserClient.requestTokens();
-
-})();
-Output;
-
-
-/**
- * compressed javascript https://jscompress.com/
- */
-//$scriptOutput = <<<Output
-//!function(){"use strict";Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[suFEFFxA0]+|[suFEFFxA0]+$/g,"")});window.WPBruiserClient=new function(){var p=new Array;function t(s){var c=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),u=s.querySelector('input[name="__INPUT_NAME__"]');if(c&&u){var e=[];e['__INPUT_NAME__']="__AJAX_NONCE__",e.action="__AJAX_ACTION__",e.requestTime=(new Date).getTime(),e.browserInfo=JSON.stringify(p),c.open("POST","__AJAX_URL__",!0),c.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8"),c.setRequestHeader("X-Requested-With","XMLHttpRequest"),c.setRequestHeader("Accept","application/json, text/javascript, */*; q=0.01"),c.send(function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.join("&")}(e)),c.onreadystatechange=function(){if(4===c.readyState&&200===c.status)try{var e=JSON.parse(c.responseText);if("undefined"===e.data)return;var a={};for(var t in e.data)if("token"==t)u.value=e.data[t],a[u.name]=null;else{for(var n="",r=e.data[t].split("|"),i=0;i<r.length;++i)p.hasOwnProperty(r[i])&&(n+=p[r[i]]);var o=document.createElement("input");o.name=t,o.value=n,o.type="hidden",s.appendChild(o),a[o.name]=null,-1<(" "+s.className+" ").indexOf(" mailpoet_form ")&&(o.name="data["+t+"]",u.name="data["+u.name+"]")}window.jQuery&&jQuery.ajaxPrefilter(function(e,t,n){if("action"in t.data&&"nf_ajax_submit"===t.data.action){for(var r in a)a[r]=s.querySelector('input[name="'+r+'"]'),a[r]&&(a[r]=a[r].value);e.data=jQuery.param(jQuery.extend(t.data||{},a))}})}catch(e){console.log(e.message)}}}}return function(){var e=window,t=document,n=0,r=0;n|=e.ActiveXObject?1:0,n|=e.opera?2:0,n|=e.chrome?4:0,n|="getBoxObjectFor"in t||"mozInnerScreenX"in e?8:0,n|="WebKitCSSMatrix"in e||"WebKitPoint"in e||"webkitStorageInfo"in e||"webkitURL"in e?16:0,n|=16&n&&-1==={}.toString.toString().indexOf("\n")?32:0,r|="sandbox"in t.createElement("iframe")?1:0,r|="WebSocket"in e?2:0,r|=e.Worker?4:0,r|=e.applicationCache?8:0,r|=e.history&&history.pushState?16:0,r|=t.documentElement.webkitRequestFullScreen?32:0,r|="FileReader"in e?64:0;var a=navigator.userAgent.toLowerCase(),i=/compatible; ([w.+]+)[ /]([w.+]*)|([w .+]+)[: /]([w.+]+)|([w.+]+)/g,o=i.exec(a);for(p={screenWidth:screen.width,screenHeight:screen.height,engine:n,features:r};null!==o;){var s={};o[1]?(s.type=o[1],s.version=o[2]):o[3]?(s.type=o[3],s.version=o[4]):s.type=o[5],s.type=s.type.trim().replace(".","").replace(" ","_");var c=!s.version||s.version;p[s.type]?(Array.isArray(p[s.type])||(p[s.type]=new Array(p[s.type])),p[s.type].push(c)):p[s.type]=c,o=i.exec(a)}}(),{requestTokens:function(){for(var e=0;e<document.forms.length;++e)t(document.forms[e])}}},window.WPBruiserClient.requestTokens()}();
-//Output;
-
-echo str_replace(array_keys($arrPlaceHolders), $arrPlaceHolders, $scriptOutput);
-
-
--- a/goodbye-captcha/engine/GdbcAjaxController.php
+++ b/goodbye-captcha/engine/GdbcAjaxController.php
@@ -17,40 +17,39 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
+defined( 'ABSPATH' ) || exit;
+
+// The public token endpoint verifies its own nonce in clientCanRetrieveToken();
+// the remaining $_POST reads only decide which third-party AJAX hooks to attach.
+// The token field is compared byte-for-byte against the value this plugin
+// issued, so it must not be passed through a sanitiser.
+// phpcs:disable WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput
+
final class GdbcAjaxController
{
CONST ACTION_RETRIEVE_TOKEN = 'gdbcRetrieveToken';
- CONST AJAX_NONCE_VALUE = __CLASS__;
+ CONST ACTION_RETRIEVE_NONCE = 'gdbcRetrieveNonce';
+ CONST CLIENT_NONCE_ACTION = 'gdbc-retrieve-token'; // nonce action for the public token flow
+ CONST AJAX_NONCE_VALUE = __CLASS__; // nonce action for the admin reports actions
public static function processRequest()
{
if( ! GdbcModulesController::isModuleRegistered(GdbcModulesController::MODULE_SETTINGS) )
return;
- if(self::isPublicGdbcAjaxRequest() ) {
-
- self::sendAjaxHeaders();
-
- if ( ! self::clientCanRetrieveToken() ) {
- wp_send_json_error();
- }
-
- $arrTokenData = GdbcRequestController::getEncryptedToken();
+ // Public token flow, registered the standard way (available to logged-out visitors).
+ add_action('wp_ajax_nopriv_' . self::ACTION_RETRIEVE_TOKEN, array(__CLASS__, 'sendEncryptedToken'));
+ add_action('wp_ajax_' . self::ACTION_RETRIEVE_TOKEN, array(__CLASS__, 'sendEncryptedToken'));
+ add_action('wp_ajax_nopriv_' . self::ACTION_RETRIEVE_NONCE, array(__CLASS__, 'sendFreshNonce'));
+ add_action('wp_ajax_' . self::ACTION_RETRIEVE_NONCE, array(__CLASS__, 'sendFreshNonce'));
- wp_send_json_success( $arrTokenData );
- exit;
- }
-
- if( ! did_action ('plugins_loaded') )
- return;
foreach(array(
GdbcModulesController::MODULE_MAIL_CHIMP_FOR_WP,
GdbcModulesController::MODULE_MAIL_POET,
- GdbcModulesController::MODULE_ZM_ALR,
GdbcModulesController::MODULE_NINJA_FORMS,
GdbcModulesController::MODULE_USER_PRO,
GdbcModulesController::MODULE_EASY_FORMS_FOR_MAILCHIMP,
@@ -61,7 +60,6 @@
GdbcModulesController::MODULE_QUFORM,
GdbcModulesController::MODULE_HTML_FORMS,
GdbcModulesController::MODULE_WP_FORMS,
- GdbcModulesController::MODULE_ULTRA_COMMUNITY,
) as $moduleName){
@@ -100,97 +98,88 @@
add_action('wp_ajax_' . $adminAjaxActionRequest, array(GdbcReportsAdminModule::getInstance(), $adminAjaxActionRequest));
}
- foreach(GoodByeCaptchaAdmin::getAdminRegisteredNotices() as $adminNotice){
- if( !($adminNotice instanceof GdbcAdminNotice) || !$adminNotice->isDismissible())
- continue;
-
- add_action('wp_ajax_gdbc-dismiss-' . $adminNotice->getFormattedNoticeKey(), array($adminNotice, 'dismiss'));
- }
-
- add_action('wp_ajax_gdbc-user-subscribed-newsletter', array(__CLASS__, 'userSubscribedToNewsLetter'));
-
- }
-
+ // Building the notices translates their messages, so it must not happen
+ // before `init` (WP 6.7 warns about loading a text domain too early).
+ // admin-ajax dispatches wp_ajax_* after init, so registering there is fine.
+ add_action('init', array(__CLASS__, 'registerNoticeDismissHandlers'), 20);
- if(GdbcModulesController::isModuleRegistered(GdbcModulesController::MODULE_LICENSES) && isset($_REQUEST['action']) && $_REQUEST['action'] === 'update-plugin')
- {
- GdbcLicensesAdminModule::getInstance()->registerAttachedHooks();
}
}
- public static function userSubscribedToNewsLetter()
+ public static function registerNoticeDismissHandlers()
{
- GdbcSettingsAdminModule::getInstance()->saveOption(GdbcSettingsAdminModule::OPTION_HIDE_SUBSCRIBE_FORM, true);
+ foreach(GoodByeCaptchaAdmin::getAdminRegisteredNotices() as $adminNotice){
+ if( !($adminNotice instanceof GdbcAdminNotice) || !$adminNotice->isDismissible())
+ continue;
+
+ add_action('wp_ajax_gdbc-dismiss-' . $adminNotice->getFormattedNoticeKey(), array($adminNotice, 'dismiss'));
+ }
}
+ /**
+ * Whether the current request may be issued an anti-spam token.
+ *
+ * @return true|string true, or an error code for the client ("invalid_nonce"
+ * tells it the page-cached nonce expired and to fetch a new one).
+ */
private static function clientCanRetrieveToken()
{
-
$settingsModuleInstance = GdbcModulesController::getPublicModuleInstance(GdbcModulesController::MODULE_SETTINGS);
if(null === $settingsModuleInstance)
- return false;
+ return 'unavailable';
if(null === ($hiddenInputName = $settingsModuleInstance->getOption(GdbcSettingsAdminModule::OPTION_HIDDEN_INPUT_NAME)))
- return false;
+ return 'unavailable';
- if(empty($_POST[$hiddenInputName]))
- return false;
+ $accept = isset($_SERVER['HTTP_ACCEPT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_ACCEPT'])) : '';
+ $requestedWith = isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_X_REQUESTED_WITH'])) : '';
+ if(false === stripos($accept, 'json') || 0 !== strcasecmp($requestedWith, 'XMLHttpRequest'))
+ return 'bad_request';
- if(!isset($_SERVER['HTTP_ACCEPT']) || false === stripos($_SERVER['HTTP_ACCEPT'], 'json'))
- return false;
-
- if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || (0 !== strcasecmp($_SERVER['HTTP_X_REQUESTED_WITH'], 'XMLHttpRequest')))
- return false;
-
- require_once( ABSPATH . WPINC . '/pluggable.php' );
-
- ( !defined('LOGGED_IN_COOKIE') && function_exists('wp_cookie_constants') ) ? wp_cookie_constants() : null;
-
- if(false === wp_verify_nonce($_POST[$hiddenInputName], __CLASS__))
- return false;
+ $nonce = isset($_POST[$hiddenInputName]) ? sanitize_text_field(wp_unslash($_POST[$hiddenInputName])) : '';
+ if('' === $nonce || false === wp_verify_nonce($nonce, self::CLIENT_NONCE_ACTION))
+ return 'invalid_nonce';
if(GdbcIPUtils::isClientIpBlackListed())
- return false;
+ return 'blocked';
return true;
-
}
-
- public static function isWpDiscuzPostCommentAjaxRequest()
+ public static function sendEncryptedToken()
{
- return !empty($_POST['wpdiscuz_unique_id']) && !empty($_POST['postId']) && MchGdbcWpUtils::isAjaxRequest() && GoodByeCaptchaUtils::isWPDiscuzPluginActivated();
+ $canRetrieve = self::clientCanRetrieveToken();
+ if(true !== $canRetrieve) {
+ wp_send_json_error(array('code' => $canRetrieve));
+ }
+
+ wp_send_json_success( GdbcRequestController::getEncryptedToken() );
}
- private static function sendAjaxHeaders()
+ /**
+ * A fresh nonce for the token flow. Pages served from a page cache carry the
+ * nonce that was current when they were rendered; once it expires the client
+ * calls this and retries. The token endpoint is meant for anonymous visitors,
+ * so handing out its nonce on request gives nothing away.
+ */
+ public static function sendFreshNonce()
{
- wp_magic_quotes();
- send_origin_headers();
-
- @header('X-Robots-Tag: noindex' );
+ wp_send_json_success(array('nonce' => self::getAjaxNonce()));
+ }
- send_nosniff_header();
- nocache_headers();
- @header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
- @header('Content-Type: application/json; charset=' . get_option( 'blog_charset' ));
+ public static function isWpDiscuzPostCommentAjaxRequest()
+ {
+ return !empty($_POST['wpdiscuz_unique_id']) && !empty($_POST['postId']) && MchGdbcWpUtils::isAjaxRequest() && GoodByeCaptchaUtils::isWPDiscuzPluginActivated();
}
- private static function isPublicGdbcAjaxRequest()
- {
- if(empty($_POST['browserInfo']) || empty($_POST['action']) || (self::ACTION_RETRIEVE_TOKEN !== $_POST['action']))
- return false;
- return true;
- }
public static function getAjaxNonce()
{
- require_once( ABSPATH . WPINC . '/pluggable.php' );
-
- return wp_create_nonce(__CLASS__);
+ return wp_create_nonce(self::CLIENT_NONCE_ACTION);
}
public static function isAdminAjaxRequestValid()
--- a/goodbye-captcha/engine/GdbcBruteGuardian.php
+++ b/goodbye-captcha/engine/GdbcBruteGuardian.php
@@ -17,17 +17,18 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
+defined( 'ABSPATH' ) || exit;
+
+// This module inspects submissions to a third-party public form to decide whether
+// they came from a bot. Those forms carry no plugin nonce, so reading $_POST
+// without one is intentional; values are validated before use.
+// phpcs:disable WordPress.Security.NonceVerification
+
final class GdbcBruteGuardian
{
- private static $arrSecurityDirectoryFiles = array(
- '.htaccess' => 'deny from all',
- 'index.php' => '<?php',
- 'index.html' => '',
- );
private static $SITE_UNDER_ATTACK_FLAG = 'wpbr-uad'; //under-attack-detected
- private static $SITE_ATTACK_WARNING_FLAG = 'wpbr-sid'; //suspicious-ips-detected
public static function startGuarding()
{
@@ -38,7 +39,6 @@
return;
self::$SITE_UNDER_ATTACK_FLAG .= '-' . get_current_blog_id();
- self::$SITE_ATTACK_WARNING_FLAG .= '-' . get_current_blog_id();
$loginAttemptsHits = 0;
@@ -106,7 +106,7 @@
private static function flagExists($flagName)
{
- $cacheHolder = GoodByeCaptchaUtils::getAvailableCacheStorage(self::getBaseCacheDirectoryPath());
+ $cacheHolder = GoodByeCaptchaUtils::getAvailableCacheStorage();
if(null === $cacheHolder)
return 0;
@@ -115,7 +115,7 @@
private static function setSiteFlag($flagName, $flagBooleanValue)
{
- $cacheHolder = GoodByeCaptchaUtils::getAvailableCacheStorage(self::getBaseCacheDirectoryPath());
+ $cacheHolder = GoodByeCaptchaUtils::getAvailableCacheStorage();
if(null === $cacheHolder)
return;
@@ -123,48 +123,9 @@
return $cacheHolder->delete($flagName);
}
- if($cacheHolder->getCacheStorage() instanceof MchGdbcCacheFileStorage)
- {
- foreach(self::$arrSecurityDirectoryFiles as $fileName => $fileContent)
- {
- $filePath = self::getBaseCacheDirectoryPath() . DIRECTORY_SEPARATOR . $fileName;
- if(MchGdbcWpUtils::fileExists($filePath))
- break;
-
- MchGdbcWpUtils::writeContentToFile($fileContent, $filePath, false);
- }
- }
-
$cacheHolder->write($flagName, MchGdbcHttpRequest::getServerRequestTime(false));
}
- private static function getBaseCacheDirectoryPath()
- {
- static $cacheDirectoryPath = false;
- if(false !== $cacheDirectoryPath)
- return $cacheDirectoryPath;
-
-// $cacheDirectoryPath = GdbcSettingsPublicModule::getInstance()->getOption(GdbcSettingsAdminModule::OPTION_CACHE_DIR_PATH);
-// if(!empty($cacheDirectoryPath)){
-// $cacheDirectoryPath .= DIRECTORY_SEPARATOR . GoodByeCaptcha::PLUGIN_SLUG . DIRECTORY_SEPARATOR . get_current_blog_id();
-// if(MchGdbcWpUtils::isDirectoryUsable($cacheDirectoryPath, true)){
-// return $cacheDirectoryPath;
-// }
-// }
-
- $cacheDirectoryPath = MchGdbcWpUtils::getDirectoryPathForCache();
- if(null === $cacheDirectoryPath)
- return null;
-
- $cacheDirectoryPath .= DIRECTORY_SEPARATOR . GoodByeCaptcha::PLUGIN_SLUG . DIRECTORY_SEPARATOR . get_current_blog_id();
- if(! MchGdbcWpUtils::isDirectoryUsable($cacheDirectoryPath, true) ) {
- return $cacheDirectoryPath = null;
- }
-
-// GdbcSettingsAdminModule::getInstance()->saveOption(GdbcSettingsAdminModule::OPTION_CACHE_DIR_PATH, MchGdbcWpUtils::getDirectoryPathForCache());
-
- return $cacheDirectoryPath;
- }
public static function isFormEntryLogEnabled()
@@ -186,49 +147,21 @@
GdbcDbAccessController::registerAttempt( $attemptEntity );
-// if(self::isSiteUnderAttack() && GoodByeCaptchaUtils::isLoginAttemptEntity($attemptEntity) && ( !GdbcIPUtils::isClientIpWhiteListed() )){
-// self::registerClientIpBruteForceRequest();
-// }
}
- private static function getIpAddressDirPath($flagName, $ipAddress)
- {
- if (null === self::getBaseCacheDirectoryPath())
- return null;
- $subDirectoryName = null;
- switch ($flagName)
- {
- case self::$SITE_UNDER_ATTACK_FLAG : $subDirectoryName = 'brute-ips'; break;
- case self::$SITE_ATTACK_WARNING_FLAG : $subDirectoryName = 'suspicious-ips'; break;
- }
-
- return self::getBaseCacheDirectoryPath() . DIRECTORY_SEPARATOR . $subDirectoryName . DIRECTORY_SEPARATOR . $ipAddress;
- }
- private static function isClientIpBruteForcing()
- {
- return @is_dir(self::getIpAddressDirPath(self::$SITE_UNDER_ATTACK_FLAG, GdbcIPUtils::getClientIpAddress()));
- }
- private static function registerClientIpBruteForceRequest()
+ /**
+ * Remove the flags this class keeps in transients (used on uninstall).
+ */
+ public static function deleteSiteFlags()
{
- if(self::isClientIpBruteForcing())
- {
- MchGdbcWpUtils::writeContentToFile(null, self::getIpAddressDirPath(self::$SITE_UNDER_ATTACK_FLAG, GdbcIPUtils::getClientIpAddress()) . DIRECTORY_SEPARATOR . MchGdbcHttpRequest::getServerRequestTime(true) . '.gdbc', false);
- return;
- }
-
- if( ! MchGdbcWpUtils::isDirectoryUsable(self::getIpAddressDirPath(self::$SITE_UNDER_ATTACK_FLAG, GdbcIPUtils::getClientIpAddress()), true) )
+ if(null === ($cacheHolder = GoodByeCaptchaUtils::getAvailableCacheStorage()))
return;
- foreach(self::$arrSecurityDirectoryFiles as $fileName => $fileContent){
- $filePath = self::getIpAddressDirPath(self::$SITE_UNDER_ATTACK_FLAG, GdbcIPUtils::getClientIpAddress()) . DIRECTORY_SEPARATOR . $fileName;
- MchGdbcWpUtils::writeContentToFile($fileContent, $filePath, false);
- }
-
- MchGdbcWpUtils::writeContentToFile(null, self::getIpAddressDirPath(self::$SITE_UNDER_ATTACK_FLAG, GdbcIPUtils::getClientIpAddress()) . DIRECTORY_SEPARATOR . MchGdbcHttpRequest::getServerRequestTime(true) . '.gdbc', false);
+ $cacheHolder->delete('wpbr-uad-' . get_current_blog_id());
}
private function __construct()
--- a/goodbye-captcha/engine/GdbcIPUtils.php
+++ b/goodbye-captcha/engine/GdbcIPUtils.php
@@ -18,6 +18,8 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
+defined( 'ABSPATH' ) || exit;
+
final class GdbcIPUtils
{
public static function isClientIpBlockedByCountry()
--- a/goodbye-captcha/engine/GdbcModulesController.php
+++ b/goodbye-captcha/engine/GdbcModulesController.php
@@ -18,6 +18,8 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
+defined( 'ABSPATH' ) || exit;
+
spl_autoload_register(array('GdbcModulesController','autoLoadModulesClasses'));
final class GdbcModulesController
@@ -66,7 +68,6 @@
CONST MODULE_PLANSO_FORMS = 'PlanSoForms';
CONST MODULE_EMAIL_NOTIFICATIONS = 'EmailNotifications';
- CONST MODULE_LICENSES = 'Licenses';
CONST MODULE_MEMBER_PRESS = 'MemberPress';
CONST MODULE_PROXY_HEADERS = 'ProxyHeaders';
@@ -355,17 +356,6 @@
)
),
- self::MODULE_LICENSES => array(
- 'info' => array(
- 'ModuleId' => 26,
- 'IsLicensed' => false,
- ),
- 'classes' => array(
- 'GdbcLicensesAdminModule' => '/modules/licenses/GdbcLicensesAdminModule.php',
- 'GdbcLicensesPublicModule' => '/modules/licenses/GdbcLicensesPublicModule.php',
- )
- ),
-
self::MODULE_MEMBER_PRESS => array(
'info' => array(
'ModuleId' => 27,
@@ -535,12 +525,6 @@
self::$arrRegisteredModules = array();
- $activatedPlugins = defined('WP_PLUGIN_DIR') ? array_merge( array_flip((array) get_option( 'active_plugins', array())), (array) get_site_option( 'active_sitewide_plugins', array() ) ) : array(); // wp_get_mu_plugins()
-
- if(defined('ABSPATH')){
- unset($activatedPlugins[plugin_basename(GoodByeCaptcha::getMainFilePath())]); // un-setting the plugin itself
- }
-
$engineDirPath = dirname(__FILE__) . DIRECTORY_SEPARATOR;
foreach(self::$arrAllModules as $moduleName => $arrModule)
@@ -549,45 +533,16 @@
foreach ($arrModule['classes'] as $className => $filePath)
{
- $filePath = $engineDirPath . ( $dirPath = trim( dirname($filePath) , '/\' ) . DIRECTORY_SEPARATOR . basename($filePath) );
+ $filePath = $engineDirPath . trim( dirname($filePath) , '/\' ) . DIRECTORY_SEPARATOR . basename($filePath);
+ // Only ever load module classes that ship inside this plugin. Earlier
+ // releases also scanned other activated plugins' directories and
+ // included PHP files found there (the paid "extension" plugins). That
+ // external module-loading path has been removed: a plugin must not
+ // execute code sourced from outside its own directory.
if(@file_exists($filePath)){
self::$arrRegisteredModules[$moduleName][$className] = $filePath;
- continue;
- }
-
- foreach($activatedPlugins as $activePlugin => $value)
- {
- if( (false === strpos($activePlugin, GoodByeCaptcha::PLUGIN_SLUG)) && (false === strpos($activePlugin, "GoodByeCaptcha")) ){
- unset($activatedPlugins[$activePlugin]);continue;
- }
-
- if(false === strpos($activePlugin, self::getModuleStandAloneDirectoryName($moduleName)))
- continue;
-
- $filePath = dirname(WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . MchGdbcUtils::stripLeftAndRightSlashes($activePlugin) ) . "/engine/$dirPath" ;
-
- break;
}
-
- if(@file_exists($filePath))
- {
- self::$arrRegisteredModules[$moduleName][$className] = $filePath;
- continue;
- }
-
- # WPBruiser old extensions
- foreach($activatedPlugins as $activePlugin => $value)
- {
- if(false === strpos($activePlugin, "GoodByeCaptcha$moduleName"))
- continue;
-
- $filePath = @dirname(WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $activePlugin ) . "/engine/$dirPath" ;
-
- break;
- }
-
- @file_exists($filePath) ? self::$arrRegisteredModules[$moduleName][$className] = $filePath : null;
}
if(empty(self::$arrRegisteredModules[$moduleName]))
@@ -597,89 +552,16 @@
}
- public static function getModuleStandAloneDirectoryName($moduleName)
- {
- return strtolower(GoodByeCaptcha::PLUGIN_SLUG . '-' . MchGdbcUtils::stripNonAlphaNumericCharacters($moduleName));
- }
-
- public static function getModuleStandAloneDirectoryPath($moduleName)
- {
- if(!self::isModuleRegistered($moduleName))
- return null;
-
- $moduleClassName = self::getModuleStandAloneClassName($moduleName);
- if(!class_exists($moduleClassName))
- {
- if(!defined('WP_PLUGIN_DIR'))
- return null;
-
- return WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . self::getModuleStandAloneDirectoryName($moduleName);
- }
-
- $classReflector = new ReflectionClass($moduleClassName);
-
- return dirname($classReflector->getFileName());
-
- }
-
- public static function getModuleStandAloneClassName($moduleName)
- {
- return MchGdbcUtils::stripNonAlphaNumericCharacters(GoodByeCaptcha::PLUGIN_NAME . $moduleName);
- }
-
-
public static function getModuleIdByName($moduleName)
{
return isset(self::$arrAllModules[$moduleName]['info']['ModuleId']) ? self::$arrAllModules[$moduleName]['info']['ModuleId'] : null;
}
- public static function isLicensedModule($moduleIdORmoduleName)
- {
- $moduleName = ((false === filter_var($moduleIdORmoduleName, FILTER_VALIDATE_INT)) ? $moduleIdORmoduleName : self::getModuleNameById($moduleIdORmoduleName));
-
- return !empty(self::$arrAllModules[$moduleName]['info']['IsLicensed']);
- }
-
public static function unRegisterModule($moduleName)
{
unset(self::$arrRegisteredModules[(string)$moduleName]);
}
- public static function getNotLicensedModuleNames()
- {
- $arrFreeModules = array();
- foreach(self::$arrAllModules as $moduleName => $arrAllModuleSettings){
- empty(self::$arrAllModules[$moduleName]['info']['IsLicensed']) ? $arrFreeModules[] = $moduleName : null;
- }
-
- return $arrFreeModules;
- }
-
- public static function getLicensedModuleNames()
- {
- $arrModules = array();
- foreach(self::$arrAllModules as $moduleName => $arrAllModuleSettings){
- !empty(self::$arrAllModules[$moduleName]['info']['IsLicensed']) ? $arrModules[] = $moduleName : null;
- }
-
- return $arrModules;
- }
-
- public static function isModuleIncludedInProBundle($moduleName)
- {
- if(!self::isModuleRegistered($moduleName))
- return false;
-
- if(!self::isLicensedModule($moduleName))
- return true;
-
- if( GoodByeCaptcha::isProVersion() ) {
- return 0 === strpos(self::getModuleDirectoryPath($moduleName), dirname(__FILE__));
- }
-
- return false;
- }
-
public static function getModuleNameById($moduleId)
{
foreach(self::$arrAllModules as $moduleKey => $moduleValue)
--- a/goodbye-captcha/engine/GdbcNotificationsController.php
+++ b/goodbye-captcha/engine/GdbcNotificationsController.php
@@ -17,13 +17,15 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
+defined( 'ABSPATH' ) || exit;
+
final class GdbcNotificationsController
{
public static function sendTestModeEmailNotification(GdbcAttemptEntity $gdbcAttemptEntity)
{
- GdbcEmailNotificationsPublicModule::getInstance()->EmailSubject = __('WPBruiser - Test Mode Notification', GoodByeCaptcha::PLUGIN_SLUG);
+ GdbcEmailNotificationsPublicModule::getInstance()->EmailSubject = __('WPBruiser - Test Mode Notification', 'goodbye-captcha');
$clientIpAddress = GdbcIPUtils::getClientIpAddress();
$currentSiteLink = MchGdbcWpUtils::getCurrentBlogLink();
@@ -39,7 +41,7 @@
if(empty($moduleDirPath))
{
- GdbcEmailNotificationsPublicModule::getInstance()->EmailBodyContent = __('WPBruiser encountered an error while trying to parse the email template!', GoodByeCaptcha::PLUGIN_SLUG);
+ GdbcEmailNotificationsPublicModule::getInstance()->EmailBodyContent = __('WPBruiser encountered an error while trying to parse the email template!', 'goodbye-captcha');
}
else
{
@@ -58,7 +60,7 @@
if( ! GdbcEmailNotificationsPublicModule::getInstance()->getOption(GdbcEmailNotificationsAdminModule::OPTION_BRUTE_FORCE_ATTACK_DETECTED) )
return;
- GdbcEmailNotificationsPublicModule::getInstance()->EmailSubject = __('Alert - Brute Force Attack Detected by WPBruiser!', GoodByeCaptcha::PLUGIN_SLUG);
+ GdbcEmailNotificationsPublicModule::getInstance()->EmailSubject = __('Alert - Brute Force Attack Detected by WPBruiser!', 'goodbye-captcha');
$adminFullName = MchGdbcWpUtils::getAdminFullName();
empty($adminFullName) ? $adminFullName = MchGdbcWpUtils::getAdminDisplayName() : null;
@@ -69,8 +71,8 @@
$totalWebAttackers = 0;
$totalBlackListed = 0;
- $detectedDate = get_date_from_gmt ( date( 'Y-m-d H:i:s', MchGdbcHttpRequest::getServerRequestTime() ), 'l, F d, Y');
- $detectedTime = get_date_from_gmt ( date( 'Y-m-d H:i:s', MchGdbcHttpRequest::getServerRequestTime() ), 'H:i:s');
+ $detectedDate = get_date_from_gmt ( gmdate( 'Y-m-d H:i:s', MchGdbcHttpRequest::getServerRequestTime() ), 'l, F d, Y');
+ $detectedTime = get_date_from_gmt ( gmdate( 'Y-m-d H:i:s', MchGdbcHttpRequest::getServerRequestTime() ), 'H:i:s');
foreach($arrLoginAttempts as $clientIp => $hits)
{
@@ -132,7 +134,11 @@
$moduleDirPath = GdbcModulesController::getModuleDirectoryPath(GdbcModulesController::MODULE_EMAIL_NOTIFICATIONS);
if(empty($moduleDirPath))
{
- GdbcEmailNotificationsPublicModule::getInstance()->EmailBodyContent = __("Brute Force attack detected on " . MchGdbcWpUtils::getCurrentBlogLink(), GoodByeCaptcha::PLUGIN_SLUG);
+ GdbcEmailNotificationsPublicModule::getInstance()->EmailBodyContent = sprintf(
+ /* translators: %s: link to the site the attack was detected on. */
+ __('Brute Force attack detected on %s', 'goodbye-captcha'),
+ MchGdbcWpUtils::getCurrentBlogLink()
+ );
}
else
{
--- a/goodbye-captcha/engine/GdbcRequestController.php
+++ b/goodbye-captcha/engine/GdbcRequestController.php
@@ -18,6 +18,17 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
+defined( 'ABSPATH' ) || exit;
+
+// This controller inspects submissions to public forms (comments, login,
+// registration) to decide whether they came from a bot. Those forms are not the
+// plugin's own and carry no plugin nonce, so reading $_POST without one is the
+// whole point of the check. Values are validated before use.
+// The token fields below are unslashed and then compared byte-for-byte against
+// the value this plugin issued; a sanitiser would alter the bytes and break the
+// check. Everything else read here is validated by getSubmittedBrowserInfo().
+// phpcs:disable WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput
+
final class GdbcRequestController
{
@@ -120,7 +131,7 @@
return false;
}
- $receivedToken = isset($_POST[$hiddenInputName]) ? $_POST[$hiddenInputName] : null;
+ $receivedToken = (isset($_POST[$hiddenInputName]) && is_string($_POST[$hiddenInputName])) ? wp_unslash($_POST[$hiddenInputName]) : null;
if(null === $receivedToken){
self::$rejectReasonCode = self::REJECT_REASON_TOKEN_MISSING;
@@ -143,7 +154,7 @@
self::$browserInfoInputName = substr($arrDecryptedToken[0], 0, $tokenIndex);
- $receivedBrowserInfoInput = isset($_POST[self::$browserInfoInputName]) ? $_POST[self::$browserInfoInputName] : null;
+ $receivedBrowserInfoInput = (isset($_POST[self::$browserInfoInputName]) && is_string($_POST[self::$browserInfoInputName])) ? wp_unslash($_POST[self::$browserInfoInputName]) : null;
if( null === $receivedBrowserInfoInput )
{
@@ -193,27 +204,65 @@
}
- public static function getEncryptedToken()
+ /**
+ * The browser fingerprint the client posted, decoded and validated.
+ *
+ * json_decode() does not sanitise, so every key and value is checked against a
+ * strict shape and anything else is dropped. Values are validated rather than
+ * transformed on purpose: the browser later re-sends the same values
+ * byte-for-byte to prove the token is its own, so altering them here would make
+ * every legitimate visitor fail that comparison.
+ *
+ * @return array<string, bool|int|float|string>
+ */
+ private static function getSubmittedBrowserInfo()
{
- if( ! isset($_POST['browserInfo']) || null === ($arrBrowserInfo = json_decode(stripcslashes($_POST['browserInfo']), true)))
+ if(!isset($_POST['browserInfo']) || !is_string($_POST['browserInfo']))
+ return array();
+
+ $rawJson = wp_unslash($_POST['browserInfo']);
+ if(!isset($rawJson[1]) || isset($rawJson[4096])) // a fingerprint is a few hundred bytes
+ return array();
+
+ $arrDecoded = json_decode($rawJson, true);
+ if(!is_array($arrDecoded))
return array();
- foreach ((array)$arrBrowserInfo as $prop => $propValue)
+ $arrBrowserInfo = array();
+ foreach($arrDecoded as $key => $value)
{
- if(!is_array($propValue) && false === strpos($prop, ' '))
+ if(!is_string($key) || !preg_match('/^[A-Za-z0-9_+-]{1,64}$/', $key))
continue;
- unset($arrBrowserInfo[$prop]);
+ if(is_bool($value) || is_int($value) || is_float($value)) {
+ $arrBrowserInfo[$key] = $value;
+ }
+ elseif(is_string($value) && preg_match('/^[A-Za-z0-9_.+- ]{0,128}$/', $value)) {
+ $arrBrowserInfo[$key] = $value;
+ }
+ // arrays, objects and anything with other characters are rejected
}
+ return $arrBrowserInfo;
+ }
+
+ public static function getEncryptedToken()
+ {
+ $arrBrowserInfo = self::getSubmittedBrowserInfo();
+ if(empty($arrBrowserInfo))
+ return array();
+
if( ($arrBrowserInfoLength = count($arrBrowserInfo)) < 3)
return array();
- $arrKeysToSave = array_flip((array)array_rand($arrBrowserInfo, mt_rand(3, $arrBrowserInfoLength - 1)));
+ $arrKeysToSave = array_flip((array)array_rand($arrBrowserInfo, wp_rand(3, $arrBrowserInfoLength - 1)));
foreach ($arrKeysToSave as $key => &$val)
{
- $val = var_export($arrBrowserInfo[$key], true);
+ // Not debug output: var_export() is used here purely to serialise the
+ // browser-info value into the string that becomes part of the encrypted
+ // token. Changing the representation would invalidate issued tokens.
+ $val = var_export($arrBrowserInfo[$key], true); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
}
$arrTokenData = self::getTokenData();
@@ -222,7 +271,7 @@
array_unshift($arrTokenData, $browserField . self::TOKEN_SEPARATOR . MchGdbcUtils::replaceNonAlphaNumericCharacters(implode('', array_values($arrKeysToSave)), ''));
return array(
- 'token' => MchCrypt::encryptToken(GdbcSettingsPublicModule::getInstance()->getOption(GdbcSettingsAdminModule::OPTION_TOKEN_SECRET_KEY), json_encode($arrTokenData)),
+ 'token' => MchCrypt::encryptToken(GdbcSettingsPublicModule::getInstance()->getOption(GdbcSettingsAdminModule::OPTION_TOKEN_SECRET_KEY), wp_json_encode($arrTokenData)),
$browserField => implode(self::TOKEN_SEPARATOR, array_keys($arrKeysToSave))
);
@@ -258,25 +307,25 @@
{
$arrReasonDescription = array(
- self::REJECT_REASON_TOKEN_INVALID => __('Invalid Token', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_TOKEN_MISSING => __('Token Not Submitted', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_TOKEN_EXPIRED => __('Token Expired', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_TOKEN_SUBMITTED_EARLY => __('Token Submitted Early', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_CLIENT_IP_BLOCKED => __('Client IP Blocked', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_BROWSER_INFO_MISSING => __('Browser Info Missing', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_BROWSER_INFO_INVALID => __('Browser Info Invalid', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_CLIENT_IP_UNDETECTABLE => __('Undetectable Client IP', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_USER_ENUMERATION => __('User Enumeration', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_PROXY_ANONYMIZER => __('Proxy Anonymizer', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_WEB_ATTACKER => __('Web Attacker', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_SERVICE_UNAVAILABLE => __('Service Unavailable', GoodByeCaptcha::PLUGIN_SLUG),
- //self::REJECT_REASON_LINK_NOTIFICATION => __('Link Notification', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_COMMENT_FIELD_TOO_LONG => __('Comment Field Too Long', GoodByeCaptcha::PLUGIN_SLUG),
- self::REJECT_REASON_COUNTRY_IP_BLOCKED => __('Blocked Country', GoodByeCaptcha::PLUGIN_SLUG),
+ self::REJECT_REASON_TOKEN_INVALID => __('Invalid Token', 'goodbye-captcha'),
+ self::REJECT_REASON_TOKEN_MISSING => __('Token Not Submitted', 'goodbye-captcha'),
+ self::REJECT_REASON_TOKEN_EXPIRED => __('Token Expired', 'goodbye-captcha'),
+ self::REJECT_REASON_TOKEN_SUBMITTED_EARLY => __('Token Submitted Early', 'goodbye-captcha'),
+ self::REJECT_REASON_CLIENT_IP_BLOCKED => __('Client IP Blocked', 'goodbye-captcha'),
+ self::REJECT_REASON_BROWSER_INFO_MISSING => __('Browser Info Missing', 'goodbye-captcha'),
+ self::REJECT_REASON_BROWSER_INFO_INVALID => __('Browser Info Invalid', 'goodbye-captcha'),
+ self::REJECT_REASON_CLIENT_IP_UNDETECTABLE => __('Undetectable Client IP', 'goodbye-captcha'),
+ self::REJECT_REASON_USER_ENUMERATION => __('User Enumeration', 'goodbye-captcha'),
+ self::REJECT_REASON_PROXY_ANONYMIZER => __('Proxy Anonymizer', 'goodbye-captcha'),
+ self::REJECT_REASON_WEB_ATTACKER => __('Web Attacker', 'goodbye-captcha'),
+ self::REJECT_REASON_SERVICE_UNAVAILABLE => __('Service Unavailable', 'goodbye-captcha'),
+ //self::REJECT_REASON_LINK_NOTIFICATION => __('Link Notification', 'goodbye-captcha'),
+ self::REJECT_REASON_COMMENT_FIELD_TOO_LONG => __('Comment Field Too Long', 'goodbye-captcha'),
+ self::REJECT_REASON_COUNTRY_IP_BLOCKED => __('Blocked Country', 'goodbye-captcha'),
);
}
- return isset($arrReasonDescription[$reasonId]) ? $arrReasonDescription[$reasonId] : __('Unknown', GoodByeCaptcha::PLUGIN_SLUG);
+ return isset($arrReasonDescription[$reasonId]) ? $arrReasonDescription[$reasonId] : __('Unknown', 'goodbye-captcha');
}
@@ -288,7 +337,7 @@
public static function redirectToHomePage()
{
- wp_redirect( home_url() ); exit;
+ wp_safe_redirect( home_url() ); exit;
}
}
--- a/goodbye-captcha/engine/GdbcTaskScheduler.php
+++ b/goodbye-captcha/engine/GdbcTaskScheduler.php
@@ -17,6 +17,8 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
+defined( 'ABSPATH' ) || exit;
+
final class GdbcTaskScheduler
{
private static function getGdbcTasks()
--- a/goodbye-captcha/engine/GdbcUpdatesController.php
+++ b/goodbye-captcha/engine/GdbcUpdatesController.php
@@ -17,6 +17,13 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
+defined( 'ABSPATH' ) || exit;
+
+// One-off schema migrations against the plugin's own table. Table names derive
+// from $wpdb->base_prefix, not user input, and identifiers cannot be bound as
+// prepare() placeholders. These run once per upgrade, so caching does not apply.
+// phpcs:disable WordPress.DB, PluginCheck.Security.DirectDB
+
final class GdbcUpdatesController
{
public static function updateToCurrentVersion()
@@ -29,6 +36,8 @@
if(null === $savedPluginVersion) // fresh install. Save default options
{
+ GdbcDbAccessController::createAttemptsTable();
+
foreach(array_keys(GdbcModulesController::getRegisteredModules()) as $moduleName)
{
if(null === ($adminModuleInstance = GdbcModulesController::getAdminModuleInstance($moduleName)))
@@ -42,6 +51,24 @@
$adminModuleInstance->saveOption($optionName, $optionValue);
}
}
+
+ // Leaving $savedPluginVersion as null had two consequences: PHP 8.1+ emits a
+ // deprecation for every version_compare() call below, and null compares lower
+ // than every version string, so a brand-new install ran the whole chain of
+ // 1.x -> 3.x migration steps.
+ //
+ // A version 1.x install predates this option, so it also has no saved version.
+ // isUpdateFromV1() tells the two cases apart: genuine upgrades keep running the
+ // migrations, new installs record the current version and skip them.
+ if( self::isUpdateFromV1() )
+ {
+ $savedPluginVersion = '1.0';
+ }
+ else
+ {
+ $savedPluginVersion = GoodByeCaptcha::PLUGIN_VERSION;
+ $settingsModuleInstance->saveOption(GdbcSettingsAdminModule::OPTION_PLUGIN_VERSION, GoodByeCaptcha::PLUGIN_VERSION);
+ }
}
@@ -224,8 +251,8 @@
- $minDateTime = date('Y-m-d H:i:s', strtotime(((-1) * (30)) . ' days', current_time( 'timestamp' )));
- $maxDateTime = date('Y-m-d H:i:s', current_time( 'timestamp' ));
+ $minDateTime = gmdate('Y-m-d H:i:s', strtotime(((-1) * (30)) . ' days', current_time( 'timestamp' )));
+ $maxDateTime = gmdate('Y-m-d H:i:s', current_time( 'timestamp' ));
$gdbcAttemptsQuery = "
SELECT Id, UNIX_TIMESTAMP(CreatedDate) AS CreatedDate, ModuleId, SectionId, ClientIp, CountryId, ReasonId
@@ -287,10 +314,6 @@
{
GdbcJetPackContactFormAdminModule::getInstance()->saveOption(GdbcJetPackContactFormAdminModule::OPTION_IS_JETPACK_CONTACT_FORM_ACTIVATE, true);
}
- if(!empty($oldSettingsOptions['IsPFActivated']) && GdbcModulesController::isModuleRegistered(GdbcModulesController::MODULE_PLANSO_FORMS))
- {
- GdbcPlanSoFormsAdminModule::getInstance()->saveOption(GdbcPlanSoFormsAdminModule::OPTION_PLANSO_GENERAL_FORM, true);
- }
delete_site_option('gdbcsettingsadminmodule-settings');
delete_site_option('gdbcwordpressadminmodule-settings');
--- a/goodbye-captcha/engine/GoodByeCaptchaAdmin.php
+++ b/goodbye-captcha/engine/GoodByeCaptchaAdmin.php
@@ -17,6 +17,8 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
+defined( 'ABSPATH' ) || exit;
+
final class GoodByeCaptchaAdmin extends MchGdbcBaseAdminPlugin
{
CONST GDBC_ADMIN_NOTICES_FILTER_KEY = 'gdbc-admin-notices';
@@ -28,21 +30,12 @@
parent::__construct($arrPluginInfo);
- $this->adminPagesList = array(
-
- new GdbcSettingsAdminPage(__('Settings', self::$PLUGIN_SLUG), __('General Settings', self::$PLUGIN_SLUG), self::$PLUGIN_SLUG),
- new GdbcSecurityAdminPage(__('Security', self::$PLUGIN_SLUG), __('Security Settings', self::$PLUGIN_SLUG), self::$PLUGIN_SLUG),
- new GdbcWordpressAdminPage(__('WordPress', self::$PLUGIN_SLUG), __('WordPress Settings', self::$PLUGIN_SLUG), self::$PLUGIN_SLUG),
- new GdbcContactFormsAdminPage(__('Contact Forms', self::$PLUGIN_SLUG), __('Contact Forms Plugins', self::$PLUGIN_SLUG), self::$PLUGIN_SLUG),
- new GdbcMembershipAdminPage(__('Membership', self::$PLUGIN_SLUG), __('Membership Page Settings', self::$PLUGIN_SLUG), self::$PLUGIN_SLUG),
- new GdbcECommerceAdminPage(__('eCommerce', self::$PLUGIN_SLUG), __('eCommerce Page Settings', self::$PLUGIN_SLUG), self::$PLUGIN_SLUG),
- new GdbcOthersAdminPage(__('Others', self::$PLUGIN_SLUG), __('All other popular plugins settings', self::$PLUGIN_SLUG), self::$PLUGIN_SLUG),
- new GdbcNotificationsAdminPage(__('Notifications', self::$PLUGIN_SLUG), __('Notifications Settings', self::$PLUGIN_SLUG), self::$PLUGIN_SLUG),
- new GdbcExtensionsAdminPage(__('Extensions', self::$PLUGIN_SLUG), __('WPBruiser Extensions', self::$PLUGIN_SLUG), self::$PLUGIN_SLUG),
- new GdbcLicensesAdminPage(__('Licenses', self::$PLUGIN_SLUG), __('Licenses Settings', self::$PLUGIN_SLUG), self::$PLUGIN_SLUG),
- new GdbcReportsAdminPage(__('Reports', self::$PLUGIN_SLUG), __('WPBruiser - Blocked Attempts', self::$PLUGIN_SLUG), self::$PLUGIN_SLUG),
-
- );
+ // The page titles below are translated, so the list must not be built before
+ // the `init` action: calling __() earlier makes WordPress load the text domain
+ // too early and emit a _load_textdomain_just_in_time notice (WP 6.7+).
+ // Everything that consumes the list (admin_menu, admin_init,
+ // admin_enqueue_scripts) runs after init, so this is safe.
+ add_action( 'init', array( $this, 'buildAdminPagesList' ), 20 );
if(GoodByeCaptcha::isNetworkActivated())
{
@@ -55,6 +48,26 @@
}
+ public function buildAdminPagesList()
+ {
+ if(!empty($this->adminPagesList))
+ return;
+
+ $this->adminPagesList = array(
+
+ new GdbcSettingsAdminPage(__('Settings', 'goodbye-captcha'), __('General Settings', 'goodbye-captcha'), self::$PLUGIN_SLUG),
+ new GdbcSecurityAdminPage(__('Security', 'goodbye-captcha'), __('Security Settings', 'goodbye-captcha'), self::$PLUGIN_SLUG),
+ new GdbcWordpressAdminPage(__('WordPress', 'goodbye-captcha'), __('WordPress Settings', 'goodbye-captcha'), self::$PLUGIN_SLUG),
+ new GdbcContactFormsAdminPage(__('Contact Forms', 'goodbye-captcha'), __('Contact Forms Plugins', 'goodbye-captcha'), self::$PLUGIN_SLUG),
+ new GdbcMembershipAdminPage(__('Membership', 'goodbye-captcha'), __('Membership Page Settings', 'goodbye-captcha'), self::$PLUGIN_SLUG),
+ new GdbcECommerceAdminPage(__('eCommerce', 'goodbye-captcha'), __('eCommerce Page Settings', 'goodbye-captcha'), self::$PLUGIN_SLUG),
+ new GdbcOthersAdminPage(__('Others', 'goodbye-captcha'), __('All other popular plugins settings', 'goodbye-captcha'), self::$PLUGIN_SLUG),
+ new GdbcNotificationsAdminPage(__('Notifications', 'goodbye-captcha'), __('Notifications Settings', 'goodbye-captcha'), self::$PLUGIN_SLUG),
+ new GdbcReportsAdminPage(__('Reports', 'goodbye-captcha'), __('WPBruiser - Blocked Attempts', 'goodbye-captcha'), self::$PLUGIN_SLUG),
+
+ );
+ }
+
public static function getAdminRegisteredNotices()
{
if( empty(self::$adminNoticesList) )
@@ -76,7 +89,8 @@
$adminNotice = new GdbcAdminNotice( GdbcAdminNotice::USER_IP_WEB_ATTACKER_NOTICE_KEY, GdbcAdminNotice::NOTICE_TYPE_DANGER );
$noticeMessage = '<p><b>';
- $noticeMessage .= sprintf( __( "Your IP Address - %s - is reported as a Web Attacker! In order to keep <b>Block Web Attackers IPs</b> option activated you must white-list your IP Address!", GoodByeCaptcha::PLUGIN_SLUG ), esc_html( GdbcIPUtils::getClientIpAddress() ) );
+ /* translators: %s: the visitor IP address that was reported. */
+ $noticeMessage .= sprintf( __( "Your IP Address - %s - is reported as a Web Attacker! In order to keep <b>Block Web Attackers IPs</b> option activated you must white-list your IP Address!", 'goodbye-captcha'), esc_html( GdbcIPUtils::getClientIpAddress() ) );
$noticeMessage .= '</b></p>';
$adminNotice->setMessage( $noticeMessage );
@@ -92,7 +106,8 @@
$adminNotice = new GdbcAdminNotice(GdbcAdminNotice::USER_IP_PROXY_ANONYM_NOTICE_KEY, GdbcAdminNotice::NOTICE_TYPE_DANGER);
$noticeMessage = '<p><b>';
- $noticeMessage .= sprintf(__("Your IP Address - %s - is reported as a dangerous Anonymous Proxy IP! In order to keep <b>Block Anonymous Proxy IPs</b> option activated you must white-list your IP Address!", GoodByeCaptcha::PLUGIN_SLUG), esc_html(GdbcIPUtils::getClientIpAddress()));
+ /* translators: %s: the visitor IP address that was reported. */
+ $noticeMessage .= sprintf(__("Your IP Address - %s - is reported as a dangerous Anonymous Proxy IP! In order to keep <b>Block Anonymous Proxy IPs</b> option activated you must white-list your IP Address!", 'goodbye-captcha'), esc_html(GdbcIPUtils::getClientIpAddress()));
$noticeMessage .= '</b></p>';
$adminNotice->setMessage($noticeMessage);
@@ -130,11 +145,15 @@
if(null === $settingsPageUrl)
$settingsPageUrl = 'Settings';
else
- $settingsPageUrl = MchGdbcHtmlUtils::createAnchorElement(__('Settings Page', GoodByeCaptcha::PLUGIN_SLUG), array('href' => $settingsPageUrl));
+ $settingsPageUrl = MchGdbcHtmlUtils::createAnc