Showing posts with label exec. Show all posts
Showing posts with label exec. Show all posts

Thursday, March 5, 2009

The Mouse That Roared: Killing A Sun Server During Lunch Break

Hey there,

We continue today with our fast-and-furious post week (brought on by a spat of work and family obligations like we've never seen before!). Like they say: "It's all right if your work gets in the way of your hobbies, but if it gets in the way of itself..." No, wait. That saying goes the other way and is completely inappropriate ;)

Today we decided to test the age-old proposition that any Goliath can be brought down by a David. In this case, we pitted a simple shell script against a SunBlade 150 with 1Gb of RAM (Half of what it can support) and a 650 MHz UltraSPARC IIi CPU (About as good as it can get). The entire experiment took about 30 minutes, because we only ran it until we got sick and tired of waiting.

The end result was a machine that was completely unusable from the console, unreachable via telnet, ftp or ssh and, somehow managed not to panic and crash after about 1000 faults of every kind and color. We're confident it would have eventually gone down, but it was surprisingly robust (in that respect). If we have hours and hours to spend at some time in the future, we'll give the same test a shot and see if the machine just comes back to its senses over time (and how long that takes). Our bet is that it will (like most Unix and Linux OS's running on halfway decent hardware). Only time will tell.

Following, a quick walkthrough of the experiment followed by the tiny little shell script (only run once) that caused all the damage. We called it tree, for some reason; perhaps because it reminded us of that old saying "If a tree falls in a forest, no one can hear you scream." ...damn! Got that one wrong, too! It's amazing what a few basic shell commands and a simple double-exec can do ;)

THE WALKTHROUGH:

1. BASELINE READING:
These are some basic statistics from when nothing much is going on.

host # date;uptime;vmstat 1 1;iostat 1 1
Tue Mar 3 16:56:17 CST 2009
4:56pm up 41 day(s), 3:25, 3 users, load average: 0.71, 1.36, 1.41
kthr memory page disk faults cpu
r b w swap free re mf pi po fr de sr dd f0 rm s1 in sy cs us sy id
0 0 0 1240680 389376 1 10 1 0 0 0 0 0 -0 -0 -0 402 381 276 71 3 26
tty dad1 ramdisk1 sd1 nfs1 cpu
tin tout kps tps serv kps tps serv kps tps serv kps tps serv us sy wt id
1 136 1 0 3 0 0 0 0 0 1 0 0 1 71 3 0 26


2. INITIAL EXECUTION OF THE SCRIPT WITH TIME/DATE STAMPING: Notice how high the uptime stats jump and the greater time differences between executions of the simple loop.

host # ./tree
host # while :;do date;uptime;vmstat 1 2;iostat 1 2;done
Tue Mar 3 17:01:22 CST 2009
5:01pm up 41 day(s), 3:30, 2 users, load average: 119.02, 27.25, 10.11
kthr memory page disk faults cpu
r b w swap free re mf pi po fr de sr dd f0 rm s1 in sy cs us sy id
0 0 0 1240680 389376 1 10 1 0 0 0 0 0 -0 -0 -0 402 381 276 71 3 26
1038 0 0 981184 260848 547 6123 17 174 174 0 0 56 0 0 0 513 6623 336 20 80 0
tty dad1 ramdisk1 sd1 nfs1 cpu
tin tout kps tps serv kps tps serv kps tps serv kps tps serv us sy wt id
1 136 1 0 3 0 0 0 0 0 1 0 0 1 71 3 0 26
0 11800 0 0 0 0 0 0 0 0 0 0 0 0 50 50 0 0

Tue Mar 3 17:02:02 CST 2009
5:02pm up 41 day(s), 3:31, 2 users, load average: 445.61, 118.66, 42.41
kthr memory page disk faults cpu
r b w swap free re mf pi po fr de sr dd f0 rm s1 in sy cs us sy id
0 0 0 1240672 389376 1 10 1 0 0 0 0 0 -0 -0 -0 402 381 276 71 3 26
1271 1 0 891840 189784 581 6149 4 239 235 0 0 95 0 0 0 591 6517 359 20 80 0
tty dad1 ramdisk1 sd1 nfs1 cpu
tin tout kps tps serv kps tps serv kps tps serv kps tps serv us sy wt id
1 136 1 0 3 0 0 0 0 0 1 0 0 1 71 3 0 26
0 550 241 31 1 0 0 0 0 0 0 0 0 0 17 83 0 0

Tue Mar 3 17:02:55 CST 2009
5:02pm up 41 day(s), 3:32, 2 users, load average: 851.80, 278.54, 102.82
kthr memory page disk faults cpu
r b w swap free re mf pi po fr de sr dd f0 rm s1 in sy cs us sy id
0 0 0 1240664 389368 1 10 1 0 0 0 0 0 -0 -0 -0 402 381 276 71 3 26
870 1 0 753176 54624 159 2286 260 1085 1236 0 758 346 0 0 0 1090 5003 1533 13 87 0
tty dad1 ramdisk1 sd1 nfs1 cpu
tin tout kps tps serv kps tps serv kps tps serv kps tps serv us sy wt id
1 136 1 0 3 0 0 0 0 0 1 0 0 1 71 3 0 26
0 170 1392 319 44 0 0 0 0 0 0 0 0 0 16 84 0 0


3. 6 MINUTES IN AND WE'VE GOT PROBLEMS: It only gets worse from here, since our script has exponentially multiplied itself so many times already that the amount of possible failed execs is infinitesimal in comparison to the system faults.

Tue Mar 3 17:07:45 CST 2009
ld.so.1: cp: fatal: /usr/lib/libc.so.1: mmap failed: Resource temporarily unavailable
ld.so.1: cp: fatal: libc.so.1: open failed: No such file or directory
Killed
ld.so.1: sh: fatal: /usr/lib/libc.so.1: mmap failed: Resource temporarily unavailable
ld.so.1: sh: fatal: libc.so.1: open failed: No such file or directory
ld.so.1: sh: fatal: /usr/lib/libc.so.1: mmap failed: Resource temporarily unavailable
ld.so.1: sh: fatal: libc.so.1: open failed: No such file or directory
ld.so.1: cp: fatal: /usr/lib/libc.so.1: mmap failed: Resource temporarily unavailable
ld.so.1: cp: fatal: libc.so.1: open failed: No such file or directory
Killed
tree: tree: cannot open
ld.so.1: cp: fatal: /usr/lib/libc.so.1: mmap failed: Resource temporarily unavailable
ld.so.1: cp: fatal: libc.so.1: open failed: No such file or directory
Killed
ld.so.1: cp: fatal: /usr/lib/libc.so.1: mmap failed: Resource temporarily unavailable
ld.so.1: cp: fatal: libc.so.1: open failed: No such file or directory
Killed
ld.so.1: cp: fatal: /usr/lib/libc.so.1: mmap failed: Resource temporarily unavailable
ld.so.1: cp: fatal: libc.so.1: open failed: No such file or directory
Killed
cp: Cannot map /lib/ld.so.1
Killed
tree: cannot fork: no swap space


4. 16 MINUTES IN AND THE CONSOLE IS TOAST: Still the brave little toaster, I mean SunBlade, stays on the net and doesn't go down. In fact, response times to echo are instant.

host # while :;do date;ping -c 10 10.99.99.99;date;done
Tue Mar 3 17:17:56 CST 2009
PING 10.99.99.99: (10.99.99.99): 56 data bytes
64 bytes from 10.99.99.99: icmp_seq=0 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=1 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=2 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=3 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=4 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=5 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=6 ttl=254 time=0 ms

Tue Mar 3 17:19:22 CST 2009
PING 10.99.99.99: (10.99.99.99): 56 data bytes
64 bytes from 10.99.99.99: icmp_seq=0 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=1 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=2 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=3 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=4 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=5 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=6 ttl=254 time=0 ms


5. 28 MINUTES IN AND WE'RE GETTING TIRED OF WAITING: The little SunBlade never tapped out (at least not in the first half hour). Even though it has been rendered completely useless, the ping responses are still sitting at 0ms. Time for a reboot.

host # while :;do date;ping -c 10 10.99.99.99;date;done
Tue Mar 3 17:30:32 CST 2009
PING 10.99.99.99: (10.99.99.99): 56 data bytes
64 bytes from 10.99.99.99: icmp_seq=0 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=1 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=2 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=3 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=4 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=5 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=6 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=7 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=8 ttl=254 time=0 ms
64 bytes from 10.99.99.99: icmp_seq=9 ttl=254 time=0 ms


6. AND THIS IS HOW EASY IT WAS TO CRIPPLE THE MACHINE: The script attached is very simple. Given a larger machine, with more horsepower, we think you'd see the exact same results within, probably, the same amount of time. Hopefully, someday, we'll be able to find out without losing our jobs ;)

If there was a lesson in today's post, it would probably read something like this: "Be mindful of the small things. They can grow into big things very fast!" (We got that one right, since we just paraphrased something that may or may not be a famous expression ;)

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/bin/bash

#
# tree - POC only - don't run this - it will spawn a lot of processes and slow your machine down severely.
#
# 2009 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

mkdir a b
cp tree a/
cp tree b/
(cd a;exec sh tree &)
(cd b;exec sh tree &)


, Mike




Discover the Free Ebook that shows you how to make 100% commissions on ClickBank!



Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Thursday, April 17, 2008

More Fun With Bash Networking

Greetings,

You may recall a post we did about a week or so ago on accessing the network directly with bash. Today's post is a bit of a follow up to that introduction, with some tips and clarification added for clarity and/or enjoyment ;)

1. The basic setup (this will be the only part revisited from our original post on bash networking. In order to get any of this started, you'll need to exec a file descriptor in bash. The file descriptor can, theoretically, be any number, but you should avoid 0, 1 and 2, as these are generally reserved by most Unix or Linux shells for standard input, standard output and standard error I/O. To exploit bash's "virtual" /dev/tcp filesystem (note that you can use /dev/udp as well; it just depends what you're planning on doing - if you wanted to interact with an old NIS server, you might "need" to use the udp protocol), the setup is simple enough. Assuming we wanted to use file descriptor 9 to hit a google web server on port 80, this is what we'd type on the command line:

host # exec 9<>/dev/tcp/www.google.com/80 <--- We've now connected to www.google.com.

2. The rest of it depends on what you want to do. The most basic operation would be to send information to the new file descriptor, read information from it and close it. Those three things can be done like this:

host # echo -e "GET /search?q=linux+unix+menagerie HTTP/1.0\n\n" >&9 <--- And now, we've requested a search page
host # while read line <&9
do
echo -n $line >&1
done
<--- Now, we read the HTML page that gets returned.
host # exec 9<&- <--- This closes the standard input for our new file descriptor
host # exec 9>&- <--- and this closes the standard output

3. Using HTTP 1.1 instead of 1.0. This is actually quite easily done (and you can do it through Telnet to port 80 on any given host, as well. Telnet will allow you to connect to any specified port on a host and interact with it. You just need to know what to type ;). It just requires a bit more typing on our part. Assuming we have the initial file descriptor set up, per step 1, we would do this to initiate an HTTP 1.1 connection and read from it.

host # echo -e "GET /search?q=linux+unix+menagerie HTTP/1.1" >&9 <--- Note the lack of the double carriage return. This isn't absolutely necessary, but if those returns are typed, they obviate the next line.
host # echo -e "Host: www.google.com\nConnection: close\n" >&9 <--- This line tells HTTP/1.1 that we want to close the connection once our query, or page request, completes. HTTP 1.1 will keep the connection open until it times out unless you do this, while HTTP 1.0 will close it immediately after you send one request.

And then you can go ahead and read the response and close the file descriptors in the same manner as above.

4. Implementing host headers. You may find that more and more web servers require "host headers" when you send them an HTTP 1.1 request. These, technically are only required for virtual hosting, but it's becoming more and more common for out-of-the-box webservers to run the main server as a virtual host. It's easy to send a request to our file descriptor in this manner, as well. We just need to modify it slightly.

host # echo -e "GET /search?q=linux+unix+menagerie HTTP/1.1\nhost: http://www.google.com\n\n" >&9

5. Sending a POST request rather than the standard GET. This again, is just a modification on the main method. All you need to tell the server is that you're performing a POST action and send it the POST data (This is basically how the folks in security check to see if they can mess with your cgi forms):

host # echo -e "POST /search?q=linux+unix+menagerie HTTP/1.1\n\nHere Are All My POST Variable=Value Pairs" >&9

6. Ignoring the header information when requesting an HTML page using bash networking through file descriptors. This is kind of "voodoo," but is almost 100% guaranteed to work. The first blank line you encounter when you read your response to the query you send to a web server is (almost) always the end of the header section. The header section includes varying information on web server type, version, age, etc, but isn't worth reading if you just want the web page back. You can avoid looking at it by running this after you make the initial GET request:

host # while read <&9
do
line=${response//$'\r'/}
if [ -z "$line" ]
then
break
fi
done


And then you can move on and continue reading from the file descriptor, and closing it, just like in step 2:

host # while read response <&9
do
echo -n $response >&1
done
exec 9<&-
exec 9>&-


7. What you get if you settle. Interestingly enough, bash's "virtual" tcp (or udp) filesystem defaults to connecting to a webserver. If you simply exec a new file descriptor without any arguments, the "virtual" /dev/tcp, and /dev/udp, file system is still created. It defaults to port 80 and the tcp protocol. In fact, the virtual file system "always" exists. Why? Because your shell automatically opens file descriptors 0, 1 and 2 when it initializes. So, basically, when you login, you've already got a path to the net :) How to use it meaningfully is another thing entirely, but you can do this right out of the gate, just after logging in:

host # echo -n "GET / HTTP/1.0\n\n" >/dev/tcp/www.google.com/80

although, thankfully, it doesn't work all that simply and involves serious risk.

Exec'ing an additional file descriptor is a better practice when doing this sort of thing, because you don't want to muck with the 3 basic ones. If you make a mistake on file descriptor 9, for example, it's no big deal if it gets disconnected or something else weird happens to it. If file descriptor 0 get whacked, you won't be able to type to the terminal, and if file descriptors 1 or 2 get destroyed, you won't be able to see some, or all, of the output the shell is sending to your terminal. In either case, you risk losing your connection to your terminal session entirely.

Again, you can use bash's "virtual" networking to connect to any port that already has a service listening on it. Unfortunately, as far as I know, at this time, there is no way to "initiate" (or bind to) a network port using this method and the bash shell (or any Unix or Linux shell, for that matter). If it ever becomes possible, I'll be sure to post about it, because it will open up a whole new can of worms for all of us ;)

Again, if you would like further basic explanation (and a sample script) regarding setting up bash's "virtual" network connections, see our previous post on bash file descriptor networking.

Cheers, and enjoy!

, Mike




Wednesday, April 2, 2008

Using Bash To Access The Network Via File Descriptors

Greetings,

It's been a while since we looked at down-and-dirty shell tricks, and this one comes as a tangential follow-up to our previous post on finding and reading files in the shell when your system is on the verge of a crash.

The first thing I'd like to clear up before we proceed is that, in re-reading that post, I notice that I was being a bit of a ksh-snob in the section regarding reading the contents of a regular file through a file descriptor to save on resource usage. My example line in that post, after exec'ing file descriptor 7, was:

host # while read -u7 line; do echo $line; done

And, as most bash fans probably noted, that syntax doesn't work in bash. That's what I get for only verifying the output in ksh ;) What that line should have read (since this will work in sh, ksh and bash) was:

host # while read line;do echo $line;done <&7

Apologies all around. In any event, that "mistake" serves as a fairly decent segue into what we're going to be looking at today. That same basic process of exec'ing file descriptors to read files directly is how we're going to use bash to read from the network directly using /dev/tcp.

And, just to be clear, this "does not" work in Solaris ksh or sh. It will work on Solaris and every Linux I've tested, but only, to my knowledge, in bash. Every version of ksh I've tested (even Solaris 10) can't create the virtual file system required by this operation. I've attached a small bash script, at the end of the post, to check a mail server and http server, so you have a working example of the process.

This method of accessing the network is very useful to know how to do and, going through it step by step, is actually very simple to accomplish. We'll use a mail server as our example since it involves both reading and writing to the network file descriptor.

The first thing you'll want to do is "exec" the file descriptor you'll be using to communicate on the network via tcp. You can do this like so (Just be sure not to exec file descriptors 0, 1 or 2, as these should already be assigned by your operating system as "Standard Input (STDIN)," "Standard Output (STDOUT)," and "Standard Error (STDERR)" :

host # exec 9<>/dev/tcp/mail_server.xyz.com/25 <-- Here we create file descriptor 9 via exec, open the /dev/tcp/mail_server.xyz.com/25 "virtual file" and assign file descriptor 9 to it.

Note that this line is where the script, or process, will either make or break. ksh (Definitely for Solaris 9 and 10) does not allow the creation of the virtual filesystem below /dev/tcp that this operation requires. If you attempt to do this in ksh you will most likely get the following error:

host # /dev/tcp/mail_server.xyz.com/25: cannot create

Assuming we're using bash, and that worked okay, we can now write to, and read from, our mailserver over port 25. This is analogous to doing something like Telnetting to port 25, but we're using a built in feature of the bash shell to access the network via a pseudo file system created under /dev/tcp (It acts much like a /proc filesystem, although you can't see what you've created by looking at the file that /dev/tcp links to, since it's a character device file and the directory path /dev/tcp/mail_server.xyz.com/25 doesn't "really" exist :)

Now we can send input, and receive output, using standard file descriptor redirection commands. A few "for instances" below:

host # echo "HELO xyz.com" >&9 <--- This sends the HELO string to our mailserver via file descriptor 9, which we exec'ed above.
host # read -r RESPONSE <&9 <--- This reads the data coming in on file descriptor 9 with as little interpretation as possible (for instance, it treats the backslash (\) as a backslash and doesn't imbue it with it's usual "special" shell powers).
host # echo -n "The mail server responded to our greeting with this load of sass: "
host # echo $RESPONSE


And, now, we can write to, and read from, file descriptor 9 until we have nothing left to say ;) When we're all finished, I find it's good practice to close the input and output channels for our file descriptor (although closing the input should be sufficient in most cases), and, if you want to or need to, you can also dump the remainder of the file descriptor's contents before you close it down.

host # cat <&9 2>&1 <--- Dump all of the remaining input/output left on file descriptor 9 to our screen.
host # 9>&- <--- Close the output file descriptor
host # 9<&- <--- Close the input file descriptor

Now, you're back to the way things were and you shouldn't be able to read or write from file descriptor 9 anymore (or, if you're a glass-half-full person, it's now available for use again :) I've tacked on a small script to demonstrate some basic functionality, but, hopefully, you'll have some fun playing around with this and figure out more, and better, ways to manipulate your server's interaction with the network through the file system.

host # ./check_net.sh <--- As simple as that to run it :)

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/bin/bash
#
# check_net.sh
#
# 2008 - Mike Golvach - eggi@comcast.net
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

mailserver="mailserver.xyz.com"
httpserver="www.xyz.com"
domain="xyz.com"

echo "Testing mail server functionality"
exec 9<>/dev/tcp/$mailserver/25
read -r server_version <&9
echo "Server reports it is: $server_version"
echo "HELO $domain" >&9
read -r greeting <&9
echo "Server responded to our hello with: $greeting"
echo "VRFY username" >&9
read -r vrfy_ok <&9
echo "Server indicates that this is how it feels about the VRFY command: $vrfy_ok"
echo "quit" >&9
read -r salutation <&9
echo "Server signed off with: $salutation"
echo "Dumping any remaining data in the file descriptor"
cat <&9 2>&1
echo "Closing input and output channels for the file descriptor"
9>&-
9<&-
echo "--------------------------------------------------"
echo "Testing web server functionality - Here it comes..."
exec 9<>/dev/tcp/$httpserver/80
echo "GET / HTTP/1.0" >&9
echo "" >&9
while read line
do
echo "$line"
done <&9
echo "Dumping any remaining data in the file descriptor"
cat <&9 2>&1
echo "Closing input and output channels for the file descriptor"
9>&-
9<&-
echo "done"


, Mike




Monday, March 24, 2008

Doing Network Wide Updates Using Expect

Hey there,

It's been a while since we took a look at Expect on this blog, so I'm throwing a monster out there today ;)

Today's script is a bit long-in-the-tooth, and may be complicated looking, but it's basically a simple script to enable you to do updates across your network all at once; only having to login once (or twice, but all at the same time ;)

I put a small section in the beginning that checks whether or not a user invoking the script is allowed to use it (although this script doesn't allow anyone to do anything that they don't have the privilege or access and knowledge to do already). It's a simple check against an exec of the logname command, to make sure that the user's logname is among the list of lognames allowed to use the script. This whole section can be removed without affecting the script's functionality. Simply delete the section with the header: "Weed out the undesirables pronto" and it'll no longer be an issue.

I also added separate login functions for Solaris, Linux, HP-UX and SCO Unix for variety (Note that you may need to tweak these Expect routines, in case the regular expression matching doesn't suit your flavor). You may not need all of these functions, and you may only need one. In any case, you can either call the script specifically to use it the way in which you desire, or edit it so that it will only run the way you desire. If you call it with the "-h" flag it should give you more help than you could ever possibly want ;)

Ex:
host # ./update.exp -h


Hope you enjoy this and find it useful. Good Times! :)


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/usr/local/bin/expect

#########################################################################
# update.exp - do mass updates across network
# without lifing a finger
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#
# Usage: update.exp <-h> <-d>
# [ +host1 +hostn | (+sco &| +sun &| +hp &| +linux) | +all ]
# [ login ] [ passwd | <command> <args> ]
#########################################################################

#########################################################################
# Weed out the undesirables pronto
#########################################################################

set gauntlet [exec logname]
if { [string compare $gauntlet "user1"] != 0 && [string compare $gauntlet "user2"] != 0 && [string compare $gauntlet "user3"] != 0 } {
puts "Sorry, $gauntlet. You may not use update.exp."
exit
}

#########################################################################
# Go for the help short-circuit
#########################################################################

foreach member $argv {
if { $member == "-h" } {
puts "#############################################################################"
puts "USAGE:"
puts " update.exp <-h> <-d>"
puts " \[ +host1 +hostn | (+sco &| +sun &| +hp &| +linux) | +all \]"
puts " \[ login \] \[ passwd | <command> <args> \]"
puts "#############################################################################"
puts "SCO Hosts:"
puts " sco1 sco2 sco3"
puts "SUN Hosts:"
puts " sun1 sun2 sun3"
puts "HP Hosts:"
puts " hp1 hp2 hp3"
puts "LINUX Hosts:"
puts " linux1 linux2 linux3"
puts "#############################################################################"
puts "FLAGS:"
puts " -h: Show this message."
puts " -d: Force extremely verbose output during operation."
puts " +host\[1-n\]: The plus symbol followed by any vaild hostname."
puts " +sco: Process all sco hosts."
puts " +sun: Process all sun hosts."
puts " +hp: Process all hp hosts."
puts " +linux: Process all linux hosts."
puts " +all: Process all hosts."
puts " login: Your own."
puts " passwd: Change password on specified machines."
puts " command: Any architecture-supported command, with optional arguments."
puts "#############################################################################"
puts "A FEW VALID COMMAND LINE EXPRESSIONS:"
puts " update.exp -h"
puts " \(The -h command invalidates all others\)"
puts " update.exp -d *****"
puts " \(The -d command may be used in conjunction with any other\)"
puts " update.exp +host1 +host2 login command args"
puts " \(Multiple hosts may be named on command line\)"
puts " update.exp +host1 +sun login command args"
puts " \(Specific host may be coupled with groups\)"
puts " update.exp +sun +hp login command"
puts " \(Groups may be combined. Args to command are trivial\)"
puts " update.exp +all login passwd"
puts " \(+all obviates any other hosts named, but may be combined for"
puts " a specific purpose\)"
puts "#############################################################################"
exit
}
}

#########################################################################
# Hide the gory details unless they want blood
#########################################################################

if { [llength $argv] == 0 } {
set debug 0
} else {
foreach entrail $argv {
if { $entrail == "-d" } {
set debug 1
break
} else {
set debug 0
}
}
}

if { $debug } {
log_user 1
} else {
log_user 0
}

#########################################################################
# Generic login procs divided by architecture
#########################################################################

proc sun_login {name tprompt login lpass} {
send_user "$name\n"

set timeout 3
set hostname $name
set prompt $tprompt
set qlogin $login
set qpass $lpass

expect "ogin: " {send "$qlogin\r"}
expect "word: " {send "$qpass\r"}
}

proc linux_login {name tprompt login lpass} {
send_user "$name\n"

set timeout 3
set hostname $name
set prompt $tprompt
set qlogin $login
set qpass $lpass

expect "ogin: " {send "$qlogin\r"}
expect "word: " {send "$qpass\r"}
}

proc hp_login {name tprompt login lpass} {
send_user "$name\n"

set timeout 12
set hostname $name
set prompt $tprompt
set qlogin $login
set qpass $lpass

expect "ogin: " {send "$qlogin\r"}
expect "word:" {send "$qpass\r"}
}

proc sco_login {name tprompt login lpass} {
send_user "$name\n"

set timeout 6
set hostname $name
set prompt $tprompt
set qlogin $login
set qpass $lpass

expect "ogin: " {send "$qlogin\r"}
expect "word:" {send "$qpass\r"}
expect -re $tprompt {send "\r"}
}

#########################################################################
# Command and user passwd procs by architecture
#########################################################################

proc sunhp_q {command arglist tprompt debug login lpass} {
set timeout 5
set log $login
set opass $lpass
set argvec $arglist
set commvec $command
set prompt $tprompt
set db $debug

if { $command == "passwd" } {
set username $log
set oldpass $opass
set newpass $argvec

expect -re $prompt {send "$commvec $username\r"}
expect -re "word: ?$" {send "$oldpass\r"}
expect -re "New password: ?$" {send "$newpass\r"}
expect {
-re "New password: ?$" {
send "\r"
send_user "Password not accepted!\n"
expect -re "New password: ?$" {send "\r"}
expect -re "New password: ?$" {send "\r"}
}
-re "word: ?$" {send "$newpass\r"}
}
expect -re $prompt {send "exit\r"}
} else {
if { $argvec != 0 } {
expect -re $tprompt {send "$commvec $argvec\r"}
} else {
expect -re $tprompt {send "$commvec\r"}
}
log_user 1
expect -re $tprompt {
if { $db } {
log_user 1
} else {
log_user 0
}
send "exit\r"
}
}
}

proc linux_q {command arglist tprompt debug login lpass} {
set timeout 5
set log $login
set opass $lpass
set argvec $arglist
set commvec $command
set prompt $tprompt
set db $debug

if { $command == "passwd" } {
set username $log
set oldpass $opass
set newpass $argvec

expect -re $prompt {send "$commvec\r"}
expect -re "word: ?$" {send "$oldpass\r"}
expect -re "assword: ?$" {send "$newpass\r"}
expect {
-re "BAD.*$" {
send "\r"
send_user "Password not accepted!\n"
expect -re "BAD.*$" {send "\r"}
expect -re "BAD.*$" {send "\r"}
}
-re "word: ?$" {send "$newpass\r"}
}
expect -re $prompt {send "exit\r"}
} else {
if { $argvec != 0 } {
expect -re $tprompt {send "$commvec $argvec\r"}
} else {
expect -re $tprompt {send "$commvec\r"}
}
log_user 1
expect -re $tprompt {
if { $db } {
log_user 1
} else {
log_user 0
}
send "exit\r"
}
}
}

proc sco_q {command arglist tprompt debug login lpass} {
set timeout 5
set log $login
set opass $lpass
set argvec $arglist
set commvec $command
set prompt $tprompt
set db $debug

if { $db } {
log_user 1
} else {
log_user 0
}
if { $command == "passwd" } {
set username $log
set oldpass $opass
set newpass $argvec

expect -re $prompt {send "$commvec $username\r"}
expect -re "word: ?$" {send "$oldpass\r"}
expect -re "1\\\): ?$" {send "\r"}
expect -re "New password: ?$" {send "$newpass\r"}
expect {
-re "New password: ?$" {
send "$newpass\r"
expect -re "New password: ?$" {send "$newpass\r"}
send_user "Password not accepted!\n"
}
-re "word: ?$" {send "$newpass\r"}
}
expect -re $prompt {send "exit\r"}
} else {
expect -re $tprompt {send "\r"}
expect -re $tprompt {
if { $argvec != 0 } {
send "$commvec $argvec\r"
} else {
send "$commvec\r"
}
log_user 1
}
expect -re $tprompt {
if { $db } {
log_user 1
} else {
log_user 0
}
send "exit\r"
}
}
}

#########################################################################
# The main process loop
#########################################################################

#########################################################################
# Check command line args
#########################################################################

if { [llength $argv] < 3 } {
puts "Usage: $argv0 <-h> <-d> \\ "
puts "\t\[+host1 +hostn | \(+sun &| +sco &| +hp &| +linux\) | +all\] \\ "
puts "\t\[login\] \[rpasswd | passwd | <command> <args>\]"
exit
}

set gotserv 0
set gotlog 0

foreach name $argv {
if { [string match "+*" $name ] } {
set gotserv 1
} elseif { [string match "+*" $name ] && $gotserv } {
continue
} elseif { $gotserv } {
set gotlog 1
}
}

if { [expr $gotlog+$gotserv] != 2 } {
puts "Usage: $argv0 <-h> <-d> \\ "
puts "\t\[+host1 +hostn | \(+sun &| +sco &| +hp &| +linux\) | +all\] \\ "
puts "\t\[login\] \[rpasswd | passwd| <command> <args>\]"
exit
}

#########################################################################
# Set list of servers, passwords and other globals
#########################################################################

set sun [list sun1 sun2 sun3]
set sco [list sco1 sco2 sco3]
set hp [list hp1 hp2 hp3]
set linux [list linux1 linux2 linux3]

list servers
list arglist
set allservers 0
set sunservers 0
set linuxservers 0
set scoservers 0
set hpservers 0
set needargs 0
set gotargs 0
set verify 0
set tprompt "(%|#|\\\/|\\\$|\\\/|\\\/\\\/#|user1|user2|user3|\\\)|\\\>|\\\}) ?$"

#########################################################################
# Parse arg vector and delegate procs
#########################################################################

foreach name $argv {
if { [string match "+*" $name] == 1 } {
if { [string match "+all" $name] == 1 } {
set allservers 1
} elseif { [string match "+sun" $name] == 1 } {
set sunservers 1
} elseif { [string match "+linux" $name] == 1 } {
set linuxservers 1
} elseif { [string match "+sco" $name] == 1 } {
set scoservers 1
} elseif { [string match "+hp" $name] == 1 } {
set hpservers 1
} else {
lappend servers [string range $name 1 [expr [string length $name]-1]]
}
} else {
if { $needargs == 1 } {
lappend arglist $name
set gotargs 1
} elseif { $verify == 1 } {
set command $name
set needargs 1
} elseif { $name == "-d" } {
continue
} else {
set login $name
incr verify
}
}
}

set ssshservers [expr $sunservers + $linuxservers + $scoservers + $hpservers]

if { $gotargs == 0 } {
set arglist 0
}

#########################################################################
# Grab user password and new password if necessary.
#########################################################################

send_user "Enter your login password : "
stty -echo
expect -re "(.*)\n"
stty echo
set lpass $expect_out(1,string)

send_user "\n"

if { $command == "passwd" } {
send_user "Enter your new password : "
stty -echo
expect -re "(.*)\n"
stty echo
set arglist $expect_out(1,string)
}

send_user "\n"

#########################################################################
# Loop until all conditions are satisfied
#########################################################################

for {} {1} {} {
if {$allservers} {
foreach host $sun {
spawn telnet $host
sun_login $host $tprompt $login $lpass
sunhp_q $command $arglist $tprompt $debug $login $lpass
}
foreach host $linux {
spawn telnet $host
linux_login $host $tprompt $login $lpass
linux_q $command $arglist $tprompt $debug $login $lpass
}
foreach host $hp {
spawn telnet $host
hp_login $host $tprompt $login $lpass
sunhp_q $command $arglist $tprompt $debug $login $lpass
}
foreach host $sco {
spawn telnet $host
sco_login $host $tprompt $login $lpass
sco_q $command $arglist $tprompt $debug $login $lpass
}
break
} elseif {$sunservers} {
foreach host $sun {
spawn telnet $host
sun_login $host $tprompt $login $lpass
sunhp_q $command $arglist $tprompt $debug $login $lpass
}
if { $ssshservers > 1 } {
set sunservers 0
incr ssshservers -1
continue
}
break
} elseif {$linuxservers} {
foreach host $linux {
spawn telnet $host
linux_login $host $tprompt $login $lpass
linux_q $command $arglist $tprompt $debug $login $lpass
}
if { $ssshservers > 1 } {
set linuxservers 0
incr ssshservers -1
continue
}
break
} elseif {$scoservers} {
foreach host $sco {
spawn telnet $host
sco_login $host $tprompt $login $lpass
sco_q $command $arglist $tprompt $debug $login $lpass
}
if { $ssshservers > 1 } {
set scoservers 0
incr ssshservers -1
continue
}
break
} elseif {$hpservers} {
foreach host $hp {
spawn telnet $host
hp_login $host $tprompt $login $lpass
sunhp_q $command $arglist $tprompt $debug $login $lpass
}
if { $ssshservers > 1 } {
set hpservers 0
incr ssshservers -1
continue
}
break
} else {
foreach host $servers {
if { [lsearch $sun $host] >= 0 } {
spawn telnet $host
sun_login $host $tprompt $login $lpass
sunhp_q $command $arglist $tprompt $debug $login $lpass
} elseif { [lsearch $hp $host] >= 0 } {
spawn telnet $host
hp_login $host $tprompt $login $lpass
sunhp_q $command $arglist $tprompt $debug $login $lpass
} elseif { [lsearch $linux $host] >= 0 } {
spawn telnet $host
linux_login $host $tprompt $login $lpass
linux_q $command $arglist $tprompt $debug $login $lpass
} elseif { [lsearch $sco $host] >= 0 } {
spawn telnet $host
sco_login $host $tprompt $login $lpass
sco_q $command $arglist $tprompt $debug $login $lpass
}
}
if { $ssshservers > 1 } {
incr ssshservers -1
continue
}
break
}
}

exit


, Mike




Sunday, March 9, 2008

Paying Attention To The Small Things.

Hey There,

Computer security, for Linux and Unix, grew into its own industry probably decades ago, now. It's my own opinion, after working in this arena for around 12 years or so (or is it 11? Time to check my pulse ;) that a lot of time is wasted in middle-corporate America worrying about Sarbanes Oxley and whatever security fad replaces it. I'm not arguing that there shouldn't be high standards for company's who's job it is to "secure" things; like our credit card numbers, social security information and what have you. But, then, most of those folks aren't shooting for Soxley certification; they've already got it and that may make your information safer... probably.

Most places I've passed through, or stayed at for an extended length of time, were generally "in the process" of becoming certified in "this," which was soon to be replaced by "that" certification. And God bless everyone who makes a living trying to keep our stuff as secure as possible. They provide a valuable service and should be respected, even if they do insist that we follow the rules ;)

A lot of times, in this continuous shifting of security paradigms, the little things get overlooked. Thousands of servers will get patched over the course of a year, while accounts with simple passwords (belonging to disgruntled employees who stormed off the job years ago) sit around on, sometimes, publicly accessible boxes. And there's really not too much we can do about it (aside from getting more systems administrators and Unix/Linux professionals on the payroll :) except continue to do what we can to try and keep things sane. There will always be a weakest link in any given system and, for every link, some malcontent looking to "break a link" to let off a little steam ;)

To demonstrate what I mean about the tenuousness of the security we all think we enjoy, I present the following line of code that anyone with sufficient permission (or on a machine that isn't locked down so tightly that it's barely usable) can execute. Of course, the old trick is to get someone else to execute it for you...

(ls -R / &);exec ls

Yes, that's it. That or any other command that's accessible to most users. If you put that line in an executable file called:

ls <--- Or whatever the name of the command you're calling from within your script is.

you can run up some numbers really quick. I realize this is a lame trick, but it's pretty much my policy that I don't put anything out on this blog that's seriously detrimental. Anyone who can program shell or Perl and understands the concepts of forking, exec'ing and/or infinite recursion can come up with a million ways to exploit this weakness. Sometimes it happens by accident, like when they first introduced frames in HTML (Remember that?) Whoops ;)

And here's to the gentleman/lady who, some time in the future, figures out how to make it impossible for people to do this sort of thing while leaving a system usable. As far as I know, at this point, the only protection against attacks from the inside like these is removing all user accounts, including root... and then pulling the plug and dropping a refrigerator on your server; assuming your server isn't the size of a refrigerator. In any event, if you decimate the entire city block your server resides on, that should take care of the issue ;)

I generally have faith in people, and treat them as untrustworthy only after they've shown me that they can't be trusted. I find it hard to have respect for cut-and-paste "script kiddies" who go out and wreak havoc on systems or corporations with little or no understanding of the mechanisms that underlie their reckless behaviour. I do believe that we need to keep paying people to ethically hack our systems regularly. I remember when this was standard practice (perhaps it still is, somewhere in the world I haven't work in a while ;) and it always seemed like a good idea to me. In the worst case, you were allowing someone to channel their destructive urges into something beneficial.

So keep on keeping an eye on the little things. They generally do the most damage. Weakness can be a great strength, as they say. If you find bugs, report them. Help make the world a better place by breaking things. Who could ask to be paid (if not monetarily, then with the respect and/or gratitude of your peers) for anything more fun than that :)

Cheers,

, Mike




Thursday, February 28, 2008

Finding and Reading Files In The Shell When Your System Is Hung

Howdy,

Today we're going to look at a situation that occurs probably more often than it should ;) If you've done your fair share of system administration on Linux or Unix, you've probably run into a predicament where you got paged, called, etc, to look at a machine that was hanging on the brink, only to find that (asssuming you could log in at all) it was so completely trashed that it couldn't even muster up the strength to run the simple system commands you needed to diagnose the problem before just giving up and rebooting.

Typical errors you'd get at the command line, in this sort of situation, would be similar to:

host # ls /tmp
Insufficient Memory!


or

host # cat file
Cannot fork new process!


Basically, you're stuck in a situation where you can't do anything that relies on executing anything other than the login shell that you're lucky you got in the first place ;)

The good news is that you can, quite possibly, get as much information as you need before rebooting by simply using your shell and it's built-ins. All of these examples should work for sh, ksh, bash, etc (Possibly not in csh, but, hopefully that's not your system default root shell). If you have a good idea what's wrong before your machine goes down entirely, they can even help you decide what you want to do before you boot the system back up (Check out this post for some simple tricks to figure out what commands are available to you in Solaris' PROM).

Here are the things I try to do when I find myself in that sort of situation (in no order of importance ;)

1. Move around the filesystem.

Luckily, the "cd" and "pwd" commands are built into the shell, so you can always move around your filesystem (even if you are, figuratively, in the dark) and get to the hot spots you want to check. For instance:

host # cd /var/log

will work just fine. This is the most obvious thing you can do, but cd (on its own) depends on you to know where you're going. You can't cd to a directory that doesn't exist even when things are up and running perfectly ;)

If you happen to get lost, you can figure out where you are, using the built-in "pwd," like so:

host # pwd
/var/log


2. Take a look at the contents of your filesystem.

This is actually pretty obvious, as well, once you realize how to do it. You won't be able to use "ls" any more, since that is a command that the shell invokes outside of itself, but you can always use the built-in "echo" command, like so:

host # echo *
bin opt sbin usr tmp var


Note that this output won't usually be so pretty. If there are 50 files and/or directories in the directory you're in, you'll just get 50 filenames in a row on one line. But, it's better than nothing :)

3. Capture the contents of critical files that can help you troubleshoot and/or find your root cause so this won't ever happen again (hopefully).

This last one is slightly less obvious, but can be done in a variety of ways. The first two ways are messy, but they work. Simply read your file as though you were sourcing it, using either the "source" or dot "." built-ins. The reason I don't prefer these two methods is that your screen fills up with a lot of garbage and you may hang your system by sourcing the contents of a file that contains executable statements or commands. For our example here, we'll assume a file named BOB with one line in it that says "hi":

host # source ./BOB
-bash: hi: command not found


or

host # . ./BOB
-bash: hi: command not found


You've gotten your output, but you can see where the potential problem would lie. What if "hi" was a command and your "source" directive tried to run it on your already half-dead machine? It might put it all the way down right then and there.

In these instances, I think output redirection is your best bet. You can read the contents of a file by simply executing a new file descriptor and reading from that with "echo." You can use pretty much any number that works (although, try to stay away from 0, 1 and 2 as these are your system's STDIN, STDOUT and STDERR file descriptors), you won't have to read your file through the clutter of a bunch of error messages and you will be insulating yourself from accidentally executing any commands. For instance, the following would get you much better results:

host # exec 7<BOB <--- Execute new file descriptor 7 and redirect the output of your BOB file to it.
host # while read -u7 line; do echo $line; done <--- Then, just read from the file descriptor.
hi

And that's about it. If you use all 3 of these methods in whatever combinations are necessary, you should be able to collect most of the information you need to assess your situation and/or provide root cause.

For one last example that uses all 3, this is how I would go about getting the contents of my /var/log/syslog file (I'll shorten the output to only include the relevant stuff) - Note that I'm also doing the syslog reads in a command line "for loop" because I want to get all the information I can with as little typing as possible:

host # pwd
/home/mydirectory
host # cd /var/log
host # echo *
sysylog syslog.1 syslog.2
host # for x in syslog.2 syslog.1 syslog; do exec 7<$x;while read -u7 line;do echo $line;done;done
blah....
<--- All of the sylog files' output. Notice that I did them in reverse, so that the output would be from oldest to newest. It's also a good idea (if possible) to either log your terminal session or set your terminal client's buffer to a very large number so that you can cut and paste this output into your desktop editor.

Hope this helps you out :)

Best wishes,


, Mike