Prevent your WordPress site from being hacked using scheduled events and regular expressions. Or die trying.

if you run a WordPress site, you should know sometimes in some ways hackers are able to inject malicious code in it.

Around the web you can find a lot of tutorials to secure your WordPress against hackers, but unluckily sometime it happens.

In most cases, some malicious code is injected in your template files, and I have to say it’s very easy to remove it once you know the bare basics of a WordPress theme.

The real problem is the time. Since we can’t refresh our WP page or hunt for malicious injections with our FTP editor every hour, sometimes it can take hours for us to realize the site has been hacked.

When it happens to me, in most of cases I receive an email from a reader saying “I got a virus from your blog”. What a shame!!

So I decided to create a bot to do the dirty work for me. And I am showing you how easy it is.

In this example I will show you how to reader header.php file every hour and send an mail if an iframe has been found.

Obviously the example can be expanded in a lot of ways (including more injections than a simple iframe, or directly removing the injected code). I will explain some interesting ways later in this post.

Now, let’s see what I added in my functions.php file:

if(!wp_next_scheduled("scheduled_event")) {
	wp_schedule_event(time(),"hourly","scheduled_event");
}

add_action("scheduled_event","send_mail_if_hacked"); 
function send_mail_if_hacked() {
	$the_header = file_get_contents(get_template_directory()."/header.php");
	$injections = preg_match_all("/()/",$the_header,$matches);
	if($injections){
		wp_mail("info@emanueleferonato.com","alert from the blog",print_r($matches,true));
	}
}

First, just a couple of lines of boring theory: in WordPress you can schedule events to be executed every hour, every day or twice a day. I will use such feature to code my bot.

Line 1: wp_next_scheduled function will return false if the event called scheduled event isn’t scheduled.

Line 2: wp_scheduled_event schedules a hook which will be executed by the WordPress actions core on a specific interval, specified by you. The action will trigger when someone visits your WordPress site, if the scheduled time has passed. That is, I am setting scheduled_event to be triggered every hour. With almost 7,000 visitors/day I am quite sure the blog is visited by at least one person for each hour. The alternative is to use daily or twicedaily rather than hourly.

Line 5: Time to add an action to scheduled event event: setting it to send_mail_if_hacked will execute a function called send_mail_if_hacked every hour.

Line 6: This is where the real bot begis

Line 7: Reading header.php file

Line 8: Looking for iframes in the header using regular expressions

Line 9: … and if I found an iframe…

Line 10: … I send an alert email.

I placed an iframe in the header and this is the mail I got:

Array
(
    [0] => Array
        (
            [0] => 
        )

    [1] => Array
        (
            [0] => 
        )

)

Not that clear, but it reported me exactly the iframe I injected.

This, while being a really simple code, is open to a lot of improvements. The most interesting I imagined is having a copy of the theme in a safe folder, then check for each main theme file to be exactly the same of the safe copy, rewriting it if not. This is also a dirty trick if you don’t want to deal with regular expressions.

How would you improve the code?

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers