winter scripting games: events 7 and 8

This post is just about my time with PowerShell for the 2007 Winter Scripting Games. If you have no interest, I certainly won’t be upset if you skip this post. I’m posting only because this will mark my first exposure to PowerShell.

I’ve found my creativity stimulated quite a lot by these games. Also, since I’ve started doing these games, I think this group of 4 events were the easiest so far. The first few might have been easy, but they required more effort since those were my first looks at PowerShell at all. By the way, MoW is also posting his responses and I must say, his code is far more elegant and experienced than mine. It’s awesome!

Beginner Event 7 involves taking a bit of code that throws an error, and manage that error. First, prevent the ugly error from displaying to the user, and then also handle the error later. This is a good Beginner topic and one of those things that often gets overlooked but is very necessary for good scripting and coding: error handling.

$error.clear()
$erroractionpreference = “SilentlyContinue”

######## START UNCHANGED CODE #########

$a = 5
$b = 6
$c = “seven”
$d = 8

$x = $a + $b
$x = $x + $c
$x = $x + $d

$x

######## END UNCHANGED CODE #########

if ($error.Count -gt 0)
{ Write-Host “An error has occurred.” }

# This would display the errors, but not required
# for ($i=0;$i -lt $error.Count;$i++)
# { $error[$i] }

Beginner Event 8 is a “simple” game of jacks. This is another excellent Beginner event in that it focuses on something rather basic but necessary: nested loops. This is simply about thinking through the logic of the problem, and then setting up counters and loops to achieve the answer.

$jacksingame = 10
$i = 1

do {
$jacks = 10
$bounces = 0

do { $bounces++;$bouncestotal++;$jacks -= ($i * 1); } until ($jacks -le 0)

$jackspickedup += 10
$i++
} until ($i -gt $jacksingame)

Write-host “Total jacks: $jackspickedup”
Write-host “Total pick-ups: $bouncestotal”

Advanced Event 7 wants a text file read, encrypted, and then also optionally decrypted using arguments when starting the script. Since I am still smarting from the rather nasty Beginner challenge to convert text to hex and back to text again, I decided to yoink that code, drop the hex part, and use the decimal values. Then increment the values by one before converting back into ASCII. Instant, if weak, encryption! (I also thought about using a simple cipher substitution or ROT13 Switch, but decided this was easier.)

if ($args[0] -eq “e”) {

$input = [string]::join([environment]::newline, (get-content -path Alice2.txt))
for($i=0;$i -lt $input.length;$i++)
{
[int[]]$a = $a + [int] $input[$i]
$a[$i] += 1
$e = $e + [char] $a[$i]
}

$encodedfile = New-Item -type file “Encoded.txt” -Force
Set-Content Encoded.txt $e

} elseif ($args[0] -eq “d”) {

if (Test-Path Encoded.txt) {

$input2 = [string]::join([environment]::newline, (get-content -path Encoded.txt))
for($i=0;$i -lt $input2.length;$i++)
{
[int[]]$x = $x + [int] $input2[$i]
$x[$i] -= 1
$y = $y + [char] $x[$i]
}

$y

} else { Write-Host “Encoded.txt not found. You probably need to use argument ‘e’ first to encode a file.”}

} else { Write-Host “Please provide an argument ‘e’ (to encode) or ‘d’ (to decode) ” }

Advanced Event 8 provided small pieces of code with the question: “Is this a valid piece of code?” Not too hard and kinda fun! I won’t post my answers here, since there’s nothing really novel in the answers.

oh to be on the same page

“One whose upper and lower ranks have the same desires will be victorious.” The Art of War, Chapter 3: Planning the Attack

It is frustrating (both for techs and for management) when they cannot agree on their goals for security. Unless they can agree, they won’t succeed.

sobering security

I saw this fly past on the Security Focus security-basics mailing list from an anonymous poster. I simply wanted to capture the moment here and let it sink it.

I work for one of the biggest universities in the US and they barely care about security, so I think you may be in for an up hill battle. I’ve been trying for years without any luck, the same story comes back from managment over and over, “we never had any security problems so why should we invest money to prevent them” and thats a direct quote from more than one person in managment.

on remarkable customer service

It seems that whenever Joel posts a significant new article on his site, I end up copying the link from here, almost like a little RSS/mirror service. I think it’s because this guy just “gets it.” I’ve yet to see bad advice from him and everything he says is majorly refreshing and awesome. I could gladly work in a company like that, even adjusting my career path for a company like the one he runs.

Anyway, I’m gushing, which is not something I usually do. Joel talks this time about remarkable Customer Service.

winter scripting games: events 5 and 6

This post is just about my time with PowerShell for the 2007 Winter Scripting Games. If you have no interest, I certainly won’t be upset if you skip this post. I’m posting only because this will mark my first exposure to PowerShell.

Beginner Event 5 can be done rather easily in vbscript. I needed to convert a string into a hexadecimal array and then back into a string. I was able to make the first conversion, but couldn’t work out how to go backwards. I actually couldn’t get from hex to ASCII code, but I could easily get the rest of the way back to a real string of readable characters. Oh well.

$r = “It was the best of times…you know the rest.”
$a = $r.ToCharArray()
$h = @()
$v = @()

for ($i=0;$i -le $a.length;$i++){
$x = [int][char]$a[$i]
$h += “{0:X}” -f $x
}
$h

for ($i=0;$i -le $h.length;$i++){

# $y = [byte]$h[$i]
# $y = “{0:D}” -f $h[$i]
# $y = [Convert]::ToString($h[$i],16)
#this is the last part $y = [char][int]$h[$i]
$y

}

Beginner Event 6 just wanted some key words to be filled into an incomplete script found at the link above. I think my answers were correct…and if not, the program did run as expected anyway.

1. -eq
2. }
3. foreach
4. continue (although this can just be left blank too)
5. While
6. Switch

Advanced Event 5 wanted an Access database opened, then some math computations made, namely the min, max, mode, median, and mean values. Now, this can be very easy in other languages, but for some reason either PowerShell does not have these helpers built in yet, or I wasn’t able to find how to do it properly. Either way, here it is. If you really delve into my code, you can see that by the time I did the median, I was using better techniques than I had been using earlier. If I wanted to, I could rewrite the max and min sections much smaller now, I think.

$adOpenStatic = 3
$adLockOptimistic = 3
$objConnection = New-Object -comobject ADODB.Connection
$objRecordset = New-Object -comobject ADODB.Recordset
$objConnection.Open(“Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =
/scores.mdb”)
$objRecordset.Open(“Select * from Results”,
$objConnection,$adOpenStatic,$adLockOptimistic)

####### START MEAN #######
$objRecordset.MoveFirst()
$i,$avg = 0

do {
$avg += $objRecordset.Fields.Item(“Score”).Value
$i++;$objRecordset.MoveNext()}
until ($objRecordset.EOF -eq $True)

$avg = [math]::truncate($avg / $i)

####### START MIN #######
$objRecordset.MoveFirst()
$max = 0

do {
if ($objRecordset.Fields.Item(“Score”).Value -gt $max)
{ $max = $objRecordset.Fields.Item(“Score”).Value}
else { }
$objRecordset.MoveNext()}
until ($objRecordset.EOF -eq $True)

####### START MAX #######
$objRecordset.MoveFirst()
$min = $max

do {
if ($objRecordset.Fields.Item(“Score”).Value -lt $min)
{ $min = $objRecordset.Fields.Item(“Score”).Value}
else { }
$objRecordset.MoveNext()}
until ($objRecordset.EOF -eq $True)

####### START MODE #######
[int[]]$modearray = @()

for ($n=0;$n -le $max;$n++)
{$modearray += 0
}
$objRecordset.MoveFirst()

do {
$n = $objRecordset.Fields.Item(“Score”).Value
$modearray[$n] = $modearray[$n] + 1
$objRecordset.MoveNext()}
until ($objRecordset.EOF -eq $True)

$modemax = 0

for ($n=0;$n -le $modearray.length;$n++)
{
if ($modearray[$n] -gt $modemax)
{ $mode = $n; $modemax = $modearray[$n]}
else { }
}

####### START MEDIAN #######
[int[]]$medianarray = @()

for ($n=0;$n -lt $i;$n++)
{$medianarray += 0}

$n = 0
$objRecordset.MoveFirst()

do {
$medianarray[$n] = $objRecordset.Fields.Item(“Score”).Value
$n++;$objRecordset.MoveNext()}
until ($objRecordset.EOF -eq $True)

$medianarray = $medianarray | sort
$median = $medianarray[$medianarray.length/2]

####### START OUTPUT #######
Write-host “Mean: $avg”
Write-host “Mode: $mode”
Write-host “Median: $median”
Write-Host “Highest score: $max”
Write-Host “Lowest score: $min”

$objRecordset.Close()
$objConnection.Close()

Advanced Event 6 wanted a nicely formatted 75-column block of text. I really didn’t know what to do here.

winter scripting games: events 3 and 4

This post is just about my time with PowerShell for the 2007 Winter Scripting Games. If you have no interest, I certainly won’t be upset if you skip this post. I’m posting only because this will mark my first exposure to PowerShell.

Beginner Event 3 was a pretty easy exercise in picking out what item in a series is not like the others. I’m sure this can be done in less code, but this made the quickest sense to me with the least effort.

$a1 = “monday”, “MONDAY”, “monday”
$a2 = “TUESDAY”, “tuesday”, “tuesday”
$a3 = “WEDNESDAY”, “wednesday”, “wednesday”
$a4 = “thursday”, “thursday”, “THURSDAY”
$a5 = “friday”, “FRIDAY”, “friday”

$x1a = [String]::Compare($a1[0],$a1[1],$False)
$x1b = [String]::Compare($a1[1],$a1[2],$False)
$x1c = [String]::Compare($a1[0],$a1[2],$False)
if ($x1a -eq 0){“a1: third”}
elseif ($x2b -eq 0){“a1: first”}
else{“a1: second”}

$x2a = [String]::Compare($a2[0],$a2[1],$False)
$x2b = [String]::Compare($a2[1],$a2[2],$False)
$x2c = [String]::Compare($a2[0],$a2[2],$False)
if ($x2a -eq 0){“a2: third”}
elseif ($x2b -eq 0){“a2: first”}
else{“a2: second”}

$x3a = [String]::Compare($a3[0],$a3[1],$False)
$x3b = [String]::Compare($a3[1],$a3[2],$False)
$x3c = [String]::Compare($a3[0],$a3[2],$False)
if ($x3a -eq 0){“a3: third”}
elseif ($x3b -eq 0){“a3: first”}
else{“a3: second”}

$x4a = [String]::Compare($a4[0],$a4[1],$False)
$x4b = [String]::Compare($a4[1],$a4[2],$False)
$x4c = [String]::Compare($a4[0],$a4[2],$False)
if ($x4a -eq 0){“a4: third”}
elseif ($x4b -eq 0){“a4: first”}
else{“a4: second”}

$x5a = [String]::Compare($a5[0],$a5[1],$False)
$x5b = [String]::Compare($a5[1],$a5[2],$False)
$x5c = [String]::Compare($a5[0],$a5[2],$False)
if ($x5a -eq 0){“a5: third”}
elseif ($x5b -eq 0){“a5: first”}
else{“a5: second”}

Beginner Event 4 just wanted a nicely formatted list of running services.

get-service | where-object {$_.status-eq “running”} | format-table
-property DisplayName, Status -auto

Advanced Event 3 involved a program to make change in various demoninations. Not too bad, and I was pretty happy with my initial formating of the input.

$a = Read-Host “Enter your dollars”
$a = $a -replace(“\$”,””)
$a = $a -replace(“\.”,””)
$a = 5000 – $a
$change = $a / 100
$change = “{0:N2}” -f $change

$tens = $a / 1000
$tens = [math]::truncate($tens)
$a = $a – $tens * 1000
$fives = $a / 500
$fives = [math]::truncate($fives)
$a = $a – $fives * 500
$ones = $a / 100
$ones = [math]::truncate($ones)
$a = $a – $ones * 100
$quarters = $a / 25
$quarters = [math]::truncate($quarters)
$a = $a – $quarters * 25
$dimes = $a / 10
$dimes = [math]::truncate($dimes)
$a = $a – $dimes * 10
$nickels = $a / 5
$nickels = [math]::truncate($nickels)
$a = $a – $nickels * 5
$pennies = $a / 1
$pennies = [math]::truncate($pennies)

Write-Host “Change returned: $change”
Write-Host “Tens: $tens”
Write-Host “Fives: $fives”
Write-Host “Ones: $ones”
Write-Host “Quarters: $quarters”
Write-Host “Dimes: $dimes”
Write-Host “Nickels: $nickels”
Write-Host “Pennies: $pennies”

Advanced Event 4 was also fairly easy and fun in attempting to map out the various chinese new year animals. I did it a slightly harder way than they gave in their answer.

$a = Read-Host “Enter your year”
$a = $a -1900
$b = $a / 12
$b = [math]::truncate($b)
$b = $b * 12
$a = $a – $b

switch($a)
{
“0”{$answer=”Rat”}
“1”{$answer=”Ox”}
“2”{$answer=”Tiger”}
“3”{$answer=”Rabbit”}
“4”{$answer=”Dragon”}
“5”{$answer=”Snake”}
“6”{$answer=”Horse”}
“7”{$answer=”Goat”}
“8”{$answer=”Monkey”}
“9”{$answer=”Rooster”}
“10”{$answer=”Dog”}
“11”{$answer=”Pig”}
}
Write-Host $answer

the problem with fuzzing as a security posture

Mike Rothman mentioned fuzzing today which prompted me to post a thought of my own. Fuzzing is not a security posture.

Fuzzing pretty much means throwing all sorts of “things” at an application either in input fields or network ports, and so on. This is something any dummy can run. But fuzzing results are an order of magnitude more difficult to determine if an issue is really a vulnerability. This isn’t the same as looking at an open port reported by Nessus or a missing patch reported by MBSA. Not only that, but fuzzing is not as fast as even an nmap scan on a network. The setup and execution are longer.

Once you get the results, oftimes you will need some memory management skills to determine if a bug will actually pop the stack properly, and then craft an exploit to prove the issue. Otherwise you might just have found some lame bug that closes the application (DoS), or less. If we raised the alarm on every issue a fuzzing found, we wouldn’t be having “Month of X Bugs,” but rather multiple “Years of X Bugs.” Check out the comments on some of those posts to see the contention some people make on whether a fuzzed result is truly exploitable or not.

Fuzzing is not terribly difficult. Interpreting the results takes an expert, unlike other scanning methods. Fuzzing won’t be a part of most IT shops or even developer circles for a long time until they start learning what happens in the OS/memory and not just doing their interpreted coding to do task A and move item B. Even QA will be hard-pressed to be given training and time to perform real fuzzing in all but the most critical and rich organizations.

comment spam

Of course it is only a matter of time, but I have slowly seen a few comment spam posts on my blog here. This is an itneresting way to see the growth of comment spam and make a few observations.

First, I’ve only seen comment spam on just a few of my posts, and typically over a week I’ll get about 10 comments on just those posts, no others. Odd, especially since two of them even pre-date this URL and site (posts ported over from my older site). I would almost think I am just getting collateral damage from a link to my site from somewhere else, but no one links to those posts that I can see. I might have to analyze my logs a bit deeper just out of curiosity. They are also almost all in chunks and only yesterday did they start getting past the junk comment filters in MovableType.

1/09 – 1/21 spam came to html in email from 12/2006
1/22 spam came to malware analysis: free video codec from 11/2006
1/31 – 2/07 spam came to illustrated guide to cryptography from 6/2006
2/02 – today spam came to remoteregistry issues from 8/2004
2/13 – today spam came to turn off ssdp and upnp from 8/2004

Second, I thought about changing their spam comments to something like, “My IP is blah and I tried to post comment spam.” But that itself is spammy and won’t scale. Or post regularly about my spammers, but again that is spammy itself and likely are just “innocent” bots.

I think I’ll just keep deleting them, but I am happy with MTs ability to score comments and hold them Unpublished if there is too much HTML in the comments. Also, there are limits to the length of certain fields which no legitimate poster should bump against, but spammers might hit. Still, some do get through, though. I also like that I can subscribe to an RSS comments feed which will show me published and unpublished comments readily and I can catch these things.

scripting games day 1 and 2: feet are wet

This post is just about my time with PowerShell for the 2007 Winter Scripting Games. If you have no interest, I certainly won’t be upset if you skip this post. I’m posting only because this will mark my first exposure to PowerShell.

The games have begun. Event 1 in the Beginner’s section basically wanted the creation of a message box (dialogue box, pop up box, et al) that changed a few attributes and did something based on the return behavior. My code looked like this:

[System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
$answer = [System.Windows.Forms.MessageBox]::Show(“Do you want to continue?”, “Continue Processing”, “YesNo”, “Question”)
if ($answer -eq “yes”)
{echo “Yes – Processing will continue…”}
else
{echo “No – Processing stopped”}

Nothing really special there. The only bad part is that I wasn’t able to bring the pop up box to the front, although some Googling turned up that this is a known issue that can be solved with vbscript.

Beginner Event 2 was a series of questions, each scored independently. In one column were ten classes, and in a second column were ten properties. The question is to match the classes with their properties. Not so bad. While I could eyeball this list and likely get an easy 8 of 10 correct, a couple would have required guesses. However, there is an easier way to do this:

get-wmiobject [class] | get-member

Replace [class] with the class name and look through the list for the matching terms.

Now, because of my success in the Beginner Events, I thought I would try my hand at the Advanced Events, which are definitely more up my alley as long as they stay in the “logic” arena as opposed to knowing my way around all the various obscure commands and methods and objects in PowerShell that I don’t know yet.

Event A1 wanted to convert from Roman Numerals to regular numbers. This actually proved more interesting than I thought it would be, and my eventual program, while satisfying the requirements, would not hold up to invalid input, error checking, or additional roman numerals above M.

$r = Read-Host “Please enter a Roman numeral:”
$a1 = $r.ToCharArray()
$a2 = @()
$value = 0

for ($i=0;$i -le $a1.length;$i++){
Switch ($a1[$i]){
“M” {$a2 += 1000}
“D” {$a2 += 500}
“C” {$a2 += 100}
“L” {$a2 += 50}
“X” {$a2 += 10}
“V” {$a2 += 5}
“I” {$a2 += 1}
}
}

for ($i=0;$i -le $a2.length;$i++){
$v1 = $a2[$i-1]
$v2 = $a2[$i]
$v3 = $a2[$i+1]

if ($flip -eq 1){$value += ($v2 – $a2[$i-1]);$flip=0}
elseif ($v2 -ge $v3){$value += $v2}
else {$flip=1}
}

Write-Host $value

Event A2 was simpler even though I had more trouble finding the information I needed (syntax, really). Find the number that when multiplied by 3 would give the smallest answer that consists of nothing but 4s. The answer is 148, and while I could create a script to find this by iterating through every number by multiplying it by 3 and check if the answer is all 4s, or even start with 10 4s and divide them by 3 all the way down to the lowest, but I eventually decided I wanted to just build a string of growing 4s and check each one to see if it was evenly divisible. Sadly, when I submitted my entry I made the mistake and echoed out “444” instead of the needed “148.” D’oh! I was too excited about figuring this one out!

$a = @()
do {
$a += 4
$b = [String]::join(“”,$a)
$m = $b % 3
if ($m -eq 0){
$x = $b / 3
write-Host $x}
}
until ($m -eq 0)

Not too shabby there, I hope! So far, that is very encouraging and my goal has expanded to not just completing the Beginner section, but to complete at least half of the points from the Advanced.

things get lost? no way!

So, the FBI is still losing laptops with sensitive information. What I really hate about this sensationalist news is things have been lost or stolen for decades upon decades. We have laptops and mobile devices and they will get lost. That’s fact and that’s going to be absolute. This is a classic example of a security incident that will happen. That means the real story here is about damage mitigation, disk encryption, and data management.

winter scripting games have begun!

“Thus in war, I have heard tell of a foolish haste, but I have yet to see a case of cleverly dragging on the hostilities. -The Art of War, Chapter 2: On Waging Battle

I take this to mean, do. Don’t wait around and throw sticks at information security. Do things. Get to work. Perform some action.

They have begun! I started in on the Beginner challenges and finished the first two rather quickly. Just for my own benefit (ego) I’ll post my own answers here after the deadlines. If nothing else, it will be just for me to document my own code and dive into PowerShell.

Since I did the two first beginner events, I thought I’d try out the Advanced ones. These are a lot more complicated for me as a beginner, but at least I know the logic and can think through things like how to get from problem A to solution B. Now I just have to look up each little step like getting input into an array, any nuances with variable types (if any) that PowerShell may have, proper syntax for ForEach loops and Switches, and basically working with arrays. I also need to see how it performs with null values or the ends of arrays. Thankfully, the PowerShell syntax so far seems very familiar and standard. I think I might be fine with a couple of the Advanced problems.

being a guru with new things

Just a quick word of advice, both to anyone reading and myself as well. If you find yourself at a point in your career where you have some good experience/knowledge and some free time to spend either in your job or just at home when geeking out, keep your eyes open for new things and grab onto them with both hands. Look for something new, learn it, and become one of the early gurus. Things like PCI knowledge, PowerShell, wireless technologies, FDE, Python, AJAX, VMWare, and many other things I have had the chance to see kinda appear and grow in my time in IT. And those people who latched on early and became gurus definitely end up being go-to guys either in their own company, the community, and possibly beyond. People you know normally suddenly are the “first” to really offer good insight and knowledge get noticed for that.

Just a note to look for in the future as technologies, languages, and practices continue to move forward. This might not mean you can become a highly paid consultant or start your own business, but at least keeping the above in mind might really grow you professionally and get you noticed in the community.

why do I stay updated on black hat techniques?

“Therefore, the business of waging war lies in carefully studying the designs of the enemy.” -The Art of War, The Nine Kinds of Terrain

Carefully studying the enemy motivations and plans and mindset but also knowing their machinations, technology, techniques, and habits. Every now and then I hear about how evil it is to have “hacking” books that shouldn’t be teaching all the techniques and steps. I don’t buy that and think that we need knowledge and study not only of security, but of insecurity so that we can assess risk and protections properly.

Another aspect of this quote is carefully studying a war in progress so that you can move intelligently. If you have an attacker in your network doing something bad, carefully study them so you know what they want, what defenses they may have already dug in, and be best able to defeat them. Just like a chess game that has developed from the start game into one side moving into an offensive position. Play as many steps ahead as your time and brain allow.

microsoft scripting games 2007

I work in a Windows environment. I’ll likely work with Windows in some form or other for my entire career, unless I get completely sucked into networking. And yet I don’t know Windows scripting. Oh the travesty! Seriously, I like programming, but I’ve never freakin’ properly learned Windows scripting. I think I will be taking a good hard look at the Microsoft Scripting Games 2007 to see how things work and maybe tackle a few of the easier challenges and get my feet wet. Really, I don’t need to be some guru that uses scripting day in and day out. You can get by with things like maintenence scripting quite well with just occassionally challenging oneself to script a little bit.

And I like challenges like these Games. There are some ways to learn in this field of IT security, support, and networking. One way is troubleshooting fires that are burning. You can only learn so much theory from other people, books, and mentors. But you have to put it into practice to really get it in this area (hence my occassional disdain for analysts, IT journalists, and people who jus repeat “best practices” ad nauseum). I particularly love challenges, puzzles, and friendly competitions that run the gamut of amazingly fun to very competitive to real-life-mirroring scenarios.

In fact, in the sidebar menu way towards the bottom I have links to various “hacking” and other challenges mixed into the “cons/training” section. I have been putting off moving the actual challenge type items down to the new challenges section. I love those things, and even if I’m late to the party or don’t know the answers, reading the practical solutions offers some excellent insight.

Anyway, I’ll see how my schedule looks and give the Microsoft Scripting Games a try my hands at it.

Someday, I may actually post my answers to various challenges past and present on either this blog, or more likely on my wiki. I find that while reading is great theory, and hands-on is great experience, being able to regurgitate the steps and lessons on virtual paper for others to understand is the last step. When you can teach someone something, you reinforce your learning of it, even if the audience is non-existent and you’re just recording it down in a place no one else will look, or describing it to a loved one who really doesn’t care but is a willing sounding board.

Some *real* quick links from a Google search:
Windows PowerShell
Getting started (vbscript)
PowerShell blog and links
PowerShell FAQ