Today's article is definitely on the amusing side, although hopefully it will make for an interesting learning opportunity. Earlier this week I was clearing out spam on my blog and found a comment that looked like the spammer's template file. The comment contained a number of short entries like this:
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
Sample spam template (Image Credit: Jeff Hicks)
The poor English aside, I thought it was kind of funny. First off, it is clear that whatever code he (making an assumption, sorry) was using failed to properly run. Then I thought that I could use this text and do the same thing in PowerShell. It is pretty clear to me that to create a proper spam comment, I need to select a choice from each option enclosed in curly braces. So let's do that. Let's build some spam with PowerShell. I'll use the text file from above.
$file = "C:\scripts\Spam3.txt" $in = Get-Content -Path $file
The trickiest part, at least for me, was coming up with a regular expression pattern to select everything in the curly braces. Eventually I came up with this:
[regex]$rx = "\{(\w+(\S+|\s+))+\}"
To start with, I'll test with a single line of text.
$m = $rx.matches($in[2])
Which gives me these matches:
My spam matches (Image Credit: Jeff Hicks)
I'll focus on the first match. I don't need the {} characters so I can replace them with empty strings and then split what remains on the | character.
$choices = $m[0].value.Replace("{","").Replace("}","") -split "\|"
This gives me an array of choices which I can select with Get-Random.
$choice = $choices | get-random
With this, I can use the replace method to replace the matching value that is, the text with the curly braces, with my randomly selected choice.
$in[2].Replace($m[0].value,$choice)
Inserting the replacement (Image Credit: Jeff Hicks)
I can repeat this process for the other values. Here's how I might do this for a single line:
$line = $in[2] foreach ($item in $m) { $choices = $item.value.Replace("{","").Replace("}","") -split "\|" $choice = $choices | get-random $line = $line.Replace($item.value,$choice) } $line
The complete line (Image Credit: Jeff Hicks)
I never promised elegant poetry.
Now that I have the technique, I can apply it to the entire file looping through each line.
$spam = Foreach ($line in $in) { $m = $rx.matches($line) if ($m) { foreach ($item in $m) { $choices = $item.value.Replace("{","").Replace("}","") -split "\|" $choice = $choices | get-random $line = $line.Replace($item.value,$choice) } } #write the result $line }
And here is the glorious, delicious spammy result:
PowerShell generated spam! (Image Credit: Jeff Hicks)
Yes, this is absolutely silly and borderline ridiculous. But this serves as a nice tool for learning about regular expressions, replacements and splitting. If you want some spam samples to play with you can download a zip file here.
Have a great weekend.