Final Ism Doc

Embed Size (px)

DESCRIPTION

ISM journal MSc

Citation preview

PAPER II

INTERNET SECURITY MANAGEMENT

SUBMITTED BY

PRANAV VISHWAS DHAWDE

YEAR 2014-2015

PRACTICAL FULFILLMENT OF

M.Sc(I.T) PART II

UNIVERSITY OF MUMBAI

DEPARTMENT OF INFORMATION TECHNOLOGY

KERALEEYA SAMAJAM (REGD), DOMBIVLIS

MODEL COLLEGE

ACCREDITED GRADE A BY NAAC

DOMBIVLI (EAST) 421201INDEX

SR NOTITLEDATESIGN

1Working with Sniffers for monitoring network communication

2Using open SSL for web server - browser communication

3Using GNU PGP

4Using IP TABLES on Linux and setting the filtering rules

5Understanding buffer overflow & format string attacks

6Using nmap

7Socket programming

Practical No. 1Aim: Working with Sniffers for monitoring network communication (Ethereal)

Wireshark is a network packet analyzer that intercepts, captures and logs information about packets passing through a network interface. This is useful for analyzing network problems, detecting network intrusions, network misuse, and other security problems, monitor usage and gather statistics, and many other applications.

InstallationWireshark for Windows can be download at http://www.wireshark.org/download.html Note : You will need to run Wireshark with root/Administrator privileges in order to perform live capture on your network interface.Start Wireshark. Under the Capture header, select the Interface List option; or click on the Interfaces button on the toolbar:This will bring up a list of network interfaces that Wireshark is able to capture packets from:

Select the network adapter (wired or wireless) that you are currently using to connect to the Internet, and hit the Start button. This will take you to the main window:

Wireshark is now capturing live network activity on your network interface. Notice that the list of packets is color-coded to highlight different types of network traffic. Open your web browser and navigate to a few random web pages observe that the network packets corresponding to your web browsing activity are captured and show up in Wireshark as well. By default, the list of captured packets will keep scrolling automatically during a live capture. You can toggle this on/off using the AutoScroll toggle button in the toolbar: After letting the capture run for a couple of minutes, press the stop capture button: .Do not close this capture session.

Filtering the Packet ListCapturing network traffic for a couple minutes could include traffic on many different protocols such as ARP, TCP, UDP, DNS, HTTP, etc. We may not be interested in all of these, depending on what we are trying to achieve.Fortunately, Wireshark allows us to filter the list based on different criteria using the Filter toolbar:Filter toolbar Let us take a look at the HTTP traffic that occurs when we browse the web. In the filter toolbar, type http and then click on Apply. The window will now list only captured packets related to HTTP traffic:

Displaying only HTTP trafficExamining HTTP TrafficExamining HTTP Traffic the HTTP traffic that occurs during web browsing. Stop and close any capture that you may have open, and start a new capture. Set the filter to show only HTTP traffic. start with the HTTP request sent from your web browser. In your web browser, navigate to some webpage In the top frame of the Wireshark main window, look for the packet that corresponds to your request. This contains the URL in the Info section. Select this packet. In the middle frame of the Wireshark window, expand the Hypertext Transfer Protocol section. Notice the details given for the: GET request Host User-Agent Accepts cookieDetails of outgoing HTTP request corresponding to proxy.htmlTake a look at the HTTP response to the above request. In the top frame of the Wireshark main window, find and select the HTTP/1.1 200 OK packet immediately below the request for proxy.html. This is the response containing the requested web page. Again, expand the Hypertext Transfer Protocol section. Notice the details given for Cache-Control Content-Type Server etcDetails of incoming HTTP response corresponding to proxy.html If we expand the HTTP chunked response section, we can find the actual data transmitted in the response. In this case, note the web page HTML visible in the bottom frame of the windowData section of the HTTP response, containing the web page HTMLThe requested web page contained a background image, which the web browser alsohad to fetch. Notice that below the two packets we have already examined, there is another pair of request and response packets corresponding to the page background image, USCwebMarble.jpg. Examine the details of these two packets as well.Now, repeat the exercise with the following links and observe the behavior of the corresponding requests and responses: a file with only text: http://wwwscf.usc.edu/~csci571/Special/HTTP/simple1.html a file with text and one gif image: http://wwwscf.usc.edu/~csci571/Special/HTTP/simple2.html a file with two frames containing simple1.htm and simple2.html: http://wwwscf. usc.edu/~csci571/Special/HTTP/simple3.html an executable script: http://nunki.usc.edu:8088/cgi-bin/test-cgi a page that uses the POST method: http://nunki.usc.edu:8088/birthday.html - fill and submit the form, and examine the request and response. a missing file: http://www-scf.usc.edu/~csci571/missingfile.html a secure directory: http://nunki.usc.edu:8088/cgi-bin/secure/test-cgiFiltering with ExpressionsWhile we can easy to examine the traffic that occurs from browsing in a controlled environment as we have done above, things may be different in practice where there may be a large amount of traffic to sift through simply isolating HTTP traffic may not be enough.To locate specific packets related to individual requests or responses from a within larger capture containing more traffic, we can perform even more specific filtering using a variety of expressions relating to various header fields and their contents.Start a new capture, and do some arbitrary web browsing, such as visiting some Wikipedia articles, reading some news, etc.Then, with the capture still active, also visit all of the web pages we used in the last section: http://www-scf.usc.edu/~csci571/Special/HTTP/simple1.html http://www-scf.usc.edu/~csci571/Special/HTTP/simple2.html http://www-scf.usc.edu/~csci571/Special/HTTP/simple3.html http://nunki.usc.edu:8088/cgi-bin/test-cgi http://nunki.usc.edu:8088/birthday.html - (fill and submit the form) http://www-scf.usc.edu/~csci571/missingfile.html http://nunki.usc.edu:8088/cgi-bin/secure/test-cgiNow, assuming we dont have any prior knowledge about the order in which we visited various web pages, lets filter the traffic using various expressions.In the filter toolbar, click on the Expression button.A dialog box will appear, showing a large list of possible packet header fields that can be used to filter the captured network.Filter expression dialog: various expressions for filtering HTTP trafficLets take a look at what some of these options do. Among the first few field options are http.request and http.response. http.request allows us to filter the traffic so that only request packets are shown; conversely, using http.response displays only response packets.Filtering only requests using the filter http.requestOther fields are more specific. For instance, recall the form that we submitted earlier we can find the request corresponding to that by taking advantage of the fact that the form was submitted using the POST method:

Building an expression in the dialog: here we are looking for http.request.method of POST

After building the filter expression and pressing Apply on the filter toolbar, we obtain the HTTP request packet that we were looking for:HTTP request packet corresponding to form submission using POST MethodWe can also look parts of URLs or whole URLs using http.host, http.request.uri andhttp.request.fulluri:Filtering for requests to the host nunki.usc.edu

Filtering for URLs containing the substring simpleAs well as the http.referer, such as in this case of a GIF image being loaded on simple2.html:Filtering request generated by the referring page simple2.htmlResponse packets :- Recall that we visited the URL http://wwwscf.usc.edu/~csci571/missingfile.html, which returned a HTTP 404 response since there is actually no page at that location. We can find the HTTP response that corresponds to that by filtering on the HTTP response code:

Building filter for HTTP 404 responsesApplying this filter, we are able to obtain the HTTP response packet that we were looking for:HTTP response corresponding to attempt to visit an inexistent pageOther fields that can be used to filter for specific response packets include the http.content_type, http.content_length, http.last_modified, http.server, etc.You can even combine multiple expressions using logical operators to form more complex filter patterns:a) and : && b) or : || c) xor : ^^ d) not : !In the following example, we build a filter to look for a HTTP response that served up aGIF image from a web server running Apache:

A packet with incorrect IP header checksum caused by checksum Offloading

To make this error go away, you can disable IP checksum validation as follows: Under the Edit menu, click Preferences Under Protocols look for IPv4. Uncheck the box for Validate the IPv4 checksum if possible Apply the settingPractical No. 2Aim: Using open SSL for web server - browser communication

1. CSR, Sign Your Certificate Signing Request,2. Remove the PassPhrase From Your Private Key3. Install Your Certificate and Private Key4. service httpd restart5. Test Your Apache SSL Virtual Host6. Configure Your Apache SSL Virtual HostGenerate the RSA Keyopenssl genrsa -des3 -out server.key 1024[enter a password][confirm your password]

Certificate Signing Request (CSR)openssl req new -key server.key -out server.csr[enter your private key password][enter your two character country code][enter your full state or province name][enter your city name][enter your company name][enter your organizational unit or leave it blank][enter your common name or fqdn][enter your admin email address][leave the rest of the attributes blank]

cat server.csr

Sign Your Certificate Signing Requestopenssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt[enter your private key password]

Remove the PassPhrase From Your Private Keycp server.key server.key.secureopenssl rsa -in server.key.secure -out server.key[enter your private key password]

Install Your Certificate and Private Keymv server.csr /etc/httpd/conf/ssl.csr/host_domain_tld.csrmv server.crt /etc/httpd/conf/ssl.crt/host_domain_tld.crtmv server.key /etc/httpd/conf/ssl.key/host_domain_tld.keymv server.key.secure /etc/httpd/conf/host_domain_tld.key.secure

chmod 400 /etc/httpd/conf/ssl.csr/host_domain_tld.csrchmod 400 /etc/httpd/conf/ssl.crt/host_domain_tld.crtchmod 400 /etc/httpd/conf/ssl.key/host_domain_tld.keychmod 400 /etc/httpd/conf/ssl.key/host_domain_tld.key.secureConfigure Your Apache SSL Virtual Host

service httpd restartTest Your Apache SSL Virtual Host

1. Now open up a web browser and try out SSL secured web site. Be sure to use the https:// prefix instead of http:// when going there. You will be prompted with a security alert informing you that your certificate is not signed by a trusted authority.2. Accept the certificate for the session so your page will load.3. Once our secure site loads you can click the padlock in the address bar to view your self-signed certificate details if you're using FireFox.4. Internet Explorer users can double-click the padlock in the bottom right corner of the window in the status bar.

That's all there is to making a self-signed certificate with OpenSSL and configuring Apache to use it to create a SSL secured web site.

Installing Apache HTTP Web Serverwhich httpd

Apache binary doesn't seem to be found on the server. Our next step is to install Apacheby using yum.yum install httpd

Two RPM packages will be downloaded from the CentOS repository (httpd-2.0.52- 22.ent.centos4.i386.rpm and httpd-suexec-2.0.52-22.ent.centos4.i386.rpm) and installed automatically. If everything goes well you should now have the Apache web server on your system.Installing mod_ssl for Secure Sockets Layer (SSL) Support Secure Sockets Layer, also known as SSL for short, provides encrypted communications between hosts. In a typical SSL setup, the web server has SSL support enabled and a certificate that verifies the company's identity. These certificates are initially generated as Certificate Signing Requests (CSR) by the server's administrator. The CSR is then signed by a third party, a Certificate Authority (CA), that validates the company's identity and makes the CSR into a full certificate.now install the mod_ssl RPM (mod_ssl-2.0.52-22.ent.centos4.i386.rpm) for Apache using yum.

yum install mod_sslmod_ssl

mod_ssl should now be installed..

Practical No. 3Aim: Using GnuPG1. generating private keys2. exchanging keys3. importing keys4. encrypting

GnuPG is a complete and free implementation of the OpenPGP standard as defined by RFC4880 (also known as PGP). GnuPG allows to encrypt and sign your data and communication, features a versatile key management system as well as access modules for all kinds of public key directories.OpenPGP is a protocol for encrypting email using public key cryptography. It is based on PGP as originally developed by Phil Zimmermann. The OpenPGP protocol defines standard formats for encrypted messages, signatures, private keys, and certificates for exchanging public keys.OpenPGP is the IETF-approved standard that describes encryption technologies that use processes that are interoperable with PGP. PGP is a proprietary encryption solution, and the rights to its software are owned by Symantec. GPG is another popular solution that follows the OpenPGP standards to provide an interface for end users to easily encrypt their files.

generating private keys

This will generate the key.

Exporting Keys

Encrypting & decrypting files

You have now successfully signed the file.To check for integrity and authenticity, the signature file - hence the file with the ending .sig, .asc, .p7s or .pem - and the signed original file (original file) must be in the same file folder. Select the signature file and select the entry Decrypt and check from the Windows Explorer context menu:

You will see the following window:

Under Enter file, Kleopatra shows the full path to your selected signature file.The option Input file is a separate signature is activated since you have signed your original file (here: Signed file) with the input file. Kleopatra will automatically find the associated signed original file in the same file folder.The same path is also automatically selected for the Ouput folder. It only becomes relevant however once you are processing more than one file simultaneously.Confirm the operations with [Decrypt/Check].Following a successful check of the signature, the following window appears:

Practical No. 4Aim: Using IP TABLES on Linux and setting the filtering rules.

Iptables is a firewall, installed by default on all official Ubuntu distributions When you install Ubuntu, iptables is there, but it allows all traffic by default.Theory:Default tables are:1. Raw2. Mangle3. NAT4. FilterDefault chains are (yes, they are written in upper case):1. PREROUTING: used by raw, mangle and nat tables2. INPUT: used by mangle and filter tables3. FORWARD: used by mangle and filter tables4. OUTPUT: used by raw, mangle, nat and filter tables5. POSTROUTING: used by mangle and nat tablesFilter table uses three chains, INPUT, FORWARD and OUTPUT. INPUT chain is for the packets meant for your own local machine. Reply of a http request made by your browser will go through INPUT chain. OUTPUT chain is for the packets going out of your machine. The http request made by your browser will go through this chain. FORWARD chain is for the packets which you receive but they are not meant for you. Your machine is just supposed to forward them to another device. This generally happens when the machine is configured as a gateway or something similar.Now every iptables rules have some "target" which is executed when it is matched against a"criteria". Following are the most common targets: ACCEPT: Packet is accepted and goes to the application for processing. DROP: Packet is dropped. No information regarding the drop is sent to the sender. REJECT: Packet is dropped and information (error) message is sent to the sender. LOG: Packet details are sent to syslogd for logging. DNAT: Rewrites the destination IP of the packet SNAT: Rewrites the source IP of the packet -p : It matches protocols like tcp, udp, icmp and all -s : It matches source IP address -d : It matches destination IP address --sport : It matches the source port --dport : It matches the destination port -i : It matches the interface from which the packet entered -o : It matches the interface from which the packet exitswe'll set default policy for iptables filter table using -P flag.

iptables -t filter -P INPUT DROPiptables -t filter -P OUTPUT DROPNow we'll allow this machine to send only http requests and ssh requests:iptables -A INPUT -p tcp -i eth0 --dport 80iptables -A INPUT -p tcp -i eth0 --dport 22

Note that -A flag is used because we want to append these rules to current iptables config. Ifwe do not use -A then the rules will be overwritten.allow connections to port 20 and 21.

iptables -A OUTPUT -p tcp -i eth0 --sport 20iptables -A OUTPUT -p tcp -i eth0 --sport 21iptables -A OUTPUT -j ACCEPT -p all -d 192.168.1.0/24 -o eth0iptables -A INPUT -j ACCEPT -p all -s 192.168.1.0/24 -i eth0

Basic Commandssudoiptables -Llists your current rules in iptables. If you have just set up your server, you will have no rules, and you should seeChain INPUT (policy ACCEPT)targetprot opt source destinationChain FORWARD (policy ACCEPT)targetprot opt source destinationChain OUTPUT (policy ACCEPT)targetprot opt source destination

Basic Iptables Options1. -AAppend this rule to a rule chain. Valid chains for what we're doing are INPUT,FORWARD and OUTPUT.2. -L - List the current filter rules.3. -m conntrack - Allow filter rules to match based on connection state. Permits the useof the --ctstate option.4. --ctstate - Define the list of states for the rule to match on. Valid states are:1. NEW - The connection has not yet been seen.2. RELATED - The connection is new, but is related to another connection alreadypermitted.3. ESTABLISHED - The connection is already established.4. INVALID - The traffic couldn't be identified for some reason.5. -m limit - Require the rule to match only a limited number of times. Allows the use of the --limit option. Useful for limiting logging rules.1. --limit - The maximum matching rate, given as a number followed by "/second", "/minute", "/hour", or "/day" depending on how often you want the rule to match. If this option is not used and -m limit is used, the default is "3/hour".6. -p - The connection protocol used.7. --dport - The destination port(s) required for this rule. A single port may be given, or a range may be given as start:end, which will match all ports from start to end, inclusive.8. -j - Jump to the specified target. By default, iptables allows four targets:1. ACCEPT - Accept the packet and stop processing rules in this chain.2. REJECT - Reject the packet and notify the sender that we did so, and stop processing rules in this chain.3. DROP - Silently ignore the packet, and stop processing rules in this chain.4. LOG - Log the packet, and continue processing more rules in this chain. Allows the use of the --log-prefix and --log-leveloptions.9. --log-prefix - When logging, put this text before the log message. Use double quotesaround the text to use.10. --log-level - Log using the specified syslog level. 7 is a good choice unless youspecifically need something else.11. -i - Only match if the packet is coming in on the specified interface.12. -I - Inserts a rule. Takes two options, the chain to insert the rule into, and the rule number it should be.1. -I INPUT 5 would insert the rule into the INPUT chain and make it the 5th rule inthe list.13. -v - Display more information in the output. Useful for if you have rules that looksimilar without using -v.14. -s --source - address[/mask] source specification15. -d --destination - address[/mask] destination specification16. -o --out-interface - output name[+] network interface name ([+] for wildcard)

Allowing Established SessionsWe can allow established sessions to receive traffic:

sudoiptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT1. The above rule has no spaces either side of the comma in ESTABLISHED,RELATED

sudoiptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Allowing Incoming Traffic on Specific PortsYou could start by blocking traffic, but you might be working over SSH, where you would need to allow SSH before blocking everything else.To allow incoming traffic on the default SSH port (22), you could tell iptables to allow all TCP traffic on that port to come in.

sudoiptables -A INPUT -p tcp --dportssh -j ACCEPT

Referring back to the list above, you can see that this tells iptables:1. append this rule to the input chain (-A INPUT) so we look at incoming traffic2. check to see if it is TCP (-p tcp).3. if so, check to see if the input goes to the SSH port (--dportssh).4. if so, accept the input (-j ACCEPT).Lets check the rules:

sudoiptables LChain INPUT (policy ACCEPT)targetprot opt source destinationACCEPT all -- anywhere anywhere state RELATED,ESTABLISHEDACCEPT tcp -- anywhere anywheretcpdpt:ssh

Now, let's allow all incoming web traffic

sudoiptables -A INPUT -p tcp --dport 80 -j ACCEPTChecking our rules, we havesudoiptables -LChain INPUT (policy ACCEPT)targetprot opt source destinationACCEPT all -- anywhere anywhere state RELATED,ESTABLISHEDACCEPT tcp -- anywhere anywheretcpdpt:sshACCEPT tcp -- anywhere anywheretcpdpt:www

We have specifically allowed tcp traffic to the ssh and web ports, but as we have not blocked anything, all traffic can still come in.Blocking TrafficOnce a decision is made to accept a packet, no more rules affect it. As our rules allowing ssh and web traffic come first, as long as our rule to block all traffic comes after them, we can still accept the traffic we want. All we need to do is put the rule to block all traffic at the end.

sudoiptables -A INPUT -j DROPsudoiptables -LChain INPUT (policy ACCEPT)targetprot opt source destinationACCEPT all -- anywhere anywhere state RELATED,ESTABLISHEDACCEPT tcp -- anywhere anywheretcpdpt:sshACCEPT tcp -- anywhere anywheretcpdpt:wwwDROP all -- anywhere anywhere

Because we didn't specify an interface or a protocol, any traffic for any port on any interface is blocked, except for web and ssh.

Editing iptablesThe only problem with our setup so far is that even the loopback port is blocked. We could have written the drop rule for just eth0 by specifying -i eth0, but we could also add a rule for the loopback. If we append this rule, it will come too late - after all the traffic has been dropped. We need to insert this rule before that. Since this is a lot of traffic, we'll insert it as the first rule so it's processed first.

sudoiptables -I INPUT 1 -i lo -j ACCEPTsudoiptables -LChain INPUT (policy ACCEPT)targetprot opt source destinationACCEPT all -- anywhere anywhereACCEPT all -- anywhere anywhere state RELATED,ESTABLISHEDACCEPT tcp -- anywhere anywheretcpdpt:sshACCEPT tcp -- anywhere anywheretcpdpt:wwwDROP all -- anywhere anywhere

The first and last lines look nearly the same, so we will list iptables in greater detail.

sudoiptables -L -vChain INPUT (policy ACCEPT 0 packets, 0 bytes)pkts bytes target prot opt in out source destination0 0 ACCEPT all -- lo any anywhere anywhere0 0 ACCEPT all -- any any anywhere anywhere stateRELATED,ESTABLISHED0 0 ACCEPT tcp -- any any anywhere anywheretcpdpt:ssh0 0 ACCEPT tcp -- any any anywhere anywheretcpdpt:www0 0 DROP all -- any any anywhere anywhereYou can now see a lot more information. This rule is actually very important, since many programs use the loopback interface to communicate with each other.

LoggingIn the above examples none of the traffic will be logged. If you would like to log dropped packets to syslog, this would be the quickest way:

sudoiptables -I INPUT 5 -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --loglevel7Saving iptables

If you were to reboot your machine right now, your iptables configuration would disappear. Rather than type this each time you reboot, however, you can save the configuration, and have it start up automatically. To save the configuration, you can use iptables-save and iptables-restore.

Practical No. 5Aim: What is buffer overflow? How a buffer overflow happens? How a buffer overflow attack takes place? How to avoid buffer overrun?What is Buffer Overflow?A buffer, in terms of a program in execution, can be thought of as a region of computers main memory that has certain boundaries in context with the program variable that references this memory.For example : char buff[10]In the above example, buff represents an array of 10 bytes where buff[0] is the left boundary and buff[9] is the right boundary of the buffer.Lets take another example :int arr[10]In the above example, arr represents an array of 10 integers. Now assuming that the size of integer is 4 bytes, the total buffer size of arr is 10*4 = 40 bytes. Similar to the first example, arr[0] refers to the left boundary while arr[9] refers to the right boundary.A buffer is said to be overflown when the data (meant to be written into memory buffer) gets written past the left or the right boundary of the buffer. This way the data gets written to a portion of memory which does not belong to the program variable that references the buffer.Here is an example :char buff[10];buff[10] = 'a';In the above example, we declared an array of size 10 bytes. Please note that index 0 to index 9 can used to refer these 10 bytes of buffer. But, in the next line, we index 10 was used to store the value a. This is the point where buffer overrun happens because data gets written beyond the right boundary of the buffer.Why are buffer overflows harmful?Buffer overflows, if undetected, can cause your program to crash or produce unexpected results.1. Consider a scenario where you have allocated 10 bytes on heap memory:char *ptr = (char*) malloc(10);Now, if you try to do something like this :ptr[10] = 'c';Then this may lead to crash in most of the cases. The reason being, a pointer is not allowed to access heap memory that does not belong to it.2. Consider another scenario where you try to fill a buffer (on stack) beyond its capacity :char buff[10] = {0};strcpy(buff, "This String Will Overflow the Buffer");

Buffer Overflow AttacksIt gets worse when an attacker comes to know about a buffer over flow in your program and he/she exploits it. Consider this example :#include #include int main(void){ char buff[15];int pass = 0;printf("\n Enter the password : \n");gets(buff);if(strcmp(buff, "thegeekstuff")){printf ("\n Wrong Password \n");}else{printf ("\n Correct Password \n");pass = 1;}if(pass){/* Now Give root or admin rights to user*/printf ("\n Root privileges given to the user \n");}return 0;}The program above simulates scenario where a program expects a password from user and if the password is correct then it grants root privileges to the user.Lets the run the program with correct password i.e. thegeekstuff :$ ./bfrovrflwEnter the password :thegeekstuffCorrect PasswordRoot privileges given to the userThis works as expected. The passwords match and root privileges are given.But do you know that there is a possibility of buffer overflow in this program. The gets() function does not check the array bounds and can even write string of length greater than the size of the buffer to which the string is written.Now, can you even imagine what can an attacker do with this kind of a loophole?Here is an example :$ ./bfrovrflwEnter the password :hhhhhhhhhhhhhhhhhhhhWrong PasswordRoot privileges given to the userIn the above example, even after entering a wrong password, the program worked as if yougave the correct password.There is a logic behind the output above. What attacker did was, he/she supplied an input of length greater than what buffer can hold and at a particular length of input the buffer overflow so took place that it overwrote the memory of integer pass. So despite of a wrong password, the value of pass became non zero and hence root privileges were granted to an attacker.To avoid buffer overflow attacks, the general advice that is given to programmers is to follow good programming practices. For example: Make sure that the memory auditing is done properly in the program using utilities likevalgrind memcheckUse fgets() instead of gets().Use strncmp() instead of strcmp(), strncpy() instead of strcpy() and so on.

Example1This example demonstrates how the application can behave when the format function doesnot receive the necessary treatments for validation in the input of format string.First is the application operating with normal behavior and normal inputs, then, theapplication operating when the attacker inputs the format string and the resultingbehavior.Below is the source-code used for the example.#include #include #include int main (int argc, char **argv){char buf [100]int x = 1snprintf ( buf, sizeof buf, argv [1] ) ;buf [ sizeof buf -1 ] = 0printf ( Buffer size is: (%d) \nData input: %s \n , strlen (buf) , buf ) ;printf ( X equals: %d/ in hex: %#x\nMemory address for x: (%p) \n , x, x,&x) ;return 0 ;}Next is the output that the program supplies when running with expected inputs. In this case the program received the string Bob as input and returned it in the output../formattest BobBuffer size is (16)Data input : BobX equals: 1/ in hex: 0x1Memory address for x (0xbffff73c)Now the format string vulnerability will be explored. If the format string parameter %x %x is inserted in the input string, when the format function parses the argument, the output will display the name Bob, but instead of showing the %x string, the application will show the contents of a memory address../formattest Bob %x %xBuffer size is (27)Data input : Bob bffff 8740X equals: 1/ in hex: 0x1Memory address for x (0xbffff73c)The inputs Bob and the format strings parameters will be attributed to the variable buf inside the code which should take the place of the %s in the Data input. So now the printf argument looks like:printf ( Buffer size is: (%d) \n Data input: Bob %x %x \n , strlen (buf) , buf ) ;When the application prints the results, the format function will interpret the format string inputs, showing the content of a memory address.

Practical No. 6Aim: Working with nmapZenmap is the official graphical user interface (GUI) for the Nmap Security Scanner. It is a multi-platform, free and open-source application designed to make Nmap easy for beginners to use while providing advanced features for experienced Nmap users.Frequently used scans can be saved as profiles to make them easy to run repeatedly. A command creator allows interactive creation of Nmap command lines. Scan results can be saved and viewed later. Saved scans can be compared with one another to see how they differ.Typical Zenmap screen shot

ScanningBegin Zenmap by typing zenmap in a terminal or by clicking the Zenmap icon in the desktop environment.

Target and profile selection

While a scan is running (and after it completes), the output of the Nmap command is shown on the screen.Any number of targets, separated by spaces, may be entered in the target field. All the target specifications supported by Nmap are also supported by Zenmap, so targets such as 192.168.0.0/24 and 10.0.0-5.* work. Zenmap remembers the targets scanned most recently. To re-scan a host, select the host from the combo box attached to the Target text field.ProfilesThe Intense scan is just one of several scan profiles that come with Zenmap. Choose a profile by selecting it from the Profile combo box. Profiles exist for several common scans. After selecting a profile the Nmap command line associated with it is displayed on the screen.Scan AggregationZenmap has the ability to combine the results of many Nmap scans into one view, a feature known as scan aggregation. When one scan is finished, you may start another in the same window. When the second scan is finished, its results are merged with those from the first. The collection of scans that make up an aggregated view is called a network inventory.An example of aggregation will make the concept clearer. Let's run a quick scan against scanme.nmap.org.

Now do the same against localhost:

Now results for both scanme and localhost are shown. This is something you could have done with one Nmap scan, giving both targets, although it's convenient not to have to think of all the targets in advance. Now suppose we want some more information about scanme, so we launch an intense scan on it.

Now scanme has a little penguin icon showing that its operating system has been detected as Linux. Additionally one of its services has been identified. Now we're doing something you can't do with a single Nmap scan, because you can't single out a host for more intense scanning like we did. The results for localhost are still present, though we won't know more about it than we did before unless we decide to do a more in-depth scan.It is not necessary to wait for one scan to finish before starting another. Several scans may run concurrently. As each one finishes its results are added to the inventory.Interpreting Scan ResultsNmap's output is displayed during and after a scan. This output will be familiar to Nmap users. Except for Zenmap'scolor highlighting, this doesn't offer any visualization advantages over running Nmap in a terminal. However, other parts of Zenmap's interface interpret and aggregate the terminal output in a way that makes scan results easier to understand and use.Scan Results TabsEach scan window contains five tabs which each display different aspects of the scan results. They are: Nmap Output, Ports / Hosts, Topology, Host Details, and Scans. Each of these are discussed in this section.The Nmap Output tab

The Nmap Output tab is displayed by default when a scan is run. It shows the familiar Nmap terminal output. The display highlights parts of the output according to their meaning; for example, open and closed ports are displayed in different colors.The Ports / Hosts tab

The Ports / Hosts tab's display differs depending on whether a host or a service is currently selected. When a host is selected, it shows all the interesting ports on that host, along with version information when available.

When a service is selected, the Ports / Hosts tab shows all the hosts which have that port open or filtered.The Topology tab

The Topology tab is an interactive view of the connections between hosts in a network. Hosts are arranged in concentric rings. Each ring represents an additional network hop from the center node. Clicking on a node brings it to the center. Because it shows a representation of the network paths between hosts, the Topology tab benefits from the use of the --traceroute option.The Host Details tab

The Host Details tab breaks all the information about a single host into a hierarchical display. Shown are the host's names and addresses, its state (up or down), and the number and status of scanned ports.Each host has an icon that provides a very rough vulnerability estimate, which is based solely on the number of open ports. The icons and the numbers of open ports they correspond to are02 open ports,34 open ports,56 open ports,78 open ports, and9 or more open ports.The Scans tab

The Scans tab shows all the scans that are aggregated to make up the network inventory. From this tab you can add scans (from a file or directory) and remove scans.While a scan is executing and not yet complete, its status is Running.You may cancel a running scan by clicking the Cancel Scan button.Sorting by HostHost selection

OS iconsFreeBSD Irix LinuxMac OS OpenBSD Red Hat LinuxSolaris or OpenSolaris Ubuntu Linux WindowsOther (no specific icon) OS detection not performedSorting by ServiceFigure 12.6. Service selection

Saving and Loading Scan ResultsTo save an individual scan to a file, choose Save Scan from the Scan menu (or use the keyboard shortcut ctrl+S). If there is more than one scan into the inventory you will be asked which one you want to save. On the save dialog, you have the choice of saving inNmap XML format (.xml extension) or Nmap text format (.nmap extension). The XML format is the only format that can be opened again by ZenmapControlsThe controls appear in a column when the Controls button is clicked.The controls are divided into sections.Comparing ResultsIt is a common desire to run the same scan twice at different times, or run two slightly different scans at the same time, and see how they differ. Zenmap provides an interface for comparing scan results. Open the comparison tool by selectingCompare Results from the Tools menu or by using the ctrl+D (think diff) keyboard shortcut. Zenmap supports comparing two scan results at a time.Figure 12.16. Comparison tool

The first step in performing a comparison is selecting two scans to compare, which are called the A scan and the B scan. The combo boxes allow you to choose from open scans. Or click the Open buttons to get scan results from a file.Comparison output

Options Summary-f, --file Open the given results file for viewing. The results file may be an Nmap XML output file (.xml, as produced by nmap -oX), or a file previously saved by Zenmap.-h, --helpShow a help message and exit.--confdir Use as the per-user configuration directory.-n, --nmap Run the given Nmap command within the Zenmap interface. After -n or -- nmap, every remaining command line argument is read as the command line to execute. This means that -n or --nmap must be given last, after any other options. Note that the command line must include the nmap executablename: zenmap -n nmap -sS target.-p, --profile Start with the given profile selected. The profile name is just a string: "Regular scan". If combined with -t, begin a scan with the given profile against the specified target.-t, --target Start with the given target. If combined with -p, begin a scan with the given profile against the specified target.-v, --verboseIncrease verbosity (of Zenmap, not Nmap). This option may be given multiple times for even more verbosity printed to the console window used to start Zenmap.Error OutputIf Zenmap happens to crash, it normally helps you send a bug report with a stack trace. Set the environment variable ZENMAP_DEVELOPMENT(the value doesn't matter) to disable automatic crash reporting and have errors printed to the console. Try the Bash shell commandZENMAP_DEVELOPMENT=1 zenmap -v -v -v to get a useful debugging output.

Practical No. 7Aim: Socket Programming.

Socket Programming:Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.When the connection is made, the server creates a socket object on its end of thecommunication. The client and server can now communicate by writing to and reading from the socket.The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them.The following steps occur when establishing a TCP connection between two computers using sockets:The server instantiates a ServerSocket object, denoting which port number communication is to occur on.The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.After the server is waiting, a client instantiates a Socket object, specifying the server name and port number to connect to.The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, the client now has a Socket object capable of communicating with the server.On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.After the connections are established, communication can occur using I/O streams.Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream.TCP is a twoway communication protocol, so data can be sent across both streams at the same time. There are following usefull classes providing complete set of methods to implement sockets.ServerSocket Class Methods:The java.net.ServerSocket class is used by server applications to obtain a port andlisten for client requestsThe ServerSocket class has four constructors: Methods with Description :public ServerSocket(int port) throws IOException1. Attempts to create a server socket bound to the specified port. An exception occurs if the port is already bound by another application.public ServerSocket(int port, int backlog) throws IOExceptionSimilar to the previous constructor, the backlog parameter specifies how many incoming clients to store in a wait queue.public ServerSocket(int port, int backlog, InetAddress address)throws IOExceptionSimilar to the previous constructor, the InetAddress parameter specifies the local IP address to bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the server to specify which of its IP addresses to accept client requests on.public ServerSocket() throws IOExceptionCreates an unbound server socket. When using this constructor, use the bind() method when you are ready to bind the server socket.

Here are some of the common methods of the ServerSocket class:Methods with Description :public int getLocalPort()Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port number in a constructor and let the server find a port for you.public Socket accept() throws IOExceptionWaits for an incoming client. This method blocks until either a client connects to the server on the specified port or the socket times out, assuming that the time-out value has been set using the setSoTimeout() method. Otherwise, this method blocks indefinitely.public void setSoTimeout(int timeout)Sets the time-out value for how long the server socket waits for aclient during the accept().public void bind(SocketAddress host, int backlog)Binds the socket to the specified server and port in the SocketAddress object. Use this method if you instantiated the ServerSocket using the no-argument constructor.

Socket Class Methods:The java.net.Socket class represents the socket that both the client and server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method.The Socket class has five constructors that a client uses to connect to a server:Methods with Description :

public Socket(String host, int port) throws UnknownHostException, IOException.This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server.public Socket(InetAddress host, int port) throws IOExceptionThis method is identical to the previous constructor, except that the host is denoted by an InetAddress object.public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.Connects to the specified host and port, creating a socket on the local host at the specified address and port.public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException.This method is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a String.public Socket()Creates an unconnected socket. Use the connect() method to connect this socket to a server.

File Name GreetingClient.javaimport java.net.*;import java.io.*;public class GreetingClient{public static void main(String [] args){String serverName = args[0];int port = Integer.parseInt(args[1]);try{System.out.println("Connecting to " + serverName+ " on port " + port);Socket client = new Socket(serverName, port);System.out.println("Just connected to " + client.getRemoteSocketAddress());OutputStream outToServer = client.getOutputStream();DataOutputStream out = new DataOutputStream(outToServer);out.writeUTF("Hello from " + client.getLocalSocketAddress());InputStream inFromServer = client.getInputStream();DataInputStream in = new DataInputStream(inFromServer);System.out.println("Server says " + in.readUTF());client.close();}catch(IOException e){e.printStackTrace();}}}// File Name GreetingServer.javaimport java.net.*;import java.io.*;public class GreetingServer extends Thread{private ServerSocket serverSocket;public GreetingServer(int port) throws IOException{serverSocket = new ServerSocket(port);serverSocket.setSoTimeout(10000);}public void run(){while(true){try{System.out.println("Waiting for client on port " +serverSocket.getLocalPort() + "...");Socket server = serverSocket.accept();System.out.println("Just connected to "+ server.getRemoteSocketAddress());DataInputStream in =new DataInputStream(server.getInputStream());System.out.println(in.readUTF());DataOutputStream out =new DataOutputStream(server.getOutputStream());out.writeUTF("Thank you for connecting to "+ server.getLocalSocketAddress() + "\nGoodbye!");server.close();}catch(SocketTimeoutException s){System.out.println("Socket timed out!");break;}catch(IOException e){e.printStackTrace();break;}}}public static void main(String [] args){int port = Integer.parseInt(args[0]);try{Thread t = new GreetingServer(port);t.start();}catch(IOException e){e.printStackTrace();}}}