CHAPTER 7
PROGRAMMING FOR SECURITY PROFESSIONALS

After reading this chapter and completing the activities, you will be able to:

Image Explain basic programming concepts

Image Write a simple C program

Image Explain how Web pages are created with HTML

Image Describe and create basic Perl programs

Image Explain basic object-oriented programming concepts

As a security professional, you need to know how both hackers and security testers use computer programming. This chapter describes the basic skills of programming. You won’t be an expert programmer after this chapter, but you’ll have a clearer idea of how programs are written. Removing the mystique eliminates the fear many networking professionals experience when hearing the word “programming.” Having a basic understanding of programming can also help you in developing custom security tools or modifying existing tools when you’re conducting security tests. In fact, most security tester positions require being able to create customized security tools. Just as a good carpenter knows how to modify a tool to fit a special job, security testers should know how to modify computer tools created for one purpose so that they can be used for other functions.

This chapter gives you a general overview of C, HTML, and Perl. Becoming a programmer takes a lot of time and practice, but this chapter gives you an opportunity to examine some programs and practice writing a couple yourself.

INTRODUCTION TO COMPUTER PROGRAMMING

Just as book editors must understand the rules and syntax of the English language, computer programmers must understand the rules of programming languages and deal with syntax errors. A command’s syntax must be exact, right down to the placement of semicolons and parentheses. One minor mistake and the program won’t run correctly, or even worse, it produces unpredictable results. Being a programmer takes a keen eye and patience; keep in mind that errors aren’t unusual the first time you try to create a program.

Unfortunately, most colleges don’t teach programming with security in mind. Many current attacks on operating systems and applications are possible because of poor programming practices. Mary Ann Davidson, Oracle’s chief security officer (CSO), speaks all over the world on this topic. She argues that software developers focus on “cool technology” and the latest programming languages. “They don’t think like attackers,” she stated to an audience filled with more than 1000 information assurance professionals. “Nor is there a requirement for software developers to demonstrate proficiency in safe, secure programming as a condition of matriculation,” she added.

Details on this issue are beyond the scope of this book, but if you decide to pursue programming or software engineering as a major, urge the college you’re attending to cover this important topic. Oracle’s CSO offered some suggestions to change the higher education system. She believes security should be part of every computer science class, “not just in a single class that students file and forget,” and textbooks should be written to emphasize security more. Grades should be based in part on the “hackability” of code students submit for assignments, and students should be required to use automated tools to find vulnerabilities in their coding. Security must be integrated into any software engineering project from its inception, not after the fact.

This chapter’s intention is to whet your appetite and give you an overview of programming. To begin, take a look at some programming fundamentals in the following section.

Programming Fundamentals

Manuals filled with a programming language’s syntax and commands can take up a lot of space on your shelves, but you can learn some basics in any programming language without consulting manuals. In fact, you can begin writing programs with just a little knowledge of some programming fundamentals, which you can remember with the acronym BLT (as in bacon, lettuce, and tomato): branching, looping, and testing.

Branching, Looping, and Testing (BLT)

Most programming languages have a way to branch, loop, and test. For example, a function in a C program can branch to another function in the program, perform a task there, and then return to its starting point. A function is a mini program within the main program that carries out a task. For example, you can write a function that adds two numbers and then returns the answer to the function that called it. Branching takes you from one area of a program (a function) to another area. Looping is the act of performing a task over and over. The loop usually completes after testing is conducted on a variable and returns a value of true or false. Although you don’t need to worry about the syntax for now, examine the following program to see where it uses branching, looping, and testing:

main()
{
     int a = 1 /* Variable initialized as integer, value 1 */
     if (a > 2) /* Testing whether “a” is greater than 2 */
           printf("A is greater than 2");
     else
           GetOut(); /* Branching: calling a different function */
           GetOut() /* Do something interesting here */
     {
           for(a=1; a<11; a++) /* Loop to display 10 times */
           {
           printf("I'm in the GetOut() function");
           }
     }
}

There you have it: the BLT of computer programming. Of course, there’s a lot more to learn in programming, but by knowing how to do these three actions, you can examine a program and understand its functionality.

A program contains different functions, or modules, that perform specific tasks. Say you’re writing a program for making a BLT sandwich. The first step is to list the tasks in this process. In computer lingo, you’re writing an algorithm (a recipe) to make a BLT sandwich. You keep an algorithm as simple as possible, but creating an algorithm is one of the most important programming skills to master.

Skipping a step in an algorithm can cause problems. For example, not rinsing the lettuce might result in a bug in your sandwich. Similarly, not reviewing your program’s code carefully might result in having a bug in your program—an error that causes unpredictable results. Bugs are worse than syntax errors because a program can run successfully with a bug, but the output might be incorrect or inconsistent. Performing tasks in the incorrect order might also create havoc. For example, putting mayonnaise on the bread before toasting it can result in soggy toast. The following list is an example of an algorithm for making a BLT sandwich:

Image Purchase the ingredients.

Image Gather all the utensils needed for making the sandwich.

Image Clean the tomatoes and lettuce.

Image Slice the tomatoes and separate the lettuce leaves.

Image Fry the bacon.

Image Drain the bacon.

Image Toast the bread.

Image Put mayonnaise on the toast.

Image Put the fried bacon, sliced tomato, and lettuce leaves on the toast.

Image Join the two slices of toasted bread.

A programmer would then convert this algorithm into pseudocode. Pseudocode isn’t a programming language; it’s an English-like language you can use to help create the structure of your program. The following example is the pseudocode that addresses purchasing all the ingredients needed for a BLT sandwich before you write the programming code:

PurchaseIngredients Function
     Call GetCar Function
     Call DriveToStore Function
     Purchase Bacon, Bread, Tomatoes, Lettuce, and Mayonnaise at store
End PurchaseIngredients Function

After writing pseudocode, you can then begin writing your program in the language of your choosing. Are outlining an algorithm and writing pseudocode necessary for every computer program you write? No. If the program you’re writing has very few lines of code, you can skip these steps, but for beginning programmers, these two steps are helpful.

Documentation

When writing any program, documenting your work is essential. To do this, you add comments to the code that explain what you’re doing. Documentation not only makes your program easier for someone else to modify; it also helps you remember what you were thinking when you wrote the program. The phrase “No comment” might be appropriate for politicians or Wall Street investors with inside trading information, but not for programmers.

Although documentation is important, many programmers find it time consuming and tedious. Often they think their code is self-explanatory and easy enough for anyone to maintain and modify, so documenting their work isn’t necessary. You’ll soon discover, however, that without good documentation, you won’t understand the lines of code you wrote three weeks ago, let alone expect a stranger to figure out your train of thought. For example, the following comments can help the next programmer understand why a new function was added to an existing program:

// The following function was added to the program June 15, 2010
// per a request from the Marketing Department.
// It appears that reports generated by the sales() function were
// not giving the marketing folks information about sales in Asia.
// This new function now uses data from text files from the offices
// in Tokyo and Hong Kong. - Bob C. Twins

Software engineering companies don’t retain programmers who don’t document their work because they know that 80% of the cost of software projects is maintenance. They also know that an average of one bug for every 2000 lines of code is the industry standard. For example, Windows Vista contains almost 50 million lines of code, but Microsoft software engineers, partly because of strict documentation rules, were able to limit bugs to fewer than the average. In general, Microsoft is below the industry standard on the average number of bugs. With bugs being so prevalent in many programs, however, it’s easy to see how attackers can discover vulnerabilities in software. Programmers can easily overlook problems in thousands of lines of code that might create a security hole attackers can exploit.

Activity 7.1: Writing Your First Algorithm


Time Required: 10 minutes

Objective: Learn to write an algorithm.

Description: Programmers must be able to think logically and approach problem solving in logical steps or tasks. Missing a step can have disastrous effects, so you should train yourself to think in a structured, logical way. A good way to test whether you can follow a step-by-step approach is by doing exercises that encourage you to think in this manner. For this activity, list at least 10 steps for making scrambled eggs. When writing the steps, make sure you don’t take anything for granted. Assume someone with no knowledge of cooking—or even of eggs—will try to follow your algorithm.


LEARNING THE C LANGUAGE

Many programming languages are available to security testers. You’ll begin your journey with an introduction to one of the most popular programming languages: C, developed by Dennis Ritchie at Bell Laboratories in 1972. The C language is both powerful and concise. In fact, UNIX, which was first written in assembly language, was soon rewritten in C. Not many programmers want to write programs in binary (machine code) or machine language, so assembly language was developed. It uses a combination of hexadecimal numbers and expressions, such as mov, add, and sub, so writing programs in this language is easier than in machine language.

This chapter gives you a basic overview of the C language. At many colleges, an entire course is devoted to learning this language; others skip C and teach C++, an enhancement of the C language. Many security professionals and hackers still use C because of its power and cross-platform usability.

A compiler is a program that converts a text-based program, called source code, into executable or binary code. Table 7.1 lists some available C compilers. Most C compilers can also create executable programs in C++. The Intel and Microsoft compilers must be purchased, but many other compilers are free and can be found with an Internet search.

Table 7.1 C language compilers

Image

Note


What’s dangerous about C is that a beginner can make some big blunders. For example, a programmer can write to areas of memory that cause damage to the OS kernel or, even worse, write a program that allows a remote user to write to areas of memory. Usually, what’s written is executable code that might give an attacker a backdoor into the system, escalate an attacker’s privileges to that of an administrator, or simply crash the program. This type of attack is usually possible because the programmer didn’t check users’ input. For example, if users can enter 300 characters when prompted to enter their last names, an attacker can probably enter executable code at this point of the program. When you see the term “buffer overflow vulnerability,” think “poor programming practices.” Keep in mind that although C is easy to learn and use, errors in using it can result in system damage.


Anatomy of a C Program

Many veteran programmers can’t think of the C language without remembering the “Hello, world!” program, the first program a C student learns:

/* The famous "Hello, world!" C program */

#include <stdio.h> /* Load the standard IO library. The library contains functions your
C program might need to call to perform various tasks. */

main()
{
     printf("Hello, world!

");
}

That’s it. You can write these lines of code in almost any text editor, such as Notepad if you’re using Windows or the vi editor if you’re using Linux. The following sections explain each line of code in this program.

Many C programs use the /* and */ symbols to comment large portions of text instead of using the // symbols for one-line comments. For example, you can type the /* symbols, add as many lines of comment text as needed, and then type the closing */ symbols. Forgetting to add the */ at the end of comment text can cause errors when compiling the program, so be careful.

The #include statement is used to load libraries that hold the commands and functions used in your program. In the Hello, world! example, the #include <stdio.h> statement loads the stdio.h library, which contains many C functions.

The parentheses in C mean you’re dealing with a function. C programs must contain a main() function, but you can also add your own functions to a C program. Note that after the main() function, an open brace (the { symbol) is on a line by itself. Braces show where a block of code begins and ends. In the Hello, world! program, the closing brace indicates the end of the program. Forgetting to add a closing brace is a common mistake.

Table 7.2 Special characters for use with the printf() function

Image

Inside the main() function, the program calls another function: printf(). When a function calls another function, it uses parameters, also known as arguments. Parameters are placed between opening and closing parentheses. In this example, the parameters ”Hello, world! ” are passed to the printf() function. The printf() function then displays (prints) the words “Hello, world!” onscreen, and the characters add two new lines after the Hello, world! display. Table 7.2 lists some special characters that can be used with the printf() function.

Declaring Variables

A variable represents a numeric or string value. For example, you can solve x + y = z if you know two of the variable values. In programming, you can declare variables at the beginning of a program so that calculations can be carried out without user intervention. A variable might be defined as a character or characters, such as letters of the alphabet, or it can be assigned a numeric value, as in the expression int x = 1. Table 7.3 shows some variable types used in C.

If the printf() function contains values other than a quoted sentence, such as numbers, you need to use conversion specifiers. A conversion specifier tells the compiler how to convert the value in a function. For example, printf(“Your name is %s!”, name) displays the following if you have assigned the value Sue to the string variable called name:

Your name is Sue!

Table 7.4 lists conversion specifiers for the printf() function.

In addition to conversion specifiers, programmers use operators to compare values, perform mathematical calculations, and the like. Most likely, programs you write will require calculating values based on mathematical operations, such as addition or subtraction. Table 7.5 describes mathematical operators used in C.

Table 7.3 Variable types in C

Image

Table 7.4 Conversion specifiers in C

Image

You might also need to test whether a condition is true or false when writing a C program. To do that, you need to understand how to use relational and logical operators, described in Table 7.6.

Using compound assignment operators as a sort of shorthand method, you can perform more complex operations with fewer lines of code. For example, TotalSalary += 5 is a shorter way of writing TotalSalary = TotalSalary + 5. Similarly, TotalSalary= 5 means the TotalSalary variable now contains the value TotalSalary5.

Table 7.5 Mathematical operators in C

Image

Table 7.6 Relational and logical operators in C

Image

Tip


Many beginning C programmers make the mistake of using a single equal sign (=) instead of the double equal sign (==) when attempting to test the value of a variable. A single equal sign (the assignment operator) is used to assign a value to a variable. For example, a = 5 assigns the value 5 to the variable a. To test the value of variable a, you can use the statement if (a == 5). If you mistakenly write the statement as if (a = 5), the value 5 is assigned to the variable a, and then the statement is evaluated as true. This happens because any value not equal to zero is evaluated as true, and a zero value is evaluated as false.


Although this chapter covers only the most basic elements of a program, with what you have learned so far, you can write a C program that displays something onscreen. Security testers should gain additional programming skills so that they can develop tools for performing specific tasks, as you see in “Understanding Perl” later in this chapter.

Branching, Looping, and Testing in C

Branching in C is as easy as placing a function in your program followed by a semicolon. The following C code does nothing, but it shows you how to begin writing a program that can be developed later. For example, in the following code, the prompt(); statement (indicated by the semicolon at the end) at the beginning branches to go to the prompt() function:

main()
{
     prompt();         //Call function to prompt user with a question
     display();        //Call function to display graphics onscreen
     calculate();      //Call function to do complicated math
     cleanup();        //Call function to make all variables equal to
                       //zero
     prompt()
     {
     [code for prompt() function goes here]
     }
     display()
     {
     [code for display() function goes here]
     }
     [and so forth]
}

When the program runs, it branches to the prompt() function and then continues branching to the functions listed subsequently. By creating a program in this fashion, you can develop each function or module one at a time. You can also delegate writing other functions to people with more experience in certain areas. For example, you can have a math wizard write the calculate() function if math isn’t your forte.

C has several methods for looping. The while loop is one way of having your program repeat an action a certain number of times. It checks whether a condition is true, and then continues looping until the condition becomes false. Take a look at the following example (with the important code bolded) and see whether you can understand what the program is doing:

main()
{
     int counter = 1; //Initialize (assign a value to)
     //the counter variable

     while (counter <= 10) //Do what's inside the braces until false
    {
           printf("Counter is equal to %d
", counter);
           ++counter; //Increment counter by 1;
    }
}

Figure 7.1 shows the output of this program. In this example, when the counter variable is greater than 10, the while loop stops processing, which causes printf() to display 10 lines of output before stopping.

The do loop performs an action first and then tests to see whether the action should continue to occur. In the following example, the do loop performs the print() function first, and then checks whether a condition is true:

Figure 7.1
A while loop in action

Image

Courtesy Course Technology/Cengage Learning


main()
{
     int counter = 1;           //Initialize counter variable
     do
     {
           printf("Counter is equal to %d
", counter);
           ++counter;           //Increment counter by 1
     } while (counter <= 10) ;  //Do what's inside the braces
                                //until false }

Note


Which is better to use: the while loop or the do loop? It depends. The while loop might never execute if a condition isn’t met. A do loop always executes at least once.


The last loop type in C is the for loop, one of C’s most interesting pieces of code. In the following for loop, the first part initializes the counter variable to 1, and then the second part tests a condition. It continues looping as long as the counter variable’s value is equal to or less than 10. The last part of the for loop increments the counter variable by 1. Figure 7.2 shows an example of a for loop.

for (counter = 1;counter <= 10;counter++);

You might see some C programs with a for loop containing nothing but semicolons, as in this example:

for (;;)
{
      printf("Wow!");
}

This code is a powerful, yet dangerous, implementation of the for loop. The for (;;) tells the compiler to keep doing what’s in the brackets over and over and over. You can create an endless loop with this statement if you don’t have a way to exit the block of code that’s running. Usually, a programmer has a statement inside the block that performs a test on a variable, and then exits the block when a certain condition is met.

Figure 7.2
A for loop

Image

Courtesy Course Technology/Cengage Learning

Activity 7.2: Learning to Use the GNU GCC Compiler


Time Required: 30 minutes

Objective: Learn how to use the GNU GCC compiler included with most *nix operating systems.

Description: In the past, programmers had to read through their code line by line before submitting the job to the mainframe CPU. The job included all the commands the CPU would execute. If a program was full of errors, the mainframe operator notified the programmer, who had to go through the code again and fix the errors. With today’s compilers, you can write a program, compile it, and test it yourself. If the compiler finds errors, it usually indicates what they are so that you can correct the code and compile the program again. In this activity, you create a C program that contains errors and try to compile the program. After seeing the errors generated, you correct the program and then recompile it until you get it right.

1. Boot your computer into Linux with the BackTrack files, and then start KDE by typing startx and pressing Enter. To view information on using the GCC compiler, open a Konsole shell, type man gcc, and press Enter.

2. Scroll through the manual by using the spacebar. As you can see, the manual contains more than enough information for learning how to use this compiler. Exit the man page when you’re finished.

3. At the shell prompt, type vi syntax.c and press Enter to use the vi editor.

4. To activate the screen, press Esc and type i.

5. Type the following code, pressing Enter after each line:

main()
{
     int age
     printf("Enter your age: ");
     scanf("%d", &age);
     if (age > 0)
     {
     printf("You are %d years old
", age);
     }
}

6. Exit and save the file by pressing Esc and then pressing : (a colon). At the : prompt, type wq and press Enter.

7. To compile the program, type gcc -o syntax.o -c syntax.c and press Enter. The -o and -c switches tell the compiler to compile and create an output file called syntax.o. The compiler returns an error (or several errors) similar to the one in Figure 7.3. The error varies depending on the compiler version you use. In any event, you should be warned that there was a syntax error before printf()because there was no semicolon after the int age statement.

Figure 7.3
Example of a syntax error

Image

Courtesy Course Technology/Cengage Learning

Note


If there are no errors in the source code you created, you get a shell prompt.


Tip


Sometimes you can correct an error easily by looking at the line number of the first error detected.


8. To correct the missing semicolon error, you can use the vi editor again. Type vi syntax.c and press Enter. Press Esc and then type a to enter Append mode. Add a semicolon to the end of the line containing the variable declaration int age.

9. Save and exit the program.

10. Compile the program again by typing gcc -c syntax.c -o syntax.o and pressing Enter. (You can also use the up arrow key to return to previous commands.)

11. At the shell prompt, type gcc -o syntax.exe syntax.o and press Enter.

12. If you entered everything correctly, you should be at the shell prompt. To run the program, type ./syntax.exe and press Enter.

13. Log off the BackTrack session for the next activity.

Security Bytes


There are two schools of thoughts on how to handle syntax errors. Many programmers believe the compiler should check for errors in their code and spend little time reading and stepping through their programs, looking for syntax or logic errors. They just compile it and see what errors pop up. Others refuse to compile the program until they have examined the code thoroughly and are confident it’s accurate and syntactically correct. For beginning programmers, examining the code carefully before compiling helps make you a better programmer. You’ll increase your skills and develop the keen eye needed to spot a missing brace or semicolon.



UNDERSTANDING HTML BASICS

HTML is a markup language used mainly for indicating the formatting and layout of Web pages, so HTML files don’t contain the kind of programming code you see in a C program. As a security professional, you should understand basic HTML syntax because it’s still the basis of Web development. No matter what language is used to create Web pages, HTML statements are used, so knowing HTML is the foundation for learning other Web languages.

Security professionals often need to examine Web pages and recognize when something looks suspicious. You should understand what HTML’s limitations are, be able to read an HTML file, and have a basic understanding of what’s happening. This section isn’t going to make you a Web developer, but it does introduce some HTML basics so that you have a foundation for exploring and learning other programming and scripting languages.

Note


Today, many Web sites use Extensible Markup Language (XML). Although this language isn’t covered in this book, it’s a good one to study if you want to specialize in Web security. Learning additional Web-development languages, such as Extensible HTML (XHTML; see www.w3c.org for more information), Perl, JavaScript, and PHP, can also enhance your skills as a security professional.


Creating a Web Page with HTML

You can create an HTML Web page in Notepad and then view it in a Web browser. Because HTML is a markup language, not a programming language, it doesn’t use branching, looping, or testing. The following is a simple example of HTML code:

<!--This is how you add a comment to an HTML Web page-->
<HTML>
<HEAD>
<TITLE>Hello, world--again</TITLE>
</HEAD>
<BODY>
This is where you put page text, such as marketing copy for an e-commerce business.
</BODY>
</HTML>

The < and > symbols denote HTML tags, which act on the data they enclose. Notice that each tag has a matching closing tag that includes a forward slash (/). For example, the <HTML> tag has the closing tag </HTML>, as do the <HEAD>, <TITLE>, and <BODY> tags. Most HTML Web pages contain these four tags. Table 7.7 describes some common formatting tags used in an HTML Web page.

There are more tags for formatting tables and lists, but this table gives you a general overview of HTML tags. You can find many references to learn more about creating HTML Web pages (refer to Appendix B). In Activity 7.3, you get a chance to practice creating a Web page, using Notepad as the editor.

Table 7.7 HTML formatting tags

Image

Activity 7.3: Creating an HTML Web Page


Time Required: 30 minutes

Objective: Create an HTML Web page.

Description: As a security tester, you might be required to view Web pages to check for possible Web security issues. A basic knowledge of HTML can help you with this task. In this activity, you create a simple HTML Web page and then view it in your Web browser.

1. Start your computer in Windows. Click Start, type notepad MyWeb.html in the Start Search text box, and press Enter. (In Windows XP and earlier, click Start, Run, type notepad MyWeb.html in the Open text box, and press Enter.) If you’re prompted to create a new file, click Yes.

2. In the new Notepad document, type the following lines, pressing Enter after each line:

<!--This HTML Web page has many tags-->
<HTML>
<HEAD>
<TITLE>HTML for Security Testers</TITLE>
</HEAD>

3. Type the next two lines, pressing Enter twice after each line:

<BODY>
<H2>Security Tester Web Site</H2>

4. Type <P><B> There are many good Web sites to visit for security testers. For vulnerabilities click </B> and press Enter.

5. Type <A HREF=HTTP://www.cve.mitre.org><FONT COLOR=red>here!</FONT></A> and press Enter.

6. Type </P> and press Enter.

7. Type <BR><FONT SIZE=-1>Copyright 2010 Security Testers, Incorporated. </FONT><BR> and press Enter.

8. Type </BODY> and press Enter. On the last line, type </HTML> to end your code.

9. Verify that you have typed everything correctly. Your file should look similar to Figure 7.4. When you’re done, save the file.

10. To test whether you have created the Web page correctly, start your Web browser, and click File, Open from the menu. In the Open dialog box, click Browse, navigate to the default location (typically C:Documents and SettingsUser), and click the MyWeb.html file you created. Click Open and then click OK. Your Web page should look like the one in Figure 7.5 if you entered the information correctly.

11. Click the here! hyperlink you created to check whether you’re sent to the correct Web site. If not, make corrections to your HTML code.

12. When you’re finished, exit your Web browser, but leave Windows running for the next activity.

Figure 7.4
HTML source code

Image

Courtesy Course Technology/Cengage Learning

Figure 7.5
An HTML Web page

Image

Courtesy Course Technology/Cengage Learning


UNDERSTANDING PERL

Many scripts and programs for security professionals are written in Practical Extraction and Report Language (Perl), a powerful scripting language. In fact, Perl is the next language of choice after C for both hackers and security professionals. In this section, you see why this language is so popular, examine the syntax of the language, and practice writing Perl scripts. You also create a utility for examining the configuration of a Windows computer.

Background on Perl

Perl, developed by Larry Wall in 1987, can run on almost any platform, and *nix-based OSs invariably have Perl installed already. The Perl syntax is similar to C, so C programmers have few difficulties learning Perl. Table 7.8 is a brief timeline of this language. For more details, visit http://history.perl.org/PerlTimeline.html.

Table 7.8 Perl timeline

Image

Hackers use Perl to create automated exploits and malicious bots, but system administrators and security professionals use it to perform repetitive tasks and conduct security monitoring. Before examining the Perl syntax, in Activity 7.4 you download and install Perl and write your first Perl script. As with any programming language, the best way to learn Perl is by using it.

Activity 7.4: Installing ActivePerl for Windows and Writing a Perl Script


Time Required: 60 minutes

Objective: Install ActivePerl 5.10 and write a Perl script.

Description: Security professionals and hackers alike use the Perl scripting language. Many hacking programs are written in Perl, so any skills you develop in this language will help you in your career. In this activity, you install a version of Perl for Windows and write a basic Perl script. (Note: The version of Perl you download might be different from the one in this activity. Updates and enhancements to software are made often, and you might have to perform different steps from what’s listed here. When in doubt, follow the software’s installation instructions.)

1. Start your Web browser, and go to http://activestate.com/activeperl. If you see a message about security, add the site to your trusted zones.

2. On the ActivePerl page, click the DOWNLOAD NOW link. If a pop-up window opens, asking you to sign up for a newsletter, close the window.

3. In the Opening ActivePerl dialog box, specify saving the installation file to your desktop. Respond to any security prompts about downloading the file.

4. After the file has been downloaded, double-click it on your desktop. If necessary, respond to any security prompts.

5. In the welcome window of the ActivePerl Setup Wizard, click Next.

6. Read the license agreement, verify that the I accept the terms in the License Agreement option button is selected, and then click Next.

7. In the Custom Setup window, follow the instructions to install all components on your hard drive, as shown in Figure 7.6. (Note that the screens you see might differ slightly, depending on the version you downloaded.) If you want to see the total disk space required, click the Disk Usage button, and then click OK. Click Next to accept the features.

8. In the Choose Setup Options window (see Figure 7.7), accept the default selections, and then click Next.

9. In the Ready to Install window, click Install. After several minutes, the program is installed.

10. In the last window, click Finish. Read the release notes, which are displayed in your Web browser automatically.

11. To begin writing your Perl script, open a command prompt window in Windows, and change to the C:Perl directory.

12. Type notepad first.pl and press Enter. When prompted to create a new file, click Yes.

13. On the first line, type # This is my first Perl script program and press Enter.

14. Next, type # I should always have documentation in my scripts-- no matter and press Enter.

Figure 7.6
Installing ActivePerl features

Image

Courtesy Course Technology/Cengage Learning

Figure 7.7
Choosing setup options

Image

Courtesy Course Technology/Cengage Learning

Figure 7.8
Creating the first.pl Perl script

Image

Courtesy Course Technology/Cengage Learning

Figure 7.9
Running the first.pl Perl script

Image

Courtesy Course Technology/Cengage Learning

15. Finish the previous comment by typing # how easy I think the script is to understand! and pressing Enter twice.

16. Next, type print “Hello security testers! ”; and press Enter.

17. Your script should look similar to Figure 7.8. Be careful not to miss a semicolon or quotation mark. Remember that programming requires a keen eye.

18. Save the file and exit Notepad.

19. At the command prompt, type first.pl and press Enter.

20. If you didn’t make any errors, your screen should look like Figure 7.9. If you did get errors, read through your code and compare it with the lines of code in this activity’s steps. Correct any errors and save the file again.

21. Close the command prompt window.


Understanding the Basics of Perl

Knowing how to get help quickly in any programming language is useful. The perl -h command gives you a list of parameters used with the perl command (see Figure 7.10).

If you want to know what the print command does, you can use perldoc -f print, which produces the output shown in Figure 7.11.

As you can see, this command gives you a detailed description of the Perl print command, which is almost identical to the C print command. Perl also has the printf command for formatting complex variables. Table 7.9 shows how to use this command to format specific data. Note the similarities to C.

Figure 7.10
Using the perl -h command

Image

Courtesy Course Technology/Cengage Learning

Figure 7.11
Using the perldoc command

Image

Courtesy Course Technology/Cengage Learning

Table 7.9 Using printf to format output

Image

Understanding the BLT of Perl

As you learned previously, all programming languages must have a way to branch, loop, and test. The following sections use code examples to show you how Perl handles these BLT functions. As you examine these examples, keep the following syntax rules in mind:

Image The sub keyword is used in front of function names.

Image Variables begin with the $ symbol.

Image Comment lines begin with the # symbol.

Image The & symbol indicates a function.

Except for these minor differences, Perl’s syntax is much like the C syntax. This similarity is one of the reasons many security professionals with C programming experience choose Perl as a scripting language.

Branching in Perl

In a Perl program, to go from one function to another, you simply call the function by entering its name in your source code. In the following example, the &name_ best_guitarist line branches the program to the sub name_best_guitarist function:

# Perl program illustrating the branching function
# Documentation is important
# Initialize variables
$first_name = "Jimi";
$last_name = "Hendrix";
&name_best_guitarist;
sub name_best_guitarist
{
     printf "%s %s %s", $first_name, $last_name, "was the best!";
}
Looping in Perl

Suppose you want to send an important message to a group of people by using the Net send command. Because you’re sending the same message to multiple users, it’s a repetitive task that requires looping. As you learned in C, you have several choices for performing a loop. In this section, you learn about two of Perl’s looping mechanisms: the for loop and the while loop.

The Perl for loop is identical to the C for loop:

for (variable assignment; test condition; increment variable)
{
    a task to do over and over
}

Substituting the variable $a, you have the following code:

for ($a = 1; $a <= 10; $a++)
{
    print "Hello, security testers!
"
}

This loop prints the phrase 10 times. Next, try getting the same output by using the while loop, which has the following syntax:

while (test condition)
{
      a task to do over and over
}

The following code produces the same output as the for loop:

$a = 1;
while ($a <= 10)
{
      print "Hello, security testers!
";
      $a++
}

Security Bytes


Chris Nandor, known for developing the Mac Classic version of Perl 5.8.0, became one of the first hackers to use a Perl script in an online election. Apparently, his Perl script added more than 40,000 votes for several Red Sox players during an online election in 1999 for the All-Stars game. Similarly, in 1993, an online election involving the Denver Broncos traced more than 70,000 votes coming from one IP address. The power of the loop!


Testing Conditions in Perl

Most programs must be able to test the value of a variable or condition. The two looping examples shown previously use the less than or equal operator (<=). Other operators used for testing in Perl are similar to C operators. Table 7.10 lists the operators you can use in Perl.

Often you combine these operators with Perl conditionals, such as the following:

Image if—Checks whether a condition is true. Example:

if ($age > 12) {
      print "You must be a know-it-all!";
}

Image else—Used when there’s only one option to carry out if the condition is not true. Example:

if ($age) > 12 {
      print "You must be a know-it-all!";
}

else
{
      print "Sorry, but I don't know why the sky is blue.";
}

Table 7.10 Perl operators

Image
Image

Image elsif—Used when there are several conditionals to test. Example:

if (($age > 12) && ($age < 20))
{
     print "You must be a know-it-all!";
}
elsif ($age > 39)
{
    print "You must lie about your age!";
}
else
{
    print " To be young...";
}

Image unless—Executes unless the condition is true. Example:

unless ($age == 100)
{
     print "Still enough time to get a bachelor's degree.";
}

The message is displayed until the $age variable is equal to 100. With some practice and lots of patience, these examples can give you a start at creating functional Perl scripts.

UNDERSTANDING OBJECT-ORIENTED PROGRAMMING CONCEPTS

Just when you think you’re comfortable with a technology concept, something new comes along. Although the concept of object-oriented programming isn’t new to experienced programmers, it might not be familiar to those just learning how to write their first Perl script, for example. Perl 5.0 uses object-oriented programming concepts, and Perl 6.0 will be based solely on this model, so this section covers some basic object-oriented concepts as a foundation for writing another Perl script. This section is by no means a complete discussion of a complex concept. Learning object-oriented programming takes time and practice, and this section merely introduces you to the fundamental concepts.

Components of Object-Oriented Programming

The version of Perl you installed has additional functions that make program calls to the Windows application programming interface (Win API). Programmers should know what functions are available in different OSs so that they can write programs that interact with these functions. For example, a C programmer knows that the Win API has the NodeName() function, which returns the NetBIOS computer name. To use this function, the programmer references it with Win32::NodeName(). The :: separates the name of the class, Win32, from the member function, NodeName(). In object-oriented programming, classes are structures that hold pieces of data and functions. The following code example shows the Employee class in C++. Classes can be written in many object-oriented languages (Java, Object COBOL, and Perl, for example). What’s important is recognizing what a class looks like:

Note


Win32 API is now officially known as Win API to reflect its support in the latest 64-bit systems. However, for the purposes of this section, Win32 API is used interchangeably with Win API.


// This is a class called Employee created in C++
class Employee
{
    public:
          char firstname[25];
          char lastname[25];
          char PlaceOfBirth[30];
          [code continues]
};
void GetEmp()
{
     // Perform tasks to get employee info
    [program code goes here]
}

The structure created in this code can contain employee information as well as a function that performs a lookup. A function contained in a class is called a member function. As mentioned, to access a member function, you use the class name followed by two colons and the member function’s name:

Employee::GetEmp()

The Win32 class contains many functions you can call from your Perl script. Table 7.11 describes some commonly used Win32 API functions.

Attackers and security professionals can use these functions to discover information about a remote computer. Although these functions aren’t difficult to understand, becoming proficient at using them in a program takes time and discipline. For security professionals who need to know what attackers can do, gaining this skill is worth the time and effort.

Table 7.11 Win32 API functions

Image
Image
Image

In Activity 7.5, you create a Perl script that uses some of the Win32 API functions listed in Table 7.11. This script gives you the following information about the Windows computer you have been using for this book’s activities:

Image Logon name of the user

Image Computer name

Image File system

Image Current directory

Image OS name

Activity 7.5: Creating a Perl Script That Uses the Win32 API


Time Required: 30 minutes

Objective: Learn how to access the Win32 API from a Perl script.

Description: In this activity, you write a basic Perl script, using the formatting functions you have already learned and the Win32 API functions in Table 7.11.

1. If necessary, open a command prompt window, and switch to the C:Perl directory. Type notepad Win32.pl and press Enter. Click Yes when prompted to create a new file.

2. In the new Notepad document, type # Win32.pl on the first line and press Enter.

3. Use what you’ve learned in this chapter to write comments for documenting the program. Be sure to enter the author name, date, and a brief description of what the program does, such as the functions it accesses from the Win32 API.

4. After your lines of documentation, press Enter several times to create blank lines for separating your comments from the program code. Then type use win32; and press Enter. (Note: Don’t forget the semicolon.)

5. You need five pieces of information (noted in the bulleted list before this activity) from the Win32 API. Attempt to write the code for getting this information, and then save the program. If you need assistance, use the following steps.

6. Type $login = Win32::LoginName(); and press Enter. This line populates the $login variable with the information gathered from LoginName().

7. Next, type the following lines to populate the other variables needed to complete the task, pressing Enter after each line:

$NetBIOS = Win32::NodeName();
$filesystem = Win32::FsType();
$Directory = Win32::GetCwd();
$os_name = Win32::GetOSName();

8. The following variables need to be displayed onscreen. Type the lines of code as shown, pressing Enter after each line. When you’re done, your window should look similar to Figure 7.12.

print "$login
";
print "$NetBIOS
";
print "$filesystem
";
print "$Directory
";
print "$os_name
";

Figure 7.12
Using the Win32 API from a Perl script

Image

Courtesy Course Technology/Cengage Learning

Figure 7.13
Running the win32.pl Perl script

Image

Courtesy Course Technology/Cengage Learning

9. After typing all the code, save the program, run it, and debug any errors. Figure 7.13 shows the output. What’s wrong with this report?

10. Spend time improving the report’s formatting so that anyone reading the output could understand its meaning.

11. Are there any improvements you think should be made to the script? Explain. What other information might be beneficial for a security professional to get from this report?

12. Close all open windows.


An Overview of Ruby

Another object-oriented language many security testers use is Ruby, which is similar to Perl. Security testers also use Metasploit 3 (www.metasploit.com), a Ruby-based program included in this book’s supporting files, to check for vulnerabilities on computer systems. Metasploit contains hundreds of exploits that can be launched on a victim’s computer or network, which makes it a useful tool for hackers. Security testers using Metasploit should understand the basics of Ruby and be able to modify Ruby code to suit different environments and targets. For example, security testers might need to modify code for a reverse shell module in Ruby so that it’s compatible with the target system where they’re conducting vulnerability tests (see Figure 7.14). A reverse shell is a backdoor initiated from inside the target’s network that makes it possible to take control of the target even when it’s behind a firewall. For more information on reverse shells, visit www.plenz.com/reverseshell.

Figure 7.15 shows some of the many exploits written in Ruby. Note the.rb extension, for Ruby, in program names. In Figure 7.16, the security tester has opened the module for the MS08-067 vulnerability exploit in vi for editing. As you can see, the Ruby syntax is similar to that of object-oriented programming, and the module includes detailed descriptions of the Ruby code.

Figure 7.14
Modifying exploit shell code in Ruby

Image

Courtesy Course Technology/Cengage Learning

Figure 7.15
Metasploit modules in Ruby

Image

Courtesy Course Technology/Cengage Learning

Figure 7.16
Examining the code of a Metasploit module written in Ruby

Image

Courtesy Course Technology/Cengage Learning

CHAPTER SUMMARY

Image Writing an algorithm and using pseudocode are good habits to adopt when writing programs.

Image Clear documentation of program code is essential.

Image C is one of the most popular programming languages for security professionals and hackers alike.

Image Learning the BLT of any programming language can help you master the fundamentals of programming. Branching, looping, and testing are the most important aspects of programming.

Image Many C compilers are available. GNU GCC is an open-source C compiler included with most Linux implementations.

Image HTML is the primary language used to create Web pages. Security professionals need to recognize when something looks suspicious in a Web page, so they should be able to read an HTML file.

Image Security professionals should have a basic knowledge of Perl and C because many security tools are written in these languages. Security professionals who understand these programming languages can modify security tools and create their own customized tools.

Image With object-oriented programming, programmers can create classes, which are structures containing both data and functions. Functions in these classes are programs that perform specific tasks.

Image Win API (formerly called Win32 API) is an interface to the Windows OS that programmers can use to access information about a computer running Windows, such as the computer name, OS name, and so forth.

Image Ruby is a flexible, object-oriented programming language similar to Perl. Security testers and attackers use Metasploit 3, containing exploit modules written in Ruby, to check for vulnerabilities or to attack systems.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset