Skip to content

Commit

Permalink
feat: virus scan file uploads using wordfence
Browse files Browse the repository at this point in the history
  • Loading branch information
joaquimds committed Nov 1, 2023
1 parent 803ccae commit e18905f
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ web/app/languages/*
!web/app/languages/.gitkeep
web/app/cache/*
web/app/vendor
web/app/wflogs

# WordPress
web/wp
Expand All @@ -34,4 +35,4 @@ docker/mysql/data/*
# Mac OS X
.DS_Store

node_modules
node_modules
62 changes: 62 additions & 0 deletions web/app/themes/awasqa/src/gravity-forms.php
Original file line number Diff line number Diff line change
Expand Up @@ -443,3 +443,65 @@ function ($post_id, $feed, $entry, $form) {
$form['fields'][] = new \GF_Field_CAPTCHA();
return $form;
});

function scanFile($file, $patterns)
{
$fh = fopen($file['tmp_name'], 'r');
while (!feof($fh)) {
$data = fread($fh, 1 * 1024 * 1024);
foreach ($patterns['rules'] as $rule) {
if (preg_match('/(' . $rule[2] . ')/iS', $data, $matches, PREG_OFFSET_CAPTURE)) {
return false;
}
}
$badStringFound = false;
if (strpos($data, $patterns['badstrings'][0]) !== false) {
for ($i = 1; $i < sizeof($patterns['badstrings']); $i++) {
if (\wfUtils::strpos($data, $patterns['badstrings'][$i]) !== false) {
$badStringFound = $patterns['badstrings'][$i];
break;
}
}
}
if ($badStringFound) {
return false;
}
}
return true;
}

add_filter('gform_validation', function ($validation_result) {
$form = $validation_result['form'];

$files = $_FILES ?? [];
$files = array_filter($files, function ($file) {
return (bool) ($file['tmp_name'] ?? null);
});

// get virus patterns from WordFence
$scan_engine = new \wfScanEngine();
$wp_version = \wfUtils::getWPVersion();
$apiKey = \wfConfig::get('apiKey');
$scanner = new \wordfenceScanner($apiKey, $wp_version, ABSPATH, $scan_engine);
$refl = new \ReflectionObject($scanner);
$prop = $refl->getProperty('patterns');
$prop->setAccessible(true);
$patterns = $prop->getValue($scanner);

foreach ($files as $file) {
$result = scanFile($file, $patterns);
if (!$result) {
$validation_result['is_valid'] = false;
@unlink($file['tmp_name']);
}
}

if (!$validation_result['is_valid']) {
wp_redirect($_SERVER['REQUEST_URI']);
exit(0);
}

//Assign modified $form object back to the validation result
$validation_result['form'] = $form;
return $validation_result;
});

0 comments on commit e18905f

Please sign in to comment.