Tuesday, June 14, 2011

Epidose #149: Tiiiiime is on my file...

Tim checks the clock

This week we had a tough time coming up with episode ideas. We combed the internet looking for ideas and we finally came across this idea. And wouldn't you know, it just so happend that I actually needed to use this bit of fu this week.

What I wanted to know is how long how many seconds (or minutes) had passed since any file in a given directory had been modified. Unfortunately, the cmd.exe version of this command is big ol script and looks something like this, so we'll have to stick with the PowerShell version.

First, let's find the most recently modified file:

PS C:\> ls | ? { !$_.PSIsContainer } | sort LastWriteTime -desc | select -f 1

Directory: C:\

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 4/7/2011 1:43 PM 2880 myfile.txt


We start off by getting a directory listing by using Get-ChildItem. The results are piped into the Where-Object cmdlet to filter for objects that aren't containers, which leaves files. We then sort the objects by the LastWriteTime in descending order. Finally, we select the first object.

To get the date difference all we need to do is take LastWriteTime property of our object and subtract it from the current time. The verbose version of the command looks like this:

PS C:\> (Get-Date) - (Get-ChildItem | Where-Object { -not $_.PSIsContainer } |
Sort-Object -Property LastWriteTime -Descending | Select-Object -First 1).LastWriteTime


Days : 66
Hours : 10
Minutes : 26
Seconds : 34
Milliseconds : 623
Ticks : 57399946235000
TotalDays : 66.4351229571759
TotalHours : 1594.44295097222
TotalMinutes : 95666.5770583333
TotalSeconds : 5739994.6235
TotalMilliseconds : 5739994623.5


This is very similar to our last command, except for the subtraction and the output of the difference.

The command is a bit long, but we can shorten it using aliases, positional parameters, and shortened parameter names.

PS C:\> (Get-Date) - (ls | ? { !$_.PSIsContainer } | sort LastWriteTime -desc | select -f 1).LastWriteTime


If we just want the total number of seconds, we can get that too.

PS C:\> ((Get-Date) - (ls | ? { !$_.PSIsContainer } | sort LastWriteTime -desc | select -f 1).LastWriteTime).TotalSeconds

5739994.6235


So we have the most recent time, but what if we want the file name too? We can get the name of the file using a slightly different approach by adding a new property to the object:

PS C:\> (ls | ? { !$_.PSIsContainer } | sort LastWriteTime -desc | select -f 1) |
select name, @{Name='SecondsSinceMod';Expression={((Get-Date) - $_.LastWriteTime).TotalSeconds}}


Name SecondsSinceMod
---- ---------------
myfile.txt 5740999.9526015


The Select-Object cmdlet is used to select the Name and create a new property, SecondsSinceMod. A hashtable is used to create these properties, and we need to provide the name and an expression (value). The name is SecondsSinceMod and the Expression is what we did earlier.

This episode is quick, and easy. Oh, time, time, time is on my side...

Hal checks out

Well, personally, I can't get no satisfaction this week. If I restrict myself to the rules we set ourselves for the blog, there doesn't actually seem to be a general solution for this problem that works across all Unix platforms without resorting to a higher-level scripting language like Perl.

We've already covered an idiom for figuring out the most recently modified file in a directory, namely "ls -t | head -1". But the problem is getting ls to report out the timestamp on the file in seconds. The GNU version of ls actually has a (very non-standard) "--time-style" option for specifying a time output format. We can leverage this to solve the problem:

$ echo $(( $(date +%s) - $(ls -lt --time-style=+%s | awk 'NR == 2 {print $6}') ))
48106

To understand what's going on here, it helps to break things down into pieces. First we grab the output of "date +%s", which gives us the current time in Unix "epoch time" format (seconds since Jan 1, 1970). Then we use "ls -lt ..." to output the contents of the current directory sorted by last modified time, using "--time-style" to output the timestamp in epoch time format. This gets piped into awk, which prints out the time stamp field from the second line of output (the first line being a header from "ls -l"). All of that is wrapped up in a "echo $(( ... - ... )) expression which prints out the difference between the current time and the timestamp on the most recently modified file-- i.e., the number of seconds since that file was changed.

Another way of getting the mtime for a file in epoch time format is with the stat command-- at least if you're on Linux or BSD (Solaris doesn't seem to have implemented a stat command, for example). However, the option for specifying epoch time format is different depending whether you're using the Linux or BSD version of the command. The Linux version is "stat -c %Y <filename>", while BSD is "stat -f %m <filename>".

So a BSD solution for our challenge would be:

$ echo $(( $(date +%s) - $(stat -f %m $(ls -t | head -1)) ))
3423825

In this case we use our "ls -t | head -1" idiom to get the file name of the most recently modified file. That file name then becomes the argument to our stat command, which gives us the epoch time stamp for that file. We then use this value to compute the difference from the current time, just as we did in the last example.

In summary then: this challenge is solvable on Linux or any system that happens to have the GNU ls command installed. And for BSD, there's an option using the stat command. That's pretty decent coverage, but not a completely portable solution. And that's really sort of annoying.

I guess Tim gets one of his rare "wins" this week. Well played, sir. Well played!

Tuesday, June 7, 2011

Episode #148: Draggin' the Line

Hal is making a blog the old, hard way:

Almost 150 Episodes into this little blog experiment, and it's no secret that new ideas are getting hard to find. But like Tommy says, you've got to be "taking and giving... day by day." This week, I'm taking a couple of ideas from commandlinefu for deleting specific lines from a file.

First up, deleting a specific line by line number. DaveQB suggested a fairly tortured bit of shell code for removing a specific line from a file, mentioning that he used it to remove SSH keys from his known_hosts file when the remote host's key had changed. While another poster pointed out that you can just use "ssh-keygen -R <hostname>", this of course only works for known_hosts files. What if we wanted a solution that works more generally?

The canonical answer (which many folks on the thread pointed out) is to use sed:

sed -i.bak 3d ~/.ssh/known_hosts

The main part of the command here is the "3d". The leading number is treated as an "address", which is really just sed's fancy way of saying "line number". When you get to the right line number, the command that comes after the number is executed. In this case, that's the "d" command to simply delete the line.

Now normally sed would just emit the modified file to the standard output, but the "-i" flag means "in place" editing. In other words, the original file is replaced with the modified version. I'm always a little skittish with in place editing and make sure I always add an argument after the "-i". This causes a copy of the original file to be saved with the extension you specify. In this case I'll end up with a known_hosts and a known_hosts.bak file in my ~/.ssh directory.

But it's fairly rare that you actually know the number of the line you want to delete from the file. More likely there are lines matching a specific pattern that you want to delete. For example, I could purge all [t]csh users from my password file:

# grep -v 'csh$' /etc/passwd >/etc/passwd.new
# cp /etc/passwd /etc/passwd.bak
# mv /etc/passwd.new /etc/passwd

Or we could do that in one command with sed and some more in place editing action:

# sed -i.bak /csh$/d /etc/passwd

Here instead of matching a specific line number we're matching a regular expression and deleting every line that matchines.

But what if you didn't want to delete every single matching line? User flatcap suggested a sed-based approach for removing only the first matching line:

# sed -i.bak '1,/csh$/{/csh$/d}' /etc/passwd

The "1,/pattern/ {...}" syntax means "do this block from the first line up through and including the line that matches the given pattern". The only downside here is needing to repeat the pattern match inside the block so you don't purge all of the lines before the first match.

But this thread got me thinking about the more general problem of removing the Nth matching line from a given file. Unfortunately, sed isn't ideal for this because the only "variable" you really have to store things in is sed's hold space. But awk makes short work of our challenge:

# awk '/csh$/ {if (++c == 3) next}; {print}' /etc/passwd >/etc/passwd.new

We're keeping a count of the number of matching lines in the variable "c". In this case, when c is equal to 3, we skip over the matching line and it doesn't get printed out. This effectively deletes the third matching line from the file.

Since awk has compound boolean operators, you can even delete ranges of lines:

# awk '/csh$/ {if (++c > 3 && c < 10) next}; {print}' /etc/passwd >/etc/passwd.new

The above command will remove the 4th-9th matching lines from the file. I'm not exactly sure why this would ever be useful, but it's a good shell trivia question anyway.

The only downside to awk is that it doesn't have sed's in place editing mode. I could do something very similar with Perl-- which has the "-i" option for in place editing just like sed-- but our blog rules don't let me use Perl.

Now if Tim can get his dog Sam to stop eating those purple flowers, we might see some Windows action on this blog...

Tim is taking his time gettin' the good sign

Hal started off by deleting lines from a file that matched a certain string. This is the same as keeping lines that don't match the string. It's like a double negative, and that is exactly what Hal did and what we'll do here:

PS C:\> (gc file.txt) -notmatch "somestring" | sc newfile.txt


We use Get-Content (alias gc) to output the file. The -NotMatch operator will pass any line that doesn't match "somestring". Finally, we use Set-Content (alias sc) to write our file. The benefit of Set-Content over something like Out-File or a redirect (>) is that Set-Content will keep the same encoding and the others will default to unicode. Set-Content makse more sense as we just want to remove lines, not change more about the file.

Unfortunately, this command will load the entire file into memory first, so it may be a problem with big files. To do the same thing without loading the file into memory requires a command that is a slightly less terse.

PS C:\> gc file.txt | ? { $_ -notmatch "somestring" } | sc newfile.txt


All we do is pipe Get-Content into Where-Object (alias ?) and then into Set-Content. Not a big change, but it is a few characters longer.

We can accomplish a similar task with the cmd.exe:

C:\> type file.txt | find /v "somestring" > newfile.txt


We use the Type command to output our file and pipe it into Find. Find's /v option displays lines that don't contain our string.

Now Hal wants to make it complicated, and only remove the first instance of "somestring". We have to do a little "enhanced fu" (not be confused with a script).

PS C:\> $found = 0; gc file.txt | ? { $_ -notmatch "somestring" -or $found++ } | sc newfile.txt


This is a little confusing at first glance. Even after I came up with it, it still confused me for a few minutes. We start off by setting $found to 0 (false). We then read our file with Get-Content and pipe it into Where-Object (alias ?). Now here is the trick.

In the Where-Object script block we first check if the line doesn't match "somestring". Due to the short circuit nature of the PowerShell's logical operators, if NotMatch is true we don't need to check if $found is true (non-zero). When we come to a line that does contain "somestring", the first portion is false and we need to check the value of $found. The first time $found is evaluated it is 0 (false), and since the entire script block evaluates to false the line is not passed down the pipeline. However, when the value of $found is checked the increment operator (++) adds one to $found, so any future attempts will evaluate to true. Seem confusing? Here is a sample file and what will happens as we work through the file:

Line 1        # notmatch true;  $found not evaluated; object passed
Line 2 # notmatch true; $found not evaluated; object passed
asomestringa # notmatch false; $found false; object NOT passed; $found incremented
Line 3 # notmatch true; $found not evaluated; object passed
asomestringa # notmatch true; $found true; object passed
Line 4 # notmatch true; $found not evaluated; object passed


So far so good. But we have a little problem. Neither PowerShell or cmd.exe will automatically create a backup. We have to create a copy ourselves and then do our modification. I won't bore you with how to copy a file.

Next, Hal removed the 3rd line of our file. Here is how we do it in PowerShell:

PS C:\> gc file.txt | ? {$_.ReadCount -ne 3} | sc newfile.txt


We can use a similar technique to remove a range of lines (4th through 9th):

PS C:\> gc file.txt | ? { (4..9) -notcontains $_.ReadCount }


We got action, not as much as *nix. We ain't got much but what we got's ours.

Tuesday, May 31, 2011

Episode #147: Lines o' Code

Hal asks, "Dude, Where's My Blog?"

Wow, the last couple of weeks have been a blur, huh? I can't remember much, but now I have a lifetime supply of pudding in the kitchen, a new track suit, and a strange tattoo on my back. Plus there are a couple of weird Swedish sounding dudes hanging around.

But none of that shall deter us from getting back on our Command Line Kung Fu horse. Today's challenge is counting lines of code. Now I'm not a big fan of "lines of code" as a metric, but sometimes it's useful to know. However, I'm generally not interested in blank lines (which for me also includes lines that are entirely whitespace) and lines which only contain comments. So we'll want to filter those out before running the remaining lines through "wc -l".

sed is probably the easiest way to get rid of the stuff we don't want:

$ sed '/^[ \t]*$/d; /^[ \t]*#/d' .bashrc | wc -l
33

The first part of the sed expression-- "/^[ \t]*$/d"-- matches the beginning of line ("^") followed by zero or more instances of space or tab ("[ \t]*") followed by end of line ("$"). If we match, then the "d" after the regex means drop the current line without printing and move on to the next.

The second regex is similar. It matches any amount of whitespace from the start of the line ("^[ \t]*") followed by a comment character ("#"). Obviously, the comment character you match will vary by programming language, but here we're working with shell code ("#" also works fine for Perl and many other scripting languages).

But what if you had an entire directory structure of source code and you wanted to count the lines in all of the individual files? The problem with our command above is that the file name doesn't end up being included in the output. But we can dust off the technique we used in Episode #46:

$ find /usr/lib/perl5/5.8.8/ -name \*.pm | while read file; do 
echo -n "$file ";
sed '/^[ \t]*$/d; /^[ \t]*#/d' $file | wc -l;
done | awk '{t = t + $2; print $2 "\t" $1} END {print t "\tTOTAL"}'

...

1800 /usr/lib/perl5/5.8.8/Tie/File.pm
91 /usr/lib/perl5/5.8.8/Tie/Scalar.pm
206 /usr/lib/perl5/5.8.8/Tie/Array.pm
179 /usr/lib/perl5/5.8.8/Shell.pm
496 /usr/lib/perl5/5.8.8/diagnostics.pm
244 /usr/lib/perl5/5.8.8/AutoLoader.pm
66 /usr/lib/perl5/5.8.8/DirHandle.pm
118 /usr/lib/perl5/5.8.8/autouse.pm
129671 TOTAL

First we use find to locate all of the source code files we're interested in and pipe the list of file names into a while loop that reads them one by one. Within the loop we spit out the file name plus a space using "echo -n" to suppress the newline usually emitted by echo. That way, our "wc -l" command output ends up on the same line as the file name. Finally, just like in Episode #46 we pipe all the output into an awk expression that neatens up the file name and line count output (reversing the two fields and adding a tab) and even prints out a nice total at the end.

So, Tim, what have you got up your sleeve besides that "Sweet" new tattoo?

Tim's been stuck in a Chinese drive thru for past few weeks. NO AND THEN!

Hal and his silly short commands. He needs to man up and go for the man-sized commands, like this:

PS C:\> Select-String -NotMatch -Pattern "^\s*(#|$)" -Path file.txt | Measure-Object -Line

Lines Words Characters Property
----- ----- ---------- --------
33


Of course, we can shorten it up a bit with aliases, shortened parameter names, and positional parameters:

PS C:\> Select-String -n "^\s*(#|$)" file.txt | measure -l


The command looks for lines that don't match our regular expression. The regular expression looks for the following, in order:
  • "^" beginning of line

  • "\s*" any number, including zero ("*"), whitepace characters ("\s")

  • "(#|$)" Either the "#" character OR ("|") the end of line ("$")


We use Select-Object (alias select) to just output the line count.

PS C:\> Select-String -n "^\s*(#|$)" file.txt | measure -l | select lines

Lines
-----
33


The recursive directory listing is a bit more complicated, and there a few ways to do it. The most PowerShell-y way to do it is by outputting objects, and we'll use Group-Object (alias group) to do it.

PS C:\> Get-ChildItem -Recurse -Include *.pm | Select-String -NoElement -Pattern "^\s*(#|$)" | Group-Object -Property Path -NoElement

Count Name
----- ----
15 C:\perl\otherdir\i.pm
17 C:\perl\hate.pm
5 C:\perl\perl.pm


We start with a recursive directory listing where we only look for .pm files. The files are piped into the Select-String cmdlet were we look for the lines we want using the aforementioned regular expression. The results are piped into Group-Object to give us number of matching lines per file.

The entire command can be shortened using the regular techniques.

PS C:\> ls -r -i *.pm | Select-String -n "^\s*(#|$)" | group Path -n


Unfortunately, there isn't a nice way to get the total line count. We can do it using a variable to store our results. I'll keep it as multiple lines for easier reading.

PS C:\> $a = ls -r -i *.pm | Select-String -n "^\s*(#|$)" | group Path -n
PS C:\> $a

Count Name
----- ----
15 C:\perl\otherdir\i.pm
17 C:\perl\hate.pm
5 C:\perl\perl.pm

PS C:\> $a | Measure-Object -Sum -Property Count | Select-Object sum

Sum
---
35


"Dude!" What does mine say?

Tuesday, May 10, 2011

Episode #146: Hard CIDR

Tim is the mailman:

Most of our episode ideas come from the mailbag, and we can never have too many. Usually, we usually have too few, so keep sending in ideas. This episode was inspired by the modern art masterpiece sent in by Matt Graeber. His "piece" reads a file, expands a list of CIDR formatted IP addresses, and does a reverse DNS lookup against each IP address.

C:\> cmd.exe /v:on /c "FOR /F "tokens=1-5 delims=./" %G IN (ips.txt) DO
@(set network=%G.%H.%I.& set /a fourth="%J+1" 1^>nul & set mask=%K&
set /a end="(2 ^<^< (32-!mask!-1))-2+!fourth!" 1>nul &
echo !network!!fourth!-!end!& echo ****************** &
FOR /L %O IN (!fourth!,1,!end!) DO @(for /F "tokens=2" %P in
('nslookup !network!%O server 2^>nul ^| find "Name:"') do
@echo !network!%O %P & ping -n 3 127.0.0.1>nul))" 2>nul


That is some serious cmd madness. Since it is such beautiful art, we will leave it to the reader to behold and interpret for himself, but we will go over a more simplified version.

It should be noted, that all the commands presented today only work with 24+ bit masks. Using built in tools to expand the CIDR format for a mask less than 24 is significantly more work because we have to manipulate the third (and possibly second or first) octet(s) as well. We'll use the file below as our sample input file:

192.168.1.32/27
10.10.10.128/26
172.16.0.0/24


We'll simplify Matt's command so it only expands and outputs the IP addresses. From there, you can replace the echo command with the command of your choice. This CIDR expansion is very handy for wraping commands that only take a single IP as input.

The simplified version of the CIDR expander is:

C:\> cmd.exe /v:on /c "FOR /F "tokens=1-5 delims=./" %G IN (ips.txt) DO
@(set network=%G.%H.%I.& set /a fourth="%J" 1^>nul & set mask=%K&
set /a end="(2 ^<^< (32-!mask!-1))-1+!fourth!" 1>nul &
FOR /L %O IN (!fourth!,1,!end!) DO @echo !network!%O)" 2>nul


192.168.1.32
192.168.1.33
...
192.168.1.62
192.168.1.63
10.10.10.128
10.10.10.129
...
10.10.10.190
10.10.10.191
172.16.0.0
172.16.0.1
...
172.16.0.254
172.16.0.255


The command begins by enabling delayed variable expansion (explained at the end of Episode #46). The For Loop then reads our file and splits the text on each period and forward slash, so we have variables that hold each octet (%G-%J) as well as the number of bits in the subnet mask (%K). Next, a bit of cmd math is done to calculate the last IP address in the range. Finally, another For loop is used to output all of the IP addresses. Of course, we could do something else with the IP addresses instead of just displaying them, like ping or nslookup.

The math used to calculate the upper bound of our network uses a Logical Shift Left (<<). This operator shifts each bit to the left one location. So 2 (00000010) left shifted by 1 is 4 (00000100) and 2 left shifted twice is 8 (000010000). This operator is used to replace the nonexistent 2^x command.

PowerShell:

The PowerShell command to expand the addresses ranges is:

PS C:\> gc ips.txt | % {
$a=$_.split('./');
$a[3]..($a[3]-1+[Math]::Pow(2,32-$a[4])) | % {
echo ($a[0],$a[1],$a[2],$_ -join ".")
}
}


We start by reading our file using the Get-Content cmdlet (aliases gc and cat). Each line is piped into a ForEach-Object loop to be parsed and manipulated.

Inside our loop we split each string into an array of substrings, using period and forward slash as delimiters. We then end up with $a[0] through $a[3] holding the first through fourth octets and $a[5] is the mask.

The range operator (..) is use to generate a list of numbers between our lower bound (last octet) and the upper bound (end of network range). Again, we use a little math to determine the size of the range. In short, the size of the range is 2^(32-masklen). There isn't a native exponent operator, so we use the built in .NET Math class to do our power function.

The output of the range is fed into another ForEach-Object cmdlet. Inside this cmdlet's scriptblock is where the IP address is reassembled and output.

Now that we have the output, we can easily feed it to another command. For example, say we wanted to ping each of the IP addresses:

 PS C:\> ... | % { ping $_ }


No off to go find some hard cider to make this pain go away...

Hal is the eggman

Tim and I usually work up our pieces of the blog independently and then jam them together using a few insults as connective tissue. It's interesting that in this case my thought process developed along a parallel course with Tim's transition from CMD.EXE to Powershell.

My initial attempt looked a lot like Matt and Tim's CMD.EXE solutions:

while read line; do 
exp=${line/*\//};
base=${line/\/*/};
lastoct=${base/*./};
net=${base/%.$lastoct/};
for ((i=0; $i < $(( 2 ** (32-$exp) )); i++)); do
oct=$(($lastoct + $i));
echo $net.$oct;
done;
done <input

The outer while loop reads the input file line-by-line. Then I exploit the bash variable substitution operator ("${var/pattern/sub}") to pull the address and exponent apart, and to strip the last octet from the address. After that it's just a for loop to create the list of addresses. That little "echo" statement in the middle of the inner loop is the whole purpose of the exercise-- the rest is just grisly parsing and setup.

So I wasn't really happy with my solution. But then it occurred to me that I don't have to do the parsing. The shell will do it for me!

IFS=./
while read o1 o2 o3 o4 exp; do
for ((i=o4; $i < $(( $o4 + 2 ** (32-$exp) )); i++)); do
echo $o1.$o2.$o3.$i;
done;
done <input

The trick is to set IFS so that the shell automatically tokenizes each line as we "read" it in the while loop (essentially we're accomplishing the same thing that Tim does with his Powershell split() operator). If IFS is set to "./" then each octet and the exponent is broken out into a different variable and I don't have to do any parsing myself. This is a very useful technique when you're dealing with any "strongly delimited" input-- like /etc/passwd, /etc/shadow, and so on.

You'll also notice that I cleaned up my loop control a little bit so that I save myself a "$((...))" operation inside the inner loop. Rather than having the loop control variable run from 0..2**(32-exp) and then adding the value to the last octet inside the loop, it's easier to start the loop with the last octet value and increment from there.

By the way, some of you may be wondering why I didn't use the built-in range operator in bash and make my for loop be something like:

for $i in {$o4..$(($o4 + 2**(32-$exp) - 1))} ...

I actually tried this approach first. But it turns out that bash only lets you use literal values-- integers or characters-- in a "{a..z}" operation. This actually strikes me as something of a bug.

In any event, that's why I ended up opting for the C-style for loop instead. I could have used something like "$( seq $o4 $(($o4 + 2**(32-$exp) - 1)) )", but why call an external program when you don't have to?

So goo goo g'joob and have a great week everybody!

Tuesday, May 3, 2011

Episode #145: A Date to Copy

Tim checks the mail (again):

One of our readers writes in asking how to generate "a list of locations of doc files which are created or modified after month and year 01 /2011." He then wants to copy all those files to another directory. He specifically stated he wanted it to work on XP and without PowerShell.

Well, let me get on my soap box for a second. PowerShell v1 and v2 are available for XP. I can't recommend enough that people install PowerShell. It will make your Windows administration and command line experience easier and much less painful. Case in point, it took me a decent amount of time to write the cmd.exe portion of this episode, which includes all the trial and error. However, the PowerShell portion is so straight forward I wrote that portion off the top of my head. So if you are on a Windows box without PowerShell, go install it before continuing. Ok, enough ranting, back to our regularly scheduled programming...

One nice thing is that we are only looking for files based on year, so that makes our time parsing much easier in cmd.exe. If we had to parse based on month and year it would be exponentially harder with this antiquated shell.

We can use a number of the techniques taken from Episode #29. Specifically, the For loop with the ~f (full file path). We can use ~t with our variable to get the modified timestamp, but there isn't a modifier to give us the creation time, so we'll have to take a slightly different approach.

First, we start off with a For loop that will find all the .doc files on the system.

C:\> for /r %i in (*.doc) do @echo %~fi

C:\Doc\file1.doc
C:\Doc\file2.doc
...


We have all the .doc files, so now we take a giant leap to our final command:

C:\> for /r %i in (*.doc) do (@dir /tw %~fi | find "/2011" > NUL ||
@dir /tc %~fi | find "/2011" > NUL) && copy %~fi C:\DocsFrom2011


We use two Dir commands with different time (/t) options. The first, /tw, displays the Last Write Time. The second, /tc, displays the Creation Time. Each of these Dir commands is piped into a Find command that looks for the year portion of the date "/2011". All that is wrapped in a bit of magic logic that is used to determine if the file should be copied or not. The magic explained...

We use some Logical ORs (||) and a Logical And (&&) to do the magic. The cmd.exe shell uses short circuit logical operators, but what does that mean? In short, if we wanted to evaluate A && B the second expression (B) is only evaluated when the result is not fully determined by A. For example, given A && B, when A is false there is no reason to evaluate B since the Logical And will then be false regardless of the value of B. Enough of the Math/Logic lesson, back to our command...

The logic in our command reduces to: (Last Write Time Matches OR CreationDate Matches) AND copy. Given our short circuit logical operators, if neither the Creation or Last Write Times match, we don't do the copy. But if either matches, copy.

Now on to the much easier, PowerShell.

PowerShell

Not only is the PowerShell version is much easier, and much more robust, as it can actually compare dates. That means we could just as easily look for files created after any arbitrary date, not just January 1.

PS C:\> Get-ChildItem -Recurse -Include *.doc | Where-Object {
$_.LastWriteTime -ge "1/1/2011" -or $_.CreationTime -ge "1/1/2011" } |
Copy-Item -Destination C:\DocsFrom2011


The command can be shortened using built in aliases and shortened parameter names:

PS C:\> ls -r -i *.doc | ? { $_.LastWriteTime -ge "1/1/2011" -or $_.CreationTime -ge "1/1/2011" } |
cp -d C:\DocsFrom2011


This command does a recursive directory listing and pipes the results into a Where-Object filter. The filter only passes objects where the relevant timestamps are greater than, or equal to, Jan 1, 2011. All the objects that make it through the filter are sent to Copy-Item to be copied to our target folder.

The PowerShell version is included, even though this portion wasn't requested by our reader. I guess that makes me only half wanted. Since Hal's shell isn't supported on XP I guess he isn't wanted either, but here he is anyway.

Hal checks in

Not wanted? Don't go projecting your insecurities onto me now. Just repeat this daily affirmation, "CMD.EXE is good enough, and gosh darn it people just love XP!" Besides, you can always install Cygwin to help you over the rough spots.

This one really is similar to Episode #29-- we just have to do something with the file names once we pick them out. For that I think I'll bust out the cpio magic as I did back in Episode #115:

# touch -t 201101010000 /tmp/marker
# cd /some/source/dir
# find . -depth \( -name \*.doc -o -name \*.docx \) -newer /tmp/marker |
cpio -pd /path/to/target/dir

5854 blocks

First I use touch to create a file with the earliest date for files which we're interested in. I use this with "find ... -newer" to find all files that have been modified since this timestamp. Unfortunately traditional Unix file systems still don't track creation time on files (unless you've upgraded to EXT4), so last modified time is all we have to go on.

Our loyal reader specified that they were only interested in doc files, but I decided to make my life harder by looking for both the old style *.doc files and the newer *.docx format. Notice that the Windows guy in our little CommandLineKungFu partnership didn't think to look for both file extensions.

Notice that I'm also using the "-depth" option with find to work around any possible issues with read-only directory permissions when cpio is creating the parallel directory structure in the target directory. See the discussion in Episode #115 for more details.

So there you go, a solution to a new problem created by putting two earlier solutions together. And that's pretty much the Unix command-line religion anyway. And that's why Unix is cool. And, gosh darn it, people like it!

Tuesday, April 26, 2011

Episode #144: What the Hex?

Tim has a sugar high

Recently, I've been going through some exploit development tutorials. One of the exploits was for a file format vulnerability. I created my malicious file and saved it on my Windows machine, and I wanted to take a quick peek at the file and confirm that I had written the correct information. I wanted to take a look at the bytes, but not all the bytes are printable. Of course there are a million ways to view this file, but I decided to try PowerShell since I didn't have any other tools installed in this clean install of Windows.

PS C:\> get-content -encoding byte -totalcount 1000 shellcode.bin
80
83
81
82
86
87
85
156
...


This uses the good ol' Get-Content cmdlet. It reads raw bytes by setting the Encoding parameter to Byte. I used the TotalCount parameter since I only want to see the first 1000 bytes.

Of course, the output isn't nice. First, the output is in decimal form instead of hex. We can quickly fix that:

PS C:\> get-content -encoding byte -totalcount 1000 shellcode.bin | % { "{0:X2} " -f $_ }
50
53
51
52
56
57
55
9C
...


We use the ForEach-Object cmdlet (alias %) to format each byte as hex. Now to fix the second output option, the vertical display.

PS C:\> (get-content -encoding byte -totalcount 1000 shellcode.bin | % { "{0:X2}" -f $_ }) -join " "
50 53 51 52 56 57 55 9C ...


Simply wrapping the entire command in paranthesis and using the Join operator effectively rotates our output.

If you want a different format you can modify the format string. Say we wanted it with a prepended '\x'.

PS C:\> (get-content -encoding byte -totalcount 1000 shellcode.bin | % { "\x{0:X2}" -f $_ }) -join " "
\x50 \x53 \x51 \x52 \x56 \x57 \x55 \x9C ...


Not to bad huh? Of course, this is super simple for Hal. <Sigh>

Hal is still Bali Hai

Thanks for taking it easy on me as I'm coming down off my vacation, Tim. How's that competition snow shoveling working out for you?

As Tim points out, this one is easy for Unix because (being a programmers' operating system) we have built-in hex dumpers. The old standby is the "od", or "octal dump" command. Despite the name, od can output in a variety of formats, including hex:

$ od -N 48 -x /bin/bash
0000000 457f 464c 0102 0001 0000 0000 0000 0000
0000020 0002 003e 0001 0000 f210 0041 0000 0000
0000040 0040 0000 0000 0000 3a80 000e 0000 0000
0000060

Here I'm using the "-N" option to only dump out the first 48 bytes of the file, and "-x" specifies that I want the output in hex format. If I wanted the output grouped as single bytes rather than pairs, I could use a slightly different option:

$ od -N 48 -t x1 /bin/bash
0000000 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
0000020 02 00 3e 00 01 00 00 00 10 f2 41 00 00 00 00 00
0000040 40 00 00 00 00 00 00 00 80 3a 0e 00 00 00 00 00
0000060

The "-t" option lets you specify the output format more completely. The first letter denotes the type of output you want: "x" for hex, "o" for octal, "a" and "c" for character types, "f" for floating point, and so on. The number following the letter lets you choose the size groups you want in the output.

But since I generally only ever want hex dumps, I usually use xxd instead of od:

$ xxd -l 48 -g 1 /bin/bash
0000000: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 .ELF............
0000010: 02 00 3e 00 01 00 00 00 10 f2 41 00 00 00 00 00 ..>.......A.....
0000020: 40 00 00 00 00 00 00 00 80 3a 0e 00 00 00 00 00 @........:......

xxd is a pure hex dumper (although it can dump bits if you use "-b") so we don't need a special option to output hexadecimal. Use "-l" to specify how many bytes you want to read, and "-g" to specify the number of bytes for grouping the output. Like od, the default output grouping is 2 bytes, but I specified 1 byte output in the command above.

If you don't want all the extra frippery that the normal xxd output gives you-- like byte offsets and ASCII translation-- you can use the "-p" (plain) option to just get the raw bytes:

$ xxd -p -l 48 /bin/bash
7f454c4602010100000000000000000002003e000100000010f241000000
00004000000000000000803a0e0000000000

This format is particularly useful when you want to pipe the output into something else. For example, I could now use sed to produce the "\x" notation similar to Tim's last example:

$ xxd -p -l 48 /bin/bash | sed 's/\(..\)/\\x\1 /g'
\x7f \x45 \x4c \x46 \x02 \x01 \x01 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x02 ...
\x00 \x00 \x40 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x80 \x3a \x0e \x00 \x00 \x00 \x00 \x00

Now if I could only figure out a way to use the shell to dump myself as quickly from one side of the Pacific to the other, that would be quite a feat! Oh well, perhaps the long flight will inspire me with some new shell fu for next week.

Tuesday, April 19, 2011

Episode #143: Unicode to Shellcode

Hal checks in from Bali

Just a quick one this week. After finishing up with my posse of hard-rocking malware-crazed weasels from SANS Bali, I'm due for a little R&R and, hey, did I mention I'm in Bali? But sun, sand, surf, and sky will not prevent me from providing our faithful readers with their weekly dose of Command Line Kung Fu. Besides, teaching Lenny Zeltser's excellent Reverse Engineering Malware class always gives me ideas for new Fu.

This week's challenge is a fairly common one for malware analysts. Many times you have Javascript code from web pages, Microsoft Office documents, or PDF files that contain shellcode payloads in various different obfuscated forms. One encoding type is two-byte, little-endian unicode represented by strings such as %u8806. Today's sample goes that one better though, by introducing extra whitespace and punctuation like so:

'%u5350%u5', '251%u5756%', 'u9c55%u00', 'e8%u0', '000%u5d00', ...

Lenny came up with some tasty Perl code to extract the necessary bytes and reformat them into hex notation such as "\x06\x88" (and from there they can be converted to an executable to analyze with a tool such as shellcode2exe.py). While I'm a big fan of Perl, it's against the rules of our little blog experiment. So I started wondering what the sed solution would look like.

Wonder no more:

$ sed 's/[^0-9A-Fa-f]//g; 
s/\(..\)\(..\)/\\x\2\\x\1/g' shellcode.uni >shellcode.hex

The first substitution gets rid of anything that isn't a hex digit. Not only does this clean up the whitespace, quotes, and commas, it even eliminates all those "%u"s for us. Next we need to grab each byte-- represented by two hex digits-- and put a "\x" in front of it. The tricky part is that the original unicode was in little-endian format, so we must swap each pair of bytes as we work through the string of characters. That's why you see me grabbing two bytes at a time and outputting them with "...\2...\1..." on the right-hand side of the substitution.

Well that's all from my little corner of the South Pacific. I must go now as I hear something calling me...

Tim checks in from a spot where the @$%#$%^ snow is falling:

The approach is the same with PowerShell: 1) read the file, 2) remove characters that don't represent hex, and 3) swap the pairs of characters while adding a "\x".

PS C:\> Get-Content shellcode.uni |
ForEach-Object { $_ -replace '[^0-9A-F]', '' } |
ForEach-Object { $_ -replace '(..)(..)', '\x$2\x$1' }


\x50\x53\x51\x52\x56\x57\x55\x9c


Notice the command above uses single quotes. That is because PowerShell will expand any strings inside double quotes before our Replace method has a chance to do any replacing. This means that PowerShell would try to convert $1 into a variable and not pass the literal string to the Replace method. If you happened to use double quotes you would get output like this:

PS C:\> Get-Content shellcode.uni |
ForEach-Object { $_ -replace '[^0-9A-F]', '' } |
ForEach-Object { $_ -replace '(..)(..)', "\x$2\x$1" }


\x\x\x\x\x\x\x\x\x\x...


A longer explanation can be found toward the end of Episode #126.

Now we have the output we want, but let's shorten up the command by using aliases:
PS C:\> gc shellcode.uni |
% { $_ -replace '[^0-9A-F]', '' } |
% { $_ -replace '(..)(..)', '\x$2\x$1' }


We can also remove the ForEach-Object cmdlets and shorten it further:

PS C:\> ((gc shellcode.uni) -replace '[^0-9A-F]', '') -replace '(..)(..)', '\x$2\x$1'


We have one minor problem, if shellcode.uni contains line breaks then each line will be read separately and the breaks won't be removed. If there are multiple lines of text in the file then Get-Content will return an array of objects instead of a multiline string.

PS C:\> (gc shellcode.uni).getType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array


We can fix this by converting it to a string.

PS C:\> ([string](gc shellcode.uni)).getType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object


Our robust shortened version of the command looks like this:

PS C:\> ([string](gc shellcode.uni) -replace '[^0-9A-F]', '') -replace '(..)(..)', '\x$2\x$1'


The final piece is to output our results, and we can use the Out-File cmdlet to do it. However, the default output encoding for PowerShell is unicode which isn't what a disassembler is expecting since it isn't the shellcode we want. We have to tell PowerShell to use ASCII by using the -Encoding parameter.

PS C:\> ... | Out-File shellcode.hex -Encoding ASCII


This our final command looks like this:

PS C:\> ([string](gc shellcode.uni) -replace '[^0-9A-F]', '') -replace '(..)(..)', '\x$2\x$1' |
Out-File shellcode.hex -en ASCII


Well that's all from my frozen corner of the Minnesota. I must go now as I hear something calling me...