CHAPTER 6

Web-Based Hacking: Servers and Applications

In this chapter, you will

•   Identify features of common web server architecture

•   Identify web application function and architecture points

•   Describe web server and web application attacks

•   Identify web server and application vulnerabilities

•   Identify web application hacking tools

Have you ever seen the movie The Shawshank Redemption? If you haven’t and we were all in a classroom together, I’d probably stop all proceedings and make the entire lot of you reading this book go watch it because I’m entirely unsure any pen test team can function with members who have not seen it. Not to mention, I do not want to be held at fault for turning you out as such; I’m not even sure you should be allowed out in open society without seeing it. However, we’re not in class, and you’re free to do whatever you want, so the best I can do for those of you who will not go see the movie is to provide a wrap-up here. And to pray for you.

In the movie, a kind, honest, well-educated banker named Andy Dufresne is wrongly convicted for the murder of his wife and sentenced to life in prison, to be served at the hellish Shawshank State Prison. He spends two decades of his life there and through all the turmoil and strife manages to form strong friendships, change lives, and stop evil in its tracks. He also manages to escape the prison, leaving the evil warden and his money-laundering operation to face the consequences of their actions. How Andy escaped the prison isn’t what the story is all about, but it is apropos for our discussion here. How, you may ask? Glad to explain.

Andy’s friend, Ellis Redding, gives him a small rock hammer early on to work on chiseling rock chess pieces. No guard could see the harm in it, so they just let him keep it. Over the next two decades, Andy, working behind a big pin-up poster of Rita Hayworth, Marilyn Monroe, and, lastly, Raquel Welch, painstakingly chisels a big hole through the solid concrete walls, allowing access to his eventual escape route—a giant sewage pipe that leads out of the prison, far away to a drainage ditch. See, Andy didn’t work on bribing guards or sneaking into the laundry truck or climbing the walls at night and running as fast as possible toward freedom. No, Andy took the route out of the prison that a lot of hackers take in gaining access into a target—something everyone just trusted to do a job and that no one ever considered could be used in any other way.

I’m not saying you’re going to be covered in...well, you know...as a result of hacking a web server. What I am saying, though, is that organizations that usually do a pretty good job of securing passwords, gates, and other obvious security targets often overlook the huge, open, public-facing front doors they have out there for use. And if you’re willing to get a little dirty, they make a fine way back in. Sure, it’s a little messy at first, but when you break back in, that poster of Andy’s sure looks nice hanging there on the wall.

Web Servers

Regardless what your potential target offers to the world—whether it’s an e-commerce site, a suite of applications for employees and business partners to use, or just a means to inform the public—that offering must reside on a server designed to provide things to the world. Web servers are unique entities in the virtual world we play in. Think about it—we spend loads of time and effort trying to hide everything else we own. We lock servers, routers, and switches away in super-secure rooms and disguise entire network segments behind NAT and DMZs. Web servers, though, are thrown to the proverbial wolves. We stick them right out front and open access to them. Sure, we try our best to secure that access, but the point still remains: web servers are open targets the entire world can see. And you can rest assured those open targets will get a strong look from attackers.

Web Organizations

I promise this won’t take long, but we need to cover some web organizations you need to be familiar with for both your efforts and your exam. It’s literally impossible for me to cover every standards or engineering group, or every international consortium out there that has contributed to making the Web what it is today. I’ll hit on a few I know you need to know about, and trust you to read up on others you should know about.

For example, take IEFT (https://www.ietf.org/). The Internet Engineering Task Force can probably best be described by the tag line on their home page: “The goal of the IETF is to make the Internet work better.” IETF creates engineering documents to help make the Internet work better from an engineering point of view. The IETF’s official documents are published free of charge as Requests For Comments (RFCs). An RFC is used to set a variety of standards—everything from the makeup of a UDP header to how routing protocols are supposed to work, and almost anything else you can think of. Per the IETF regarding RFCs: “…this name (used since 1969, before the IETF existed) expresses something important: the Internet is a constantly changing technical system, and any document that we write today may need to be updated tomorrow.” When you think IETF, think engineering, and engineering only—they’re not here to police what the engineered solution is used for, just to provide the work to get the thing running. “We try to avoid policy and business questions, as much as possible, to concentrate solely on the engineering side of the house.” They recommend www.internetsociety.org/ as a place to go worry about policy.

Another oldie but goodie is the World Wide Web Consortium (W3C). W3C (https://www.w3.org) is an international community where “member organizations, a full-time staff, and the public work together to develop Web standards.” Their stated mission is “to lead the World Wide Web to its full potential by developing protocols and guidelines that ensure the long-term growth of the Web.” For example, when incompatible versions of HTML are offered by different vendors, causing inconsistency in how web pages are displayed, the consortium tries to get all those vendors to implement a set of core principles and components that are chosen by the consortium. W3C engages in education and outreach, develops software, and serves as an open forum for discussion about the Web.

Want an organization more specific to security? Check out OWASP (https://www.owasp.org). The Open Web Application Security Project is a 501(c)(3) worldwide not-for-profit charitable organization focused on improving the security of software. Their mission is to make software security visible so that individuals and organizations worldwide can make informed decisions about true software security risks. OWASP publishes reports, documents, and training efforts to assist in web security.

For example, the OWASP Top 10 is “a powerful awareness document for web application security. The OWASP Top 10 represents a broad consensus about what the most critical web application security flaws are” (https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project).

So what makes up the Top 10? Glad you asked. As of this writing, the current available list is from 2017, and that list is the one referenced within the version 10 courseware. However, a cursory check of that list versus what was on the site for the version 9 CEH exam shows there have been some significant changes. Given how exams work (each test is random and the test pool may have older questions to pull from for your specific examination), I’m going to list the current Top 10, with a reference to where it was on last year’s list. I’ll also include last year’s full list at the end, just for reference. Hopefully your exam will be specific on which is which, but I can’t promise that. All I can do is give you what’s current and hope for the best (go to https://www.owasp.org/index.php/Top_10-2017_Top_10 to view the list current as of this writing). OK, here we go, quoted directly from the current list:

•   A1 – Injection Flaws   Injection flaws, such as SQL, OS, and LDAP injection, occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization. (Position on previous/last year’s list: #1)

•   A2 – Broken Authentication and Session Management   Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords, keys, or session tokens, or to exploit other implementation flaws to assume other users’ identities. (Position on previous/last year’s list: #2)

•   A3 – Sensitive Data Exposure   Many web applications do not properly protect sensitive data, such as credit cards, tax IDs, and authentication credentials. Attackers may steal or modify such weakly protected data to conduct credit card fraud, identity theft, or other crimes. Sensitive data deserves extra protection, such as encryption at rest or in transit, as well as special precautions when exchanged with the browser. (Position on previous/last year’s list: #6)

•   A4 – XML External Entities (XXE)   A new addition. Attackers can exploit vulnerable XML processors if they can upload XML or include hostile content in an XML document, exploiting vulnerable code, dependencies, or integrations. By default, many older XML processors allow specification of an external entity, a URI that is dereferenced and evaluated during XML processing. These flaws can be used to extract data, execute a remote request from the server, scan internal systems, perform a denial-of-service attack, as well as execute other attacks. (Position on previous/last year’s list: N/A, new entry for 2017 list)

•   A5 – Broken Access Control   A new addition. Exploitation of access control is a core skill of attackers. Static Application Security Testing (SAST) and Dynamic Application Security Testing (DAST) tools can detect the absence of access control but cannot verify if it is functional when it is present. Access control is detectable using manual means, or possibly through automation for the absence of access controls in certain frameworks. Access control weaknesses are common due to the lack of automated detection, and lack of effective functional testing by application developers. Access control detection is not typically amenable to automated static or dynamic testing. Manual testing is the best way to detect missing or ineffective access control, including HTTP method (GET vs. PUT, and so on), controller, direct object references, and so on. (Position on previous/last year’s list: N/A, new entry for 2017 list)

•   A6 – Security Misconfiguration   Good security requires having a secure configuration defined and deployed for the application, frameworks, application server, web server, database server, and platform. Secure settings should be defined, implemented, and maintained, as defaults are often insecure. Additionally, software should be kept up to date. (Position on previous/last year’s list: #5)

•   A7 – Cross-Site Scripting (XSS)   XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation or escaping. XSS allows attackers to execute scripts in the victim’s browser, which can hijack user sessions, deface websites, or redirect the user to malicious sites. It’s notable that this dropped so precipitously from the last list. It’s still a Top 10 issue, however, so don’t discount. (Position on previous/last year’s list: #3)

•   A8 – Insecure Deserialization   A new addition. Interestingly, unlike other entries on the list, this was included in the Top 10 based on an industry survey and not on quantifiable data. Exploitation of deserialization is somewhat difficult, as off-the-shelf exploits rarely work without changes or tweaks to the underlying exploit code. Some tools can discover deserialization flaws, but human assistance is frequently needed to validate the problem. It is expected that prevalence data for deserialization flaws will increase as tooling is developed to help identify and address it. The impact of deserialization flaws cannot be understated. These flaws can lead to remote code execution attacks, one of the most serious attacks possible. (Position on previous/last year’s list: N/A, new entry for 2017 list)

•   A9 – Using Components with Known Vulnerabilities   Components such as libraries, frameworks, and other software modules almost always run with full privileges. If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover. Applications using components with known vulnerabilities may undermine application defenses and enable a range of possible attacks and impacts. (Position on previous/last year’s list: #9)

•   A10 – Insufficient Logging and Monitoring   A new addition. Like #8, this was also included in the Top 10 based on an industry survey. Exploitation of insufficient logging and monitoring is the bedrock of nearly every major incident. Attackers rely on the lack of monitoring and timely response to achieve their goals without being detected. One strategy for determining if sufficient monitoring is in place is to examine the logs following penetration testing. The testers’ actions should be recorded sufficiently to understand what damages they may have inflicted. Most successful attacks start with vulnerability probing, and should be noted and acted upon at that stage. Allowing such probes to continue can raise the likelihood of successful exploit to exponentially. (Position on previous/last year’s list: N/A, new entry for 2017 list)

(The OWASP Top 10 is free to use. It is licensed under the Creative Commons Attribution-ShareAlike 4.0 license.)

Images

NOTE    In an effort to cover everything (since this is, after all, an All-in-One guide), here’s the previous version of the Top 10 list in its entirety for your perusal: A1 – Injection Flaws, A2 – Broken Authentication and Session Management, A3 – Cross-Site Scripting (XSS), A4 – Insecure Direct Object References, A5 – Security Misconfiguration, A6 – Sensitive Data Exposure, A7 – Missing Function Level Access Control, A8 – Cross-Site Request Forgery (CSRF), A9 – Using Components with Known Vulnerabilities, A10 – Unvalidated Redirects and Forwards.

As a security professional, I don’t really know whether I should celebrate or be concerned as a result of all this. On one hand, apparently we’ve all gotten better at fixing or preventing insecure direct object reference, missing function-level access control, cross-site request forgery, and unvalidated redirects, as these dropped off the list. On the other hand, much of the Top 10 has stayed, and seemingly common-sense things made the list, such as not making use of components you know are vulnerable (are you kidding me?!?) and ensuring you have proper monitoring. In any case, this is a great resource to measure your web security by. Not the only one, but a good one.

OWASP also provides a really cool option for security education. WebGoat (https://www.owasp.org/index.php/Category:OWASP_WebGoat_Project) is a deliberately insecure web application maintained by OWASP that is designed to teach web application security lessons. “The primary goal of the WebGoat project is simple: create a de-facto interactive teaching environment for web application security. In the future, the project team hopes to extend WebGoat into becoming a security benchmarking platform and a Java-based Web site Honeypot.” You can install it on virtually any platform, it can interface with Java or .NET just fine, and it contains dozens of “lessons” displaying security vulnerabilities you should be aware of. It’s actually a great idea when you think about it: a box you know is there but don’t know much about holds numerous potential security flaws, and you get to test your skillset against it without endangering anything. Not bad for a goat…

I could go on and on with other organizations—they’re endless. ISECOM, Internet Society, OpenSource.org, and a bazillion others are out there for your perusal. Most are trying to make things better. Here’s hoping they succeed.

When We Meet the Enemy, Will It Be Us?

You’ve purchased this book, so I don’t have to tell you that interest in security, pen testing, and ethical hacking is real and growing. And on the face of it, what we’re all doing about it is a very good thing. Training an army of good guys to secure our systems makes all sorts of sense, and if we don’t look at things the way our adversaries do, we’re not doing ourselves any favors. After all, one of the most quoted lines in all of history regarding all this is, “If you know the enemy and know yourself, you need not fear the result of a hundred battles. If you know yourself but not the enemy, for every victory gained you will also suffer a defeat. If you know neither the enemy nor yourself, you will succumb in every battle.” (Sun Tzu, The Art of War). But in some respects, isn’t there a downside to all this?

Consider malware authors, for instance. Back in the early days of Internet networking, viruses weren’t nearly as sophisticated as they are today and just didn’t really matter to most folks. A decade or so passed, and all that changed. But what was really interesting about the whole thing was it seemed those who wrote the best viruses got hired by the antivirus companies, and malware, to quote Ron Burgundy, “escalated quickly.” Was “rewarding” terrible behavior a good thing or bad? Are systems better off today because AV companies hired people who thought like bad guys (because they were), or did the entire advent of all that force malware into loftier horizons (or deeper depths, depending on your perspective)?

I just did a search for “how to be a hacker.” Over 243 million results. “How to hack a Web Server” returned almost 146 million. And “Scripts I can use to hack”? Almost 19 million. YouTube videos on everything you can imagine, articles and whitepapers on techniques, and tips that simplify things to the point my cat may be able to pull it off are available everywhere. Training opportunities (many of which are terrible wastes of time and money, despite well-known name providers) for “ethical” hacking abound. There are even wikis on everything you can imagine, including a really inane one titled “12 steps to becoming a hacker.” Really? That’s all it takes? Well, geez, why am I not hacking?

Are we creating the enemy? Are we making this stuff so available, so palatable that those who wouldn’t otherwise join the fight on the dark side now see opportunity? Are we forcing the evolution of hacking mentality and techniques to greater sophistication by our efforts to be well informed and skilled in defense? Add to it all the monetization of “hacking” nowadays (the days of this being a community wherein the technology and the exploitation of it was purely an exercise in science, thinking, and tinkering are dead), and it gets even cloudier. I think the reward/risk comparative here closes the argument for me, but I just can’t help worrying about it. Will I, one day, face an enterprising young hacker who’d never considered it before but read an interesting book on hacking and went on to learn all he could? Maybe. But my guess, and hope, is that by that time the number of good guys will outweigh those on the other side. If not, I suppose the mirror is where we’ll all look for blame.

Attack Methodology

When you consider the sheer number of methodology steps EC-Council throws out there, it’s really a miracle anyone even bothers taking this exam. However, as I stated earlier, despite whatever you may think of their lack of relevance in the day-to-day life and actions of real pen testers and hackers, methodology steps from ECC are testable. Argue with me all you want, and flail your arms around and scoff at how dumb they are until you feel satisfied everyone knows you know they’re dumb. But if you ignore them, you’ll miss out on test questions. The choice is yours.

EC-Council defines six different stages in web server attack methodology: information gathering, web server footprinting, website mirroring, vulnerability scanning, session hijacking, and web server password cracking. Thankfully, when it comes to web server attack methodology, these aren’t so much phases to remember nor a step-by-step, foolproof method. Instead, they are recommendations on what to cover in your efforts so you don’t overlook something. I don’t believe you’ll be asked about them in order (in other words, “What represents step 4 in the web server attack methodology?”). Instead, they’re just here as ECC’s attempt at a good way to organize your thoughts and ensure something doesn’t get lost.

First off, you’ll start out with information gathering and footprinting. Web server information gathering is done using things like Internet searches about the target (traffic statistics and such), whois (we went over this little jewel back in Chapter 2), and reviewing the robots.txt file (a small file, made to be accessible and readable, that tells web spiders which pages not to crawl for indexing). Footprinting efforts in regard to web servers involve things like banner grabbing (check our scintillating write up on this in Chapter 3), and the use of a few tools more specialized for web server examinations. For example, Netcraft can provide some great high-level information. HTTPRecon and ID Serve work really well in identifying, reliably, the web server architecture and OS, and HTTPrint provides lots of really cool information.

Lastly, when it comes to footprinting and enumerating web servers, don’t discount that wonderful little tool we covered back in Chapter 3—nmap. There are a bajillion different methods in which to use nmap to scan and enumerate boxes, and web servers are no exception. Here are a few nmap commands you may find useful (in the real world and for your exam):

•   nmap --script http-trace -p80 localhost   Detects a vulnerable server that uses the TRACE method.

•   nmap --script http-google-email <host>   Lists e-mail accounts.

•   nmap --script hostmap-* <host>   Discovers virtual hosts on an IP address that you are attempting to footprint. The * character is replaced by the name of the online dB you’re attempting to query. For example, hostmap-IP2Hosts queries the dB at www.ip2hosts.com.

•   nmap --script http-enum -p80 <host>   Enumerates common web applications.

•   nmap -p80 --script http-robots.txt <host>   Grabs the robots.txt file.

Again, I find myself compelled to advise you to grab the tools and test them out for yourself. There are more nmap commands than we can possibly include here—these are just a few primary ones to play with. Run nmap scans against everything you own. Set up a web server in your lab and blast it with everything. It is, by far, the best way to learn.

Images

NOTE    A few other tools for web server footprinting you may wish to check out include Burp Suite (https://portswigger.net/burp), SpiderFoot (www.spiderfoot.net), XProbe (https://sourceforge.net), P0f (https://github.com), and Recon-ng (https://bitbucket.org).

Next in our methodology line is website mirroring, and it is exactly what it sounds like. Wouldn’t it be so much easier on you if you had a copy of the website right there in your own lab to examine? It’d save you all that pesky network traffic generation from your constant banging on the “live” site and give you loads of time to examine structure and whatnot. While it’s not necessarily the quietest thing in the world, nor is it always easy to obtain or always complete, if it’s possible to grab a mirror image of the website, go for it. Tools for pulling this off include, but are not limited to, Wget, BlackWidow, HTTrack, WebCopier Pro, Web Ripper, and SurfOffline.

In your next step, if you have a means to get it running against the web server, a vulnerability scanner will practically give you everything you need to gain access. Nessus is probably the most common vulnerability scanner available, but it’s certainly not the only option. Nikto is a vulnerability scanner more suited specifically for web servers. An open source tool, Nikto scans for virtually everything you can think of, including file problems, script errors, and server configuration errors. It can even be configured within Nessus to kick off a scan automatically when a web server is discovered! Plug-ins and signatures are numerous and varied, and they update automatically for you. The only drawback is that Nikto is a relatively noisy tool, much like Nessus and virtually every other vulnerability scanner, so you won’t be running it stealthily.

In any case, if there is a way to pull it off, a good vulnerability scan against a web server is about as close to a guarantee as anything we’ve talked about thus far. It won’t necessarily discover any bad unknowns, but it will show you the bad knowns, and that’s all you can hope for at this juncture. By their very design, websites are open to the world, and many—not all, but many—will have something overlooked. Take your time and be patient; eventually your efforts will pay off.

Images

NOTE    The last steps in web server methodology, session hijacking and password cracking, are covered more extensively elsewhere in this book. Chapter 9 covers session hijacking in full, and password cracking is covered in Chapter 5.

Web Server Architecture

At its most basic, a web server acts like any other server you already know about: it responds to requests from clients and provides a file or service in answer. This can be for any number of things in today’s world, but let’s just consider in this section the obvious exchange web servers were created for (we can cover some of the other craziness later). A request first comes from a client to open a TCP connection on (usually) port 80 or 443. After agreeing to the handshake on the page request, the server waits for an HTTP GET request from the client. This request asks for specific HTML code representing a website page. The server then looks through a storage area and finds the code that matches the request and provides it to the client.

This all sounds simple enough, but there’s really a multitude of issues to think about just in that exchange. How does the server validate what the client is asking for? Does the server respond only to specific verbiage in the request, or can it get confused and respond with other actions? Where are the actual files of HTML (and other) code stored, and how are the permissions assigned to them? I could go on and on, but I think you can understand my point—and to get to some of the answers to these questions, I believe it’s prudent we take some time and examine the makeup of the more common web servers in the marketplace.

Images

EXAM TIP    One thing bandied about a bit on exam study guides I’ve seen is the trifecta of web servers and where they should sit in the organization’s network. In short, web functions generally have three sides: a web front end (a server facing the Internet), an application server (internally, set up to do the work), and a database server (internally, for obvious purposes). You’ll need to know the common-sense 10,000-foot view of all of it—where the servers should sit and what they’re for.

When it comes to web servers, there are three major players on the block. According to web surveys conducted by W3Techs (www.w3techs.com), most web servers on the Internet are Apache (www.apache.org), making up 45.4 percent of the marketplace. Internet Information Services (IIS) servers, Microsoft’s web server platform that ruled the namespace for decades, not only fell in market share but continues its decline in popularity and finds itself in third place. So who’s in second? Nginx (https://www.nginx.com/, and pronounced “engine-x,”) now makes up 39.8 percent of all web servers on the Internet and is growing quickly in popularity: as a matter of fact, Nginx has increased in usage by 0.4 percent, while both Apache and IIS have dropped by 0.03 and 0.02 percent, respectively. Since its public release in 2004, Nginx has exploded in growth and is now in use by such recognizable Internet residents as Netflix, Hulu, the Discovery Channel, Dropbox, Pinterest, and a host of others.

Interestingly, ECC doesn’t even mention Nginx in the official courseware—instead choosing to only mention Apache and IIS architecture. Matter of fact, looking around at every piece of study material I can find, I don’t see anyone talking about it, and that concerns me. When we completed the edition for version 9, I was convinced it was very possible—scratch that, very probable—that by the time it found its way to print and you finished your study for the exam that Nginx would have over 30 percent of the market share. Turns out I was right, and now, given every piece of statistical evidence I can find, it’s highly probably that by time you actually take your exam, Nginx will make up nearly half the web servers in the world—and you won’t even be asked about it. In my humble opinion, that’s somewhat of a crime. I won’t spend a whole lot of time talking about Nginx, but it is part of the present and will make up a majority of the future. Despite its lack of coverage on your exam, you’ll need to learn Nginx basics to do your job.

Benchmarks prove Nginx edges out other lightweight web servers and proxies, and simply blows the doors off others (Linux Journal didn’t trust the press and ran their own tests, largely coming to the same conclusion). Per the Nginx site, Nginx is “a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. Unlike traditional servers, Nginx doesn’t rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load.” I guess it should come as no surprise that a high-performance web server that requires only small resources to run and has proven itself capable of running everything from small family sites to multinational clusters is a challenger to Microsoft and IIS. But when you throw in the fact that it’s free, then it’s not only a surprise—it’s to be expected. You won’t be tested on it anytime soon on the exam, but at the rate this brand is growing, you can bet you will soon—or you should be.

Images

EXAM TIP    Don’t get too concerned—you won’t be saddled with a lot of minutiae on the exam concerning the architecture of various web servers. If your goal is pure test study, you can breeze through much of this section. To help out, keep in mind a couple tips: First, Apache configuration is almost always done as part of a module within special files (http.conf, for instance, can be used to set server status), and the modules are appropriately named (mod_negotiation, for instance). Second, almost everything questioned on IIS configuration is going to come down to privileges, and IIS itself runs in the context of LOCAL_SYSTEM and will spawn shells accordingly.

Market leader Apache is an open source, powerful, and fast web server that typically runs on a Unix or Linux platform, although you can load and use it on a wide variety of operating systems. By and large, Apache servers haven’t seemed to display as many, or as serious, vulnerabilities as their Microsoft IIS peers, but this isn’t to say they are foolproof. Several critical vulnerabilities on Apache servers have come to light in the past, making them as easy a target as anything else.

Images

NOTE    The tier system is something you’ll need to be aware of in network design. N-tier architecture (a.k.a. multitier architecture) distributes processes across multiple servers. Each “tier” consists of a single role carried out by one (or more, or even a cluster of) computer systems. Typically this is carried out in “three-tier architecture,” with a presentation tier, logic tier, and data tier, but there are other implementations.

While we’re not diving so far down into this as to drown ourselves in details, you do need to know a little about the basics of Apache design and architecture. Apache is built modularly, with a core to hold all the “magic” and modules to perform a wide variety of functions. Additionally, because of its open source nature, there is a huge library of publicly available add-ons to support functions and services. If you’re really interested in seeing some of the modules and learning about how they work, Apache provides a write-up and details at http://httpd.apache.org/docs/current/mod/. Figure 6-1 shows a very brief, overly simplistic view of the whole thing in practice (note the database does not have to be in the same OS container; in fact, it really shouldn’t be).

Images


Figure 6-1 Apache

IIS servers are easy-to-manage, Windows-based options for the web provider. Originally, IIS was riddled with security concerns, and finding an IIS 5 or earlier server at your target is cause for wild celebration on the pen test team. Heck, even the IIS 7.0 version, which Microsoft said included “a new modular design that allows for a lessened attack surface and increased performance,” caused many a hacker to start giggling uncontrollably. Later versions, though, have done a much better job of tightening the security screws. Will IIS 10 answer the security bell? Time will tell.

Whether it’s an Apache or an IIS server, misconfiguration of the settings is the most common vulnerability that will be exploited. Areas of concern include error messaging, default passwords, SSL certificates, scripts, remote administrative functions, configuration files, and services on the machine. Settings such as properly configuring (restricting?) remote administration, eliminating unnecessary services, and changing any default passwords or accounts are pretty obvious things, but they’re so often overlooked it’s not even funny.

Others maybe aren’t as obvious, but should be concerning. What about error reporting? Sure, it’s helpful to you to leave on debug logging or to set everything to verbose when you’re trying to troubleshoot an issue, but isn’t that same information really useful to a bad guy? Are the SSL certificates in place current? What about default passwords? Are the config files and scripts properly protected and configured? Keep those configuration issues in mind when you start scratching at the front door; they’re usually keys that can open a lock or two.

Images

EXAM TIP    The httpd.conf file on Apache servers controls aspects including who can view the server status page (which just so happens to contain information on the server, hosts connected, and requests being attended to). The php.ini file is one you want to look at for the verbose error messaging setting.

Finally, in our discussion about web server architecture, I’d be remiss if I didn’t discuss the protocol behind the scenes in almost everything web related: HTTP. Don’t worry, I’m not going to send you running to the edge of the nearest cliff (or to the closest bourbon bottle—whatever your poison) with HTTP-minutiae madness. After all, this is a book on CEH, not one designed to make you a web designer. However, I do want to cover some of the basics that’ll help you in your job and on the exam.

First, a shocking revelation: Hypertext Transfer Protocol was originally designed to transfer hypertext (and hypertext, to borrow Wikipedia’s stellar definition, is “structured text that uses logical links, a.k.a. hyperlinks, between nodes containing text”). In other words, HTTP was designed as a request-response Application layer protocol where a client could request hypertext from a server. This hypertext could be modified and set up in such a way as to provide resources to the requesting user agent (UA)—for instance, a web browser.

For example, a client requests a particular resource using its Uniform Resource Identifier (URI)—most commonly expressed for web requests in the form of a URL (Uniform Resource Locator)—and a server responds to the HTTP request by providing the resource requested. In practice, HTTP can be used for virtually anything anymore—with good or bad intent. It also provides for (mostly) secure communication in its HTTPS version: HTTP over TLS, or HTTP over SSL. Although I could go on and on about other features of HTTP, including some well-known recent attacks against the secure version (see Chapter 11 for a discussion on Heartbleed and POODLE), what we really need to get to for your exam is the particular markup of hypertext most of us see every single day—HTML.

I think I’m safe in assuming that if you’re reading this book and consider yourself a candidate for the CEH certification, you’re probably already aware of what HTML is. For the sake of covering everything, HTML is simply a method to mark up hypertext so it will display accordingly in a browser. In other words, HTML files consist of a bunch of tags that tell the browser how to display the data inside. Tags such as <img>, <table>, and <body> are probably easily recognized by anyone. Others, such as <form>, <head>, <input type=___>, and so on, may not be, but they sure hold some interesting details for the observant.

Images

NOTE    Although it’s not really tested on the exam (yet), take a little time to explore XML. While HTML was designed specifically to display data, XML was created to transport and store data. XML tags are, basically, whatever you want them to be.

This simplicity makes HTML easy to work with but also has its own issues. For example, because tags start with the < character, it’s tough to put this character into the text of a page; as soon as the browser sees it, it thinks everything past it is a tag, until it sees the close character, >. To get around this, HTML entities were created. An HTML entity is a way of telling the browser to display those characters it would otherwise look at as a tag or part of the programming itself. There are tons of these entries, all of which you’ll see later and can use in your efforts to crawl and confuse web servers, but the big ones are noted in Table 6-1 (including the nonbreaking space, listed first).

Images


Table 6-1 HTML Entities

So now that you know a little on HTML, let’s take a closer look at HTTP. Specifically, we need to cover HTTP request methods. These are pretty straightforward and easy to understand, but they will worm their way into your exam at some point, so we’ll cover the basics here. HTTP works as a request-response protocol, and several request methods are available. HTTP request methods include GET, HEAD, POST, PUT, DELETE, TRACE, and CONNECT. The W3C provided a great rundown of these methods (https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html), so why not stick with what the international community on web standards say about them?

•   The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. In short, it basically requests data from a resource: “Please send me the HTML for the web page located at _insert-URL-here_.” The problem with it is designers—especially early on—used HTTP GET to send data as well, and when sending data, the GET method adds the data to the URL. For example, if a GET was used in answering a bill for a credit card, you might see the URL display like this: http://www.example.com/checkout?7568.asp/credit1234567890123456 (the underlined section showing the ridiculousness of using GET in this way).

•   The HEAD method is identical to GET except that the server must not return a message-body in the response. This method is often used for testing hypertext links for validity, accessibility, and recent modification, as well as for requesting headers and metadata.

•   The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. The actual function performed by the POST method is determined by the server and is usually dependent on the Request-URI. In short, it’s a better method of submitting data to a resource for processing. It can also be used to elicit a response, but its primary purpose is to provide data for the server to work with. POST is generally considered safer than GET because an admin can make it so it’s not stored in browser history or in the server logs, and it doesn’t display returned data in the URL.

•   The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity should be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI.

•   The DELETE method requests that the origin server delete the resource identified by the Request-URI.

•   The TRACE method is used to invoke a remote, Application layer loopback of the request message. The final recipient of the request should reflect the message received back to the client as the entity-body of a 200 (OK) response.

•   The CONNECT method is reserved for use with a proxy that can dynamically switch to being a tunnel (for example, SSL tunneling).

Images

NOTE    Both POST and GET are client-side ideas that can be manipulated with a web proxy. While GET is visible in a browser, POST is equally visible within a good-old Wireshark capture.

Last thing on HTTP (I promise) is a quick rundown on HTTP response messages. Why? Because you can glean information about your target based on what the protocol was designed to send back to you given a specific circumstance. I’m not going to dedicate a lot of page space to these because they’re barely mentioned on your exam, but they’re still very important.

The first digit of the Status-Code defines the class of response. The last two digits do not have any categorization role, but more thoroughly define the response intent. There are five values for the first digit:

•   1xx: Informational   Request received, continuing process.

•   2xx: Success   The action was successfully received, understood, and accepted.

•   3xx: Redirection   Further action must be taken in order to complete the request.

•   4xx: Client Error   The request contains bad syntax or cannot be fulfilled.

•   5xx: Server Error   The server failed to fulfill an apparently valid request.

See what I mean? Could sending a URL requesting a resource and receiving a 5xx message back help determine server issues? Maybe. A 4xx receipt? Better check my URL and see if it’s right. A 3xx return? That might be very interesting…

Images

EXAM TIP    Need something else to worry about, security-wise? Don’t forget about third-party scripts and apps. Many organizations make use of third-party scripts for functions such as marketing, and so on, that can be exploited to gain access to the server’s data.

Web Server Attacks

So, we know a little about web server architecture and have a little background information on the terminology, but the question remains, How do we hack them? It’s a good question, and one we’ll tackle in this section. Many other attack vectors also apply to web servers—password attacks, denial of service, man in the middle (sniffing), DNS poisoning (a.k.a. hijacking), and phishing—but there are many more. Web server attacks are broad, multiple, and varied, and we’ll hit the highlights here, both for your career and for your exam.

Images

EXAM TIP    DNS amplification is an attack manipulating recursive DNS to DoS a target. The bad guy uses a botnet to amplify DNS answers to the target until it can’t do anything else.

Directory traversal is one form of attack that’s common and successful, at least on older servers. To explore this attack, think about the web server architecture. When you get down to it, it’s basically a big set of files in folders, just like any other server you have on your network. The server software is designed to accept requests and answer by providing files from specific locations on the server. It follows, then, that there are other folders on the server (maybe even outside the website delivery world) that hold important commands and information.

For a broad example, suppose all of a website’s HTML files, images, and other items are located in a single folder (FOLDER_A) off the root of the machine, while all the administrative files for the server itself are located in a separate folder (FOLDER_B) off the root. Usually HTML requests come to the web server software asking for a web page, and by default the server goes to FOLDER_A to retrieve them. However, what if you could somehow send a request to the web server software that instead says, “Server, I know you normally go to FOLDER_A for HTML requests. But this time, would you please just jump up and over to FOLDER_B and execute this command?” Figure 6-2 shows this in action.

Images


Figure 6-2 Directory traversal

Welcome to directory traversal. In this attack, the hacker attempts to access restricted directories and execute commands outside intended web server directories. Also known as the dot-dot-slash attack, directory climbing, and backtracking, this attack basically sends HTTP requests asking the server to drop back to the root directory and give access to other folders. An example of just such a command might look like this:

Images

The dot-dot-slashes are intended to take the shell back to the root and then to pull up the password file. This may take a little trial and error, and it isn’t effective on servers that take steps to protect input validation, but it’s definitely worth your time.

Images

EXAM TIP    ECC sometimes likes asking about parameter or URL tampering. In short, you just manipulate parameters within the URL string in hopes of modifying data such as permissions and elevation of privileges, prices and quantities of goods, and credentials. The trick is to simply look at the URL and find parameters you can adjust and re-send.

A major problem with directory traversal is that it’s sometimes fairly noisy. Signature-based IDSs have rules in place to look for dot-dot-slash strings and the like. One method for getting around this is to use Unicode in the string to represent the dots and slashes. As you’re probably already aware, several Unicode strings can be used to represent characters and codes. In general, the %2e code can represent a dot, whereas %sf can represent a slash. Putting them together, your Unicode string would look like this:

Images

Additionally, don’t be afraid to mix up your Unicode in different variations; %2e%2e/ and ..%2f are examples.

Images

EXAM TIP    This dot-dot-slash attack is also known as a variant of Unicode or unvalidated input attack. Unicode is a standard for ensuring consistent encoding and text representation and can be accepted by servers for malicious purposes. Unvalidated input means the server has not been configured to accept only specific input during an HTTP GET, so an attacker can craft the request to ask for command prompts, to try administrative access passwords, and so on.

Another easy and simple attack vector involves manipulating the hidden field on the source code of the page. See, back in the day, web developers simply trusted users wouldn’t bother looking at the source code (assuming they were too stupid or apathetic), and they relied on poor coding practices. The thought was that if the users didn’t see it displayed in their browsers, they wouldn’t know it was there. To take advantage of this, developers used an HTML code attribute called “hidden.” Despite the fact that it’s a well-known but unsecured method to transmit data, especially on shopping sites, and it’s a generally accepted fact that the web page itself shouldn’t be holding this information, the use of the hidden attribute for pricing and other options is still pretty prevalent. To see how it works, check out the following code I took from a website I found today:

Images

Suppose I really wanted a surfboard but really didn’t want to pay $659.99 for it. I could simply save the code from this page to my desktop (being sure to check for Unicode encoding if prompted to), change the “price” value to something more reasonable (such as 9.99), save the code, and then open it in a browser. The same web page would appear, and when I clicked the Add To Cart button, the surfboard would be added to my cart, with a cost to me of $9.99. Obviously, this amounts to theft, and you could get into a world of trouble trying this, so please don’t be ridiculous and attempt this. The idea here isn’t to show you how to steal things; it’s to show you how poor coding can cost a business. Not to mention, the hidden field can carry other things too. For example, might the following line, which I found on another forum website earlier, be of interest to you?

Images

Another attack you should focus some study time on is dubbed “web cache poisoning.” A web cache is a just storage space that sits between a web server and a client (like a web browser or a mobile app). It waits for network requests to come in and saves copies of the responses. Why? Because the entire idea of the cache is to speed up responses to future requests. If you ask the server for something and then later I ask for the same thing, it’s faster to pull the cache response for me than to re-create all the processing to answer the same question. In short, caches speed up delivery, make web services appear more responsive, and theoretically at least, help reduce network traffic. But can you see where that could be problematic from a security perspective? Suppose an attacker clears the cache on a target, then replaces it with something he wants in there. The cache response can then wreck all sorts of havoc among visitors to the server.

To successfully carry out the attack, a bad guy must first find vulnerable service code (allowing him to fill the HTTP header field with multiple headers). He then forces the cache server to flush its actual cache content and sends a specially crafted request designed to be stored in cache. He then sends a second request, forcing the response to be the previously injected content from earlier. And voilà—cache poisoning is exploited. Check out Figure 6-3 for an overview of the whole thing.

Images


Figure 6-3 Web cache poisoning

Images

EXAM TIP    One web attack tool you’ll need to become familiar with is WFETCH (Microsoft.com). It allows you to craft HTTP requests to see raw request and response data, as well as to pull off performance tests and other assessments.

Other web attacks covered by ECC are fairly self-explanatory. A misconfiguration attack takes advantage of configuration items on the server not being configured correctly. A password attack and SSH brute-force attack? Exactly what they sound like. Web defacement attacks are the unique ones in the “obvious list of web attacks,” but only because of what ECC focuses on.

Images

NOTE    CSPP (connection string parameter pollution) is an injection attack that takes advantage of web applications that communicate with databases by using semicolons to separate each parameter. It has been around since 2010, but there’s not much written about it or attention paid to it, for whatever reason. If carried out successfully, this attack can be used to steal user identities and hijack web credentials.

A web defacement attack results in the page being…well, defaced: an attacker maliciously alters the visual appearance of the page. Interestingly, ECC doesn’t bother to talk about how an attacker would get in to do this, only the results of that pwning (pwning being a variant of the “leetspeak” term pwn, pronounced pōwn, and meant to imply domination or humiliation of a rival, or that a system has been owned). In short, if the hacker is dumb enough to change the visual on the site, alerting everyone in the world that he got it, that’s considered defacement.

Images

NOTE    Defacement doesn’t always have to be about embarrassment or feeding an ego. Sometimes defacement can be downright subtle, for whatever purpose, and sometimes it can be designed to inflict real harm on a target. If, for example, you were to deface the website of a candidate running for office and quietly alter wording to indicate a change in platform, it may not be noticed for a long while. And by the time it is, the damage is done.

Finally, you can use a variety of tools to help in web server attacks—some of which we’ll hit later in the chapter, many of which you just need to play with in order to learn. Brutus (www.hoobie.net) is a decent choice to try brute-forcing web passwords over HTTP, and THC-Hydra is a pretty fast network logon cracker. And don’t overlook the all-in-one attack frameworks such as Metasploit; these can make short work of web servers.

The S in Sisyphus Is for “Security”

So, you know the story of King Sisyphus from Greek mythology, right? Actually, it’s probably not fair to ask if you’ve heard the story, because there are bunches of them all leading to the same end. Maybe it is more apropos to ask if you’re familiar with his punishment, so let’s start there. See, King Sisyphus was a smart but deceitful man. In numerous versions of the story in mythology he used these “gifts” to outsmart the gods, ensnaring Hades in chains so that no one on Earth could die. I suppose he may have even eventually gotten away with that; however, in addition to being smart and deceitful, he was also arrogant and brash. After letting everyone know he felt his cleverness was greater than that of Zeus, he was given a most unique punishment. King Sisyphus was doomed in eternity to roll a giant boulder up a mountain. However, as soon as the boulder got almost to the top, it would magically roll away from him back down the mountainside, forcing him to start all over. Hence, any pointless or never-ending activity came to be known as Sisyphean in nature. And that’s why I’m convinced the first IT security engineer was his descendant.

A guy asked me a while back, “If I’m following good security principles, how is hacking even possible?” He had taken care of all the crazy default passwords and settings on his system. He had patched it thoroughly. He’d set up monitoring of both network traffic and file integrity itself. He had done everything he could possibly think of security-wise, and he smugly told me that hacking his box was impossible. I then shattered his naiveté by saying, “Congratulations. You’re right. Today. Just remember that you will always have to be right every other day, too—and I have to be right only once.”

Time is definitely on the side of the hacker because things consistently change in our virtual world. New vulnerabilities and new ways around security features come out every single day, and it’s—dare, I say—a Sisyphean task to continue monitoring for, and applying, security fixes to systems. The only way we, on the security side, can win? Stop pushing the boulder at all and just unplug everything. Until then, all we can do is get more of us pushing that rock up the hill—and somebody to distract Zeus when we get to the top.

Metasploit (introduced in Chapter 5) will cover lots of options for you, including exploitation of known vulnerabilities and attacking passwords over Telnet, SSH, and HTTP. A basic Metasploit exploit module consists of five actions: select the exploit you want to use, configure the various options within the exploit, select a target, select the payload (that is, what you want to execute on the target machine), and then launch the exploit. Simply find a web server within your target subnet, and fire away!

Images

NOTE    I’m not saying YouTube videos always show the best, or even proper, usage of any tool, but there are innumerable videos showing Metasploit in action, and sometimes the best way to learn is just watching someone use it. Speaking of free training, check out https://www.offensive-security.com/metasploit-unleashed/ and give the free class/book a try. In fact, type Learn Metasploit in your favorite browser and make use of what’s out there.

You won’t get asked a whole lot of in-depth questions on Metasploit, but you do have to know the basics of using it and some of what makes the whole thing run. It’s called a framework for a reason—it’s a toolkit that allows for exploit development and research. A high-level overview of Metasploit architecture is shown in Figure 6-4. The framework base accepts inputs from custom plug-ins, interfaces (how you interact with the framework), security tools, web services, and modules (each with its own specific purpose). Under MODULES, for example, EXPLOITS would hold the actual exploit itself (which you can play with, alter, configure, and encapsulate as you see fit), while PAYLOADS combines the arbitrary code executed if the exploit is successful. AUXILIARY is used to run one-off actions (like a scan), while NOPS is used mainly for buffer-overflow-type operations. REX, right there in the middle of the figure, is the library for most tasks, such as handling sockets, protocols, and text transformations.

Images


Figure 6-4 Metasploit

Images

EXAM TIP    Read up on Shellshock (a.k.a. Bashdoor). It’s not a web server attack per se, but since many Internet-facing services and some web server deployments use Bash to process certain requests, it’s worth mentioning here. Shellshock works by causing Bash to unintentionally execute commands when the commands are concatenated (usually via CGI) to the end of function definitions stored in the values of environment variables.

Attacking Web Applications

Web applications are another issue altogether, although many of the same attacks and lines of reasoning will bleed over here from the web server side. As a matter of fact, a good three quarters of the official courseware chapter devoted to web applications is a near rewrite of the web server chapter. However, there is some good stuff here you’ll need to know and, as anyone who’s been on a pen test team over the past few years or so will attest, you’ll probably see as much success and as many results from your efforts against the web applications themselves than anything else.

A web application, in terms of your CEH exam, fills an important gap between the website front end and the actual database performing the work. Users interact with the website to affect database or other dynamic content instances, but it’s the web app that’s actually performing the magic. Web applications are increasingly becoming an attack vector of choice, due in large part to their sheer numbers and the lack of standardization across the board. Many web apps are created “in house” by the business and, as a result, usually have vulnerabilities built in because of a lack of security oversight during their creation. This section is all about the attacks you might see and use in hacking web applications. And don’t be surprised if there is bleed over between web application and web server hacking—it’s all part of attaining the same goal.

Web applications are most often hacked because of inherent weaknesses built into the program at inception. Developers might overlook known vulnerabilities, forget to patch security flaws, or leave default passwords and accounts open for exploitation. A patient hacker can scratch away at the application looking for these vulnerabilities, eventually finding a way in. It’s obviously impossible to cover every single one of these vulnerabilities and the attacks that work on them because each is dependent on the circumstances and the individual application. For now, we’ll just concentrate efforts on a few and see where we get.

Identifying entry points is a good place to start. After all, if you can figure out where the application is asking you for input, you’re already looking at a way in. To accomplish this, be sure to examine cookies, headers, POST data, and encoding or encryption measures. And for goodness sake, don’t ignore the obvious—the URL can tell you a lot (input parameters and such are often displayed there). There are several tools that can help in identifying your entry points, including WebScarab, HTTPrint, and Burp Suite.

Identifying function and technology on the server side helps greatly as well. You can sometimes browse through URLs and get a good idea of server makeup, form, and function. For example, consider the following URL:

https://anybiz.com/agents.aspx?name=ex%50clients&isActive=0&inDate=20%2F11%2F2012&stopDate=20%2F05%2F2013&showBy=name

The platform is shown easily enough (aspx), and we can even see a couple column headers from the back-end database (inDate, stopDate, and name). Error messages and session tokens can also provide valuable information on server-side technology, if you’re paying attention. A really good way to get this done is mirroring, which provides you with all the time you need on a local copy to check things out. You won’t be able to get actual code, but it will give you time to figure out the best way into the real site for future analysis.

Images

NOTE    Heard of Web 2.0 yet? No, it’s not another Internet speak for “exponentially intelligent people,” nor does it refer to any technical specification update. It simply refers to a somewhat different method of creating websites and applications: while 1.0 relies on static HTML, 2.0 uses “dynamic” web pages. Because they’re dynamic in nature, 2.0 apps allow users to upload and download to a site simultaneously, which provides much better infrastructure for social media and other user participation efforts. Per ECC, because Web 2.0 apps provide for more dynamic user participation, they also offer more attack surface.

Application Attacks

If you haven’t seen the official courseware for CEH study, it’s a nightmare. It’s delivered within the “Aspen” learning systems in EC-Council, and is available in “downloadable” PDFs. The PDF files are locked—you can’t select and copy anything to help improve your own study—and the built-in protections prevent screen capture software from even giving you a shot at reviewing things later. Add to it the fact that the site forces constant authentication challenges and, wow, it can get frustrating. Each chapter in the guide is nothing but slides—the same slides used in ECC’s official CEH class—covering everything ECC wants you to know as an ethical hacker. The web supplication chapter within this insanity is gigantic. When you consider there is an additional, separate chapter for injection attacks (SQL), with its own giant page count, you can see that this can get out of hand pretty quickly.

Why am I boring you with this? Mainly as a warning: as I said way back in Chapter 1, this information updates and changes a lot, so be prepared—you’re going to need to practice this stuff as much as possible, and you’ll probably see one or two new items on your exam we may not have even heard of as of this writing. We’ll do the best we can to cover everything we know about today, and hope anything new popping up will be so evident you’ll come across it during practice and your own research. Thankfully, we have a couple things going for us. First is, I know what I’m doing (at least I think I do) and will get the relevant information out to you—not to mention OWASP has tons of free stuff out on their site for us to review on given attacks. Second is, most of this section is very similar to the information we covered on web server attacks and security in the first half of this chapter. We’ll hit these in rapid fire format, so get ready!

Injection Attacks Not Named SQL

One successful web application attack deals with injecting malicious commands into the input string. The objective is much like that of the parameter-tampering methods discussed earlier in this chapter: to pass exploit code to the server through poorly designed input validation in the application. This can occur using a variety of different methods, including file injection (where the attacker injects a pointer in the web form input to an exploit hosted on a remote site), command injection (where the attacker injects commands into the form fields instead of the expected test entry), and shell injection (where the attacker attempts to gain shell access using Java or other functions).

LDAP injection is an attack that exploits applications that construct LDAP statements based on user input. To be more specific, it exploits nonvalidated web input that passes LDAP queries. In other words, if a web application takes whatever is entered into the form field and passes it directly as an LDAP query, an attacker can inject code to do all kinds of things. You’d think this kind of thing could never happen, but you’d be surprised just how lazy a lot of code guys are.

For example, suppose a web application allows managers to pull information about their projects and employees by logging in, setting permissions, and providing answers to queries based on those permissions. Manager Matt logs in every morning to check on his folks by entering his username and password into two boxes on a form, and his login is parsed into an LDAP query (to validate who he is). The LDAP query would look something like

Images

which basically says, “Check to see whether the username Matt matches the password MyPwd! If it’s valid, login is successful and off he goes.”

In an LDAP injection attack, the attacker changes what’s entered into the form field by adding the characters)(&) after the username and then providing any password (see Figure 6-5). Because the & symbol ends the query, only the first part—“check to see whether Matt is a valid user”—is processed and, therefore, any password will work. The LDAP query looks like this in the attack:

Images


Figure 6-5 LDAP injection

Images

This basically says, “Check to see whether you have a user named Matt. If he’s there, cool—let’s just let him do whatever he wants.” While there’s a lot of other things you can do with this, I think the point is made: don’t discount something even this simple because you never know what you’ll be able to find with it.

Images

EXAM TIP    SOAP injection is another related attack. Simple Object Access Protocol (SOAP) is designed to exchange structured information in web services in computer networks and uses XML to format information. You can inject malicious query strings (much like SQL injection, as a matter of fact) that may allow you to bypass authentication and access databases behind the scenes. SOAP is compatible with HTTP and SMTP, and messages are typically “one way” in nature.

Buffer Overflow

A buffer overflow attack is one that should never be successful in modern technology but still remains a great weapon in your arsenal because of poorly designed applications. To truly use this attack, you’re probably going to have to become a good computer programmer, which I’m sure just excites you to no end. The good news on this, though, is twofold. First, many Metasploit-like tools make this much easier for you to attempt. Second, you only need to know the basic mechanics of the attack for your CEH exam, and it’s barely mentioned anymore. In the real world, the best hackers are usually exceptional programmers—it’s just a fact of life. As far as your exam is concerned, you need know only a few things to succeed.

Images

NOTE    Some buffer overflow attacks are also referred to as smashing the stack. The name came from a presentation that has become one of the founding documents of hacking, “Smashing the Stack for Fun and Profit,” by Aleph One (for Phrack 49). The original write-up can be found in numerous places with any Internet search engine and is worth a read.

The most basic definition of a buffer overflow is an attempt to write more data into an application’s prebuilt buffer area in order to overwrite adjacent memory, execute code, or crash a system (application). In short, you input more data than the buffer is allocated to hold. The result can be anything from crashing the application or machine to altering the application’s data pointers, allowing you to run different executable code. ECC used to have several categories and memorization terms for you in regard to buffer overflows (like stack, heap, NOP sleds, and so on), but the latest version doesn’t seem to care much about it at all.

In addition to good coding techniques, to avoid allowing the overflow in the first place, sometimes developers can use “canaries” or “canary words.” The idea comes from the old mining days, when canaries were kept in cages in various places in a mine. The canary was more susceptible to poison air and would, therefore, act as a warning to the miners. In buffer overflow and programming parlance, canary words are known values placed between the buffer and control data. If a buffer overflow occurs, the canary word will be altered first, triggering a halt to the system. Tools such as StackGuard make use of this for stack protection.

Images

NOTE    All of these are memory management attacks that take advantage of how operating systems store information. While canary words are good for test purposes, address space layout randomization (ASLR) and data execution prevention (DEP) are extremely common mechanisms to fight most of these attacks.

XSS

The next web application/server attack is cross-site scripting (XSS). This can get a little confusing, but the basics of this attack revolve around website design, dynamic content, and invalidated input data. Usually when a web form pops up, the user inputs something, and then some script dynamically changes the appearance or behavior of the website based on what has been entered. XSS occurs when the bad guys take advantage of that scripting (JavaScript, for instance) and have it perform something other than the intended response.

For example, suppose instead of entering what you’re supposed to enter in a form field, you enter an actual script. The server then does what it’s supposed to—it processes the code sent from an authorized user. Wham! The attacker just injected malicious script within a legitimate request and…hack city.

Images

EXAM TIP    You’ll need to know what XSS is and what you can do with it. Also, be able to recognize that a URL such as the following is an indicator of an XSS attempt: http://IPADDRESS/";!--"<XSS>=&{()}. Instead of the URL passing to an existing page/element internally, it passes to the script behind the forward slash.

XSS attempts pop up all over the place in several formats. One of the classic attacks of XSS involves getting access to “document.cookie” and sending it to a remote host. Suppose, for example, you used the following in a form field entry instead of providing your name:

Images

Should the app be vulnerable to XSS, the Java script entered (converted to HTML entities where appropriate—how fun!) will be run and you can obtain cookies from users accessing the page later. Neat!

XSS can be used to perform all kinds of badness on a target server. Can you bring a target down with a good old DoS attack? Why not? Can I send an XSS attack via e-mail? Of course! How about having the injected script remain permanently on the target server (like in a database, message forum, visitor log, or comment field)? Please—that one even has a name (stored XSS, a.k.a. persistent or Type-I XSS). It can also be used to upload malicious code to users connected to the server, to send pop-up messages to users, and to steal virtually anything. That PHP session ID that identifies the user to the website stolen through an XSS? Well, the attacker has it now and can masquerade as the user all day, plugged into a session.

Images

NOTE    The XSSed project (www.xssed.com), created in 2007, and is an excellent resource on all things related to cross-site scripting vulnerabilities. Per the site, it is the largest online archive of XSS vulnerable websites and was started to increase security and privacy on the web. Professional and amateur webmasters and web developers are notified about any cross-site scripting vulnerability affecting their online properties. May definitely be worth checking out!

XSS attacks can vary by application and by browser and can range from nuisance to severe impact, depending on what the attacker chooses to do. Thankfully ECC doesn’t bog down the exam with tons of scripting knowledge. XSS question will be somewhat general in nature, although you will occasionally see a scenario-type question involving a diagram and a script input.

Cross-Site Request Forgery (CSRF)

A cross-site request forgery (CSRF) is a fun attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated. OWASP has such a cool explanation of this attack from their free documentation, so I thought we’d start there:

CSRF tricks the victim into submitting a malicious request. It inherits the identity and privileges of the victim to perform an undesired function on the victim’s behalf. For most sites, browser requests automatically include any credentials associated with the site, such as the user’s session cookie, IP address, Windows domain credentials, and so forth. Therefore, if the user is currently authenticated to the site, the site will have no way to distinguish between the forged request sent by the victim and a legitimate request sent by the victim. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.

Images

EXAM TIP    A session fixation attack is somewhat similar to CSRF. The attacker logs in to a legitimate site and pulls a session ID, and then sends an e-mail with a link containing the fixed session ID. When the user clicks it and logs in to the same legitimate site, the hacker can now log in and run with the user’s credentials.

Imagine if you added a little social engineering to the mix. Just send a link via e-mail or chat, and—boom!—you can now get the users of a web application into executing whatever actions you choose. Check out Figure 6-6 for a visual of the whole thing in action.

Images


Figure 6-6 CSRF

If you’re a security-minded person and are wondering what you can do about this, relax—the answer is right here. CSRF attacks can be mitigated by configuring a web server to send random challenge tokens. If every user request includes the challenge token, it becomes easy to spot illegitimate requests not initiated by the user.

Cookies

A cookie is a small text-based file that is stored on your system for use by the web server the next time you log in. It can contain information such as authentication details, site preferences, shopping cart contents, and session details. Cookies are sent in the header of an HTTP response from a web server and may or may not have an expiration date. The original intent was to provide a continuous, stable web view for customers and to make things easier for return surfers.

The problem, of course, is that seemingly everything designed to make our technological life easier can be co-opted for evil. Cookies can definitely prove valuable to the hacker, and a tool such as the Cookie Editor add-on for Firefox opens up parameter-tampering opportunities. Cookies themselves aren’t executable; they’re just text files, after all. However, they can be manipulated to use as spyware (cookies can be used to track computer activity), change pricing options, and even authenticate to a server. For example, an entry in a cookie reading “ADMIN=no” can be changed to “ADMIN=yes,” thus providing administrative access to site controls.

Images

NOTE    Ever heard of a CAPTCHA? Of course you have—you’ve filled in the little numbers verifying you’re a real person before. Did you know those can be hijacked as well? CAPTCHAs can manipulate all sorts of server-side nonsense when abused.

Passwords can sometimes also be stored in cookies, and although it’s a horrible practice, it’s still fairly prevalent. Access to a target’s physical machine and the use of a tool to view the cookies stored on it (such as Karen’s Cookie Viewer) might give you access to passwords the user has for various websites. And, if they are like most people, it’s nearly a guarantee that the password you just lifted is being reused on another site or account. Additionally, don’t be thrown off by cookies with long, seemingly senseless text strings beside the user ID sections. On a few, you may be able to run them through a Unicode (or Base64) decoder to reveal the user’s password for that site.

SQL Injection

Because this is such an important topic in the world of hacking and web security, we need to set some ground rules and expectations first. SQL injection is, by far, the most common and most successful injection attack technique in the world. Remember OWASP’s Top 10? Injection was at the top of the list, and SQL injection is at the top of that list. It pops up nearly everywhere—the next big credit card theft story you read will, most likely, be because of a SQL injection attack of some sort. And, of course, ECC dedicated an entire chapter of official courseware study to the topic. All of which should lead you to believe, then, that mastering SQL is a skill you will want to gain as a successful ethical hacker. And although that is true, it’s not what we’re going to do here.

Becoming a SQL master is not what this book is about, nor do I have the space or time to cover every facet of it—or even most of facets, for that matter. As a matter of fact, even ECC’s coverage of the topic is largely…pedestrian in nature. There are lots of slides, words, samples, and images to be sure, but most of it is repetitive for items covered elsewhere and barely grazes the surface of what SQL is and how to use it.

My job here is twofold. Primarily it’s to help you pass the test, and secondarily it’s to assist you in becoming a true ethical hacker. You’re going to get the basics here—both for your exam and your career—but it’s going to be just enough to whet your appetite. If you really want to become a seasoned master at this, study SQL and learn all you can about how it works. As I’ve said repeatedly already, a single book simply can’t cover it all. You’ll be a better hacker, and a better IT professional all around, by doing a little research on your own and practicing. Now, on with the show.

Structured Query Language (SQL) is a computer language designed for managing data in a relational database system. The relational database is simply a collection of tables (consisting of rows, which hold individual fields containing data) tied together using some common field (key) that you can update and query. Each table has a name given to it that is referenced when you perform queries or updates. SQL comes into play when you are adding, deleting, moving, updating, or viewing the data in those tables and fields. It’s not too overwhelmingly complicated to do the simple stuff, but the SQL queries can, eventually, get pretty complex.

Images

NOTE    SQL encompasses three standard areas of data handling—definition (DDL), manipulation (DML), and control (DCL). Most SQL injections are within the DML part of SQL.

For example, let’s consider the SELECT command. SELECT is used to choose the data you’d like to perform an action on. The statement starts, amazingly enough, with the word SELECT, followed by innumerable options and elements to define what you want to act upon and what that action will be. For example, a command of

Images

says, “Database, I’d like you to pull all records from the table named Orders.” Tweaked a little, you can get more granular. For example,

Images

will pull everything in the order ID, first name, and last name columns from the table named Orders. When you start adding other command options such as WHERE (setting up a conditional statement), LIKE (defining a condition where something is similar to a given variable), AND, and OR (self-explanatory), you can get even crazier. For example,

Images

will pull all orders made by some dude with the last name of Walker.

In addition to SELECT, there are a bunch of other options and commands of great interest to a hacker. For example, can you—with no other SQL experience or knowledge—figure out what the command DROP TABLE tablename does? Any of you who didn’t respond with “Delete the table tablename from the database” should immediately start taking Ginkoba to improve your cognitive and deductive skills. How about the commands INSERT and UPDATE? As you can see, SQL isn’t rocket science. It is, though, powerful and commands a lot of respect. Researching command language syntax for everything SQL can offer will pay off dividends in your career—trust me on this.

So, you know a little about SQL databases, and have a basic understanding of how to craft query commands, but the big question is, “So what? Why is this so important?” In answer, pause for just a moment and consider where a database might reside in a web server/application arena you’re trying to hack and what it’s there to do. The front end takes input from the user through the web server and passes it through an application or form to the database to actually adjust the data. And what, pray tell, is on this database? Maybe items such as credit card account numbers, personally identifiable information, and account numbers and passwords don’t interest you, but I promise you can find all of that and more in a web-serviced database.

Images

NOTE    Just so you know, the semicolon doesn’t necessarily have to be at the end of every statement; however, some platforms freak out without it. Add it to be safe.

SQL injection occurs when the attacker injects SQL queries directly into the input form. Properly constructed, the SQL command bypasses the intent of the front end and executes directly on the SQL database. For example, consider Figure 6-7 and the sample SQL shown there. The form is constructed to accept a user ID and password from the user. These entries are placed into a SQL query that says, “Please compare the username given to the password in its associated field. If this username matches this password, allow access.” What we injected changed the original query to say, “You can compare whatever you’d like, but 1=1 is a true statement, so allow access please.”

Images


Figure 6-7 SQL injection

Images

NOTE    You can also try SQL injection up in the URL itself. For example, you can try to pass authentication credentials by changing the URL to read something like this: www.example.com/?login='OR1=1--.

Of course, knowing this isn’t any good to you if you can’t figure out whether the target site is vulnerable to SQL injection in the first place. To find out, check your target for a web login page, and instead of entering what’s asked at the web form, simply try a single quote (') and see what kind of error message, if any, you receive. If that doesn’t work, try entering anything'or 1=1- and see what you get. If you receive an error message like the one shown in Figure 6-8, you’re more than likely looking at a site vulnerable to SQL injection.

Images


Figure 6-8 SQL error message

Most developers are familiar with this little SQL “test,” and lots of things have been done to prevent its use. Many C++ and .NET applications now simply explode with errors when they are sent a single quote (or some variant thereof) and other special characters, and this input never even gets processed by the application. Another effort involves the so-called magic quotes in Apache, which filters out (escape) the characters before the application ever sees them. Of course, “fuzzing attack” tools such as Burp can make use of the error messaging to point out the underlying potential vulnerabilities on the system.

Images

NOTE    Fuzz testing involves inputting bunches of random data into a target (a site, an application, anything) to see what will happen. Designers work on code for data inputs they expect a customer to input; however, whether intentionally or not, input data not even close to what’s expected may be ingested. While we mention it here in terms of SQL injection, fuzzing is used on tons of different stuff.

To see SQL in action, consider a website that has a “Forgot your password? Click here and we’ll send it to you” message. After clicking the button, you get a pop-up window asking you to insert your e-mail address. You type it in and press ENTER, and your password is e-mailed to your account on file. Well, what if you send a SQL command in the form instead and ask the database to create (INSERT) a new record in the user and password table just for you? The command

Images

says to the database, “Database, you have a table there named cust. I think that probably stands for customers. So if you would, please enter into the fields labeled Email, Password, Userid, FirstName, and LastName these new values I’m supplying for you. Thank you, and hack ya later.”

For that matter, if you’re at a site requiring login, why not just try bypassing the authentication altogether? Try logging in using SQL statements. For example,

Images

might be beneficial. You can also try the old standby

Images

or some variation thereof, such as

Images

or

Images

In any case, you can find bunches of these types of SQL strings to try on the Internet. One cautionary note, though: brute-forcing SQL this way isn’t the quietest means of gaining access. If you’re banging away with 10,000 variations of a single open quote, you’re going to get noticed.

There are tons of SQL injection examples and just as many names given for the attacks. We can’t cover them all here, but EC-Council was kind enough to split all of them into three main categories for us:

•   In-band SQL injection   This is SQL injection where the attacker is using the same communication channel to perform and retrieve the results of the attack. This is the most commonly used type. Examples are Union Query attacks (the UNION command allows you to join together SELECT queries; for example, SELECT fname,lname FROM users WHERE id=$id UNION ALL SELECT socialsecuritynumber,1 FROM secretstuff; combines a relatively harmless query with one that’s a little more…useful), error-based (the objective is to purposely enter poorly constructed statements in an effort to get the database to respond with table names and other information in its error messages), tautology (an overly complex term used to describe the behavior of a database system when deciding whether a statement is true; because user IDs and passwords are often compared and the “true” measure allows access, if you trick the database by providing something that is already true [1 does, indeed, equal 1], then you can sneak by), and end-of-line/inline comments.

•   Out-of-band SQL injection   Contrary to in-band, this type of SQL injection uses different communication channels for the attack and results. It’s also more difficult to pull off.

•   Blind/inferential   This type occurs when the attacker knows the database is susceptible to injection, but the error messages and screen returns don’t come back to the attacker (not to mention results are oftentimes Boolean in return). Because there’s a lot of guesswork and trial and error, this attack takes a long while to pull off.

Images

EXAM TIP    Another in-band attack is known as “piggybacking.” The idea is simple—just add your malicious request on the back of a legitimate one. Also, as an aside, please keep in mind that anything other than basic SQL will have some significant semantic differences, so always Google the database version you’re trying.

As always, you can peck around with this stuff and learn it manually, or you can take advantage of tools already created to make your job easier. Sqlmap and sqlninja are both automated scanners designed to look specifically for injection vulnerabilities. Another one I’ve seen in play is called Havij, which allows enumeration, code execution on the target, file system manipulation, and other madness over SQL connections. SQLBrute is a tool that, amazingly enough, allows you to blast through predefined SQL injection queries against a target. Others include Pangolin, SQLExec, Absinthe, and BobCat.

Images

NOTE    Protection against SQL injection usually comes down to security-minded web and database design in the first place. However, you can make use of tools and signatures to at least monitor for attempts; for one example, you can check the Snort signatures for prebuilt SQL rules and then block or monitor for attempts using the signatures.

HTTP Attack

Another neat little attack is called HTTP response splitting. The attack works by adding header response data to an input field so that the server splits the response in a couple directions. If it works, the attacker controls the content of the second header, which can be used for any number of things—like redirecting the user to a malicious site the attacker runs. OWASP calls HTTP response splitting “a means to an end, not an end in itself,” because the attack is designed to allow other attacks (through the second header content) to work.

One final thought on web application testing is that it isn’t actually a hack at all, but it sure is productive. A common method of security testing (hacking) a web application is to simply try using it in a manner in which it wasn’t intended to be used. This isn’t applying some groovy hacker tool or scripting code to inject through some James Bond type of ploy; it’s just trying different things with an application—sometimes even by accident. As many a tester will say, with a chuckle in his voice, “It’s not a hack; it’s a feature.”

Sometimes This Is Depressing

Oftentimes in writing, I get into a zone and just excitedly start pounding away on the keyboard—excitedly looking up information on how something works or reading about a cool new tool or option for us to use. But every once in a while, I start reading things and get really bummed out over the seeming futility of my chosen profession. The raw numbers of what is stacked against us are downright terrifying.

For example, did you know that according to Google’s own website security report there was a 32 percent increase in the number of successful website attacks in 2016? A 32 percent increase during a timeframe in which cyber security is at the forefront of the news and we’re pumping out more security graduates and certified professionals than ever before. Even more astounding than that is the fact that 61 percent of those web administrators had no idea the attacks were successful. And according to a report from Imperva (a cyber security company), half of all website visitors are bots and, of those, approximately 29 percent of all your “visitors” are there to attack your site.

Want more? I found this little gem of a story in a ZDNET article I was reading today (https://www.zdnet.com/article/your-website-is-under-constant-attack/): Honeynet, an international non-profit security research organization, with help from students at Holberton School, recently set up a honeypot to track security attacks on a cloud-based web server. The box ran on a barebones Amazon Web Services (AWS) instance, with no services that would (should) be useful to anybody else. It did not even have a domain name. Shortly after starting the server, they started capturing network packets for a 24-hour period and then analyzed the packet capture file. In a day, this unnamed, almost invisible web server was attacked more than a quarter of a million times.

And that’s just the attackers intending to do you harm. A story from Wired.com (https://www.wired.com/story/mirai-botnet-minecraft-scam-brought-down-the-internet/) will just about bring you to tears. On a Friday afternoon in October 2016, the Internet slowed or stopped for nearly the entire eastern United States. Dyn, a company providing a key part of the Internet’s backbone, came under a DDoS assault the likes of which no one had ever seen before: until then, a large DDoS attack was often considered to be 10 to 20 Gbps (gigabits per second), while a follow-on Mirai attack against OVH hit a whopping 901 Gbps. And where did it all come from? Who were the masterminds behind one of the world’s most sophisticated DDoS attacks in history and what were they out to gain?

A 21-year-old Rutgers college student from suburban New Jersey and his two college-age friends admitted their role in creating and launching “Mirai,” as the bot came to be known, into the world. Why? To gain an advantage in the game Minecraft. Minecraft…

Think about all that for a minute. In 24 hours, a no-name, no-nothing VM in AWS was attacked a quarter of a million times. Today, almost half your website visitors are bots intending you ill will. And somewhere in your organization, statistically, at least one of your systems has fallen prey to some form of attack that you’re probably completely in the dark about. And kids using sites to DDoS opponents in video games (yes that’s real, you can actually pay a site to DDoS some guy playing _insert-game-here_) can accidentally cripple communications for millions of folks.

It’s enough to make you wonder how we can keep up.

But that’s the challenge, fellow security professionals. It’s our burden to bear. It’s the role we play in making our world a better place. So during those long days of reviewing code, or challenging ridiculous arguments in security evaluation and budget meetings, or staring at a screen so long your eyes dry out, just remember what you’re here for. Because without security folks at least attempting to stem the tide, we’d have all been washed away long ago.

Countermeasures

So, what’s left to do with all these attacks and such aimed at our (by design) public-facing servers? While the attack vectors are always changing and this war will never end, there are a few things that should be put into place to help. For example, placement of the servers is extremely important. We discussed DMZs, zones, and firewalls earlier, and this is where that information can be put into play. Don’t allow access into your internal network from the public, and don’t put servers the public should be accessing in the internal network. Not only can placement avoid attacks, but it can limit damage if your servers were to be exploited.

Keeping up with security patching is an absolute necessity. Unfortunately, even in the most imposing of enterprise networks where you’d be certain somebody has their finger on the pulse of patching, this just gets overlooked. Internal fighting over schedules, what patch might break which application, and so on, wind up leaving servers vulnerable to attack. ECC would like to plug MBSA (Microsoft Baseline Security Analyzer) as a good means to check for missing patches on a Windows machine, but it’s certainly not the only one out there. Unfortunately from a security perspective, discovering patches are missing isn’t an issue—getting them installed often is.

Other mitigations seem like common sense. Turn off unnecessary services, ports, and protocols. Remove outdated, unused accounts and properly configure default accounts that must remain. Set up appropriate file and folder permissions, and disable directory listing as much as possible. Ensure you have a means to detect attacks and to respond to them. The list goes on and on. From a hacking perspective, it’s great that patching and other security measures are either overlooked or flat out ignored. Remember, all you need is one opening, one crack, and your path to success is laid out in front of you.

Chapter Review

Web organizations assist in a wide array of efforts to improve the Internet. IEFT (https://www.ietf.org/, Internet Engineering Task Force) creates engineering documents to help make the Internet work better from an engineering point of view. The IETF’s official documents are published free of charge as RFCs (Requests For Comments). The World Wide Web Consortium (W3C, https://www.w3.org) is an international community where “member organizations, a full-time staff, and the public work together to develop Web standards.” W3C engages in education and outreach, develops software, and serves as an open forum for discussion about the Web.

OWASP (https://www.owasp.org, Open Web Application Security Project) is a 501(c)(3) worldwide not-for-profit charitable organization focused on improving the security of software. OWASP publishes reports, documents, and training efforts to assist in web security, including the “Top 10” security issues facing web applications and servers, and WebGoat (a deliberately insecure web application designed to teach web application security lessons). The current Top 10 list includes A1 – Injection Flaws, A2 – Broken Authentication and Session Management, A3 – Sensitive Data Exposure, A4 – XML External Entities (XXE), A5 – Broken Access Control, A6 – Security Misconfiguration, A7 – Cross-Site Scripting (XSS), A8 – Insecure Deserialization, A9 – Using Components with Known Vulnerabilities, and A10 – Insufficient Logging and Monitoring.

At its most basic, a web server acts like any other server you already know about; it responds to requests from clients and provides a file or service in answer. Apache configuration is almost always done as part of a module within special files (http.conf, for instance, can be used to set server status), and the modules are appropriately named (mod_negotiation, for instance). Also, almost everything questioned on IIS configuration is going to come down to privileges, and IIS itself will spawn all shells as LOCAL_SYSTEM. Apache is built modularly, with a core to hold all the “magic” and modules to perform a wide variety of functions. Additionally, because of its open source nature, there is a huge library of publicly available add-ons to support functions and services.

Whether it’s an Apache or an IIS server, misconfiguration of the settings is the most common vulnerability that will be exploited. Areas of concern include error messaging, default passwords, SSL certificates, scripts, remote administrative functions, configuration files, and services on the machine. Settings such as properly configuring (restricting?) remote administration, eliminating unnecessary services, and changing any default passwords or accounts are pretty obvious. The httpd.conf file on Apache servers controls aspects including who can view the server status page (which just so happens to contain information on the server, hosts connected, and requests being attended to). The php.ini file is one you want to look at for verbose error messaging setting.

The tier system is something you’ll need to be aware of in network design. N-tier architecture (a.k.a. multitier architecture) distributes processes across multiple servers. Each “tier” consists of a single role carried out by one (or more, or even a cluster of) computer systems. Typically this is carried out in “three-tier architecture,” with a presentation tier, logic tier, and data tier, but there are other implementations.

An HTML entity is a way of telling the browser to display certain characters it would otherwise look at as a tag or part of the programming itself. Examples include &nbsp; and &lt;. HTTP request methods include GET, HEAD, POST, PUT, DELETE, TRACE, and CONNECT. Both POST and GET are client-side ideas that can be manipulated with a web proxy. While GET is visible in a browser, POST is equally visible within a good-old Wireshark capture. An HTTP HEAD requests headers and metadata. It works exactly like an HTTP GET, except it doesn’t return any body information to display within your browser. An HTTP GET basically requests data from a resource. However, HTTP GET can be used to send data as well, and when sending data, the GET method adds the data to the URL.

A POST, on the other hand, is a much better method of submitting data to a resource for processing. It can also be used to elicit a response, but its primary purpose is to provide data for the server to work with. POST is generally considered safer than GET because it is not stored in browser history or necessarily in the server logs, and it doesn’t display returned data in the URL.

There are many attack vectors regarding web servers: password attacks, denial of service, man in the middle (sniffing), DNS poisoning (a.k.a. hijacking), and phishing. DNS amplification is an attack manipulating recursive DNS to DoS a target. The bad guy uses a botnet to amplify DNS answers to the target until it can’t do anything else.

Directory traversal is one form of attack that’s common and successful, at least on older servers. In this attack, the hacker attempts to access restricted directories and execute commands outside intended web server directories. Also known as the dot-dot-slash attack, directory climbing, and backtracking, this attack basically sends HTTP requests asking the server to drop back to the root directory and give access to other folders. This dot-dot-slash attack is also known as a variant of Unicode or unvalidated input attack. Unicode is a standard for ensuring consistent encoding and text representation and can be accepted by servers for malicious purposes. Unvalidated input means the server has not been configured to accept only specific input during an HTTP GET, so an attacker can craft the request to ask for command prompts, to try administrative access passwords, and so on.

ECC sometimes likes asking about parameter or URL tampering. In short, this just involves manipulating parameters within the URL string in hopes of modifying data, such as permissions and elevation of privileges, prices and quantities of goods, and credentials. The trick is to simply look at the URL and find parameters you can adjust and re-send.

Other web attacks covered by ECC are fairly self-explanatory. A misconfiguration attack takes advantage of configuration items on the server not being configured correctly. A password attack and an SSH brute-force attack? Exactly what they sound like. Web defacement results in the page being…well, defaced: an attacker maliciously alters the visual appearance of the page.

Metasploit will cover lots of options for you, including exploitation of known vulnerabilities and attacking passwords over Telnet, SSH, and HTTP. A basic Metasploit exploit module consists of five actions: select the exploit you want to use, configure the various options within the exploit, select a target, select the payload (that is, what you want to execute on the target machine), and then launch the exploit. The framework base accepts inputs from custom plug-ins, interfaces (how you interact with the framework), security tools, web services, and modules (each with its own specific purpose).

Web 2.0 refers to a somewhat different method of creating websites and applications: while 1.0 relies on static HTML, 2.0 uses “dynamic” web pages. Because they’re dynamic in nature, 2.0 apps allow users to upload and download to a site simultaneously, which provides much better infrastructure for social media and other user participation efforts. Per ECC, because Web 2.0 apps provide for more dynamic user participation, they also offer more attack surface.

One successful web application attack deals with injecting malicious commands into the input string. The objective is much like that of the parameter-tampering methods discussed earlier in this chapter: to pass exploit code to the server through poorly designed input validation in the application. This can occur using a variety of different methods, including file injection (where the attacker injects a pointer in the web form input to an exploit hosted on a remote site), command injection (where the attacker injects commands into the form fields instead of the expected test entry), and shell injection (where the attacker attempts to gain shell access using Java or other functions).

LDAP injection is an attack that exploits applications that construct LDAP statements based on user input. In an LDAP injection attack, the attacker changes what’s entered into the form field by adding the characters)(&) after the username and then providing any password.

SOAP injection is another related attack. Simple Object Access Protocol (SOAP) is designed to exchange structured information in web services in computer networks and uses XML to format information. You can inject malicious query strings (much like SQL injection, as a matter of fact) that may allow you to bypass authentication and access databases behind the scenes. SOAP is compatible with HTTP and SMTP, and messages are typically one way in nature.

A buffer overflow attack, also known as smashing the stack, is an attempt to write more data into an application’s prebuilt buffer area in order to overwrite adjacent memory, execute code, or crash a system (application).

Cross-site scripting (XSS) involves injecting a script into a form field intended for something else. One of the classic attacks of XSS involves getting access to “document .cookie” and sending it to a remote host.

A cross-site request forgery (CSRF) is a fun attack that forces an end user to execute unwanted actions on a web application on which they’re currently authenticated. CSRF tricks the victim into submitting a malicious request. It inherits the identity and privileges of the victim to perform an undesired function on the victim’s behalf. CSRF attacks can be mitigated by configuring a web server to send random challenge tokens. If every user request includes the challenge token, it becomes easy to spot illegitimate requests not initiated by the user.

A session fixation attack is somewhat similar to CSRF. The attacker logs in to a legitimate site and pulls a session ID, and then sends an e-mail with a link containing the fixed session ID. When the user clicks it and logs in to the same legitimate site, the hacker can now log in and run with the user’s credentials.

A cookie is a small text-based file that is stored on your system for use by the web server the next time you log in. It can contain information such as authentication details, site preferences, shopping cart contents, and session details. Cookies are sent in the header of an HTTP response from a web server and may or may not have an expiration date. The original intent was to provide a continuous, stable web view for customers and to make things easier for return surfers.

SQL injection is, by far, the most common and most successful injection attack technique in the world. Structured Query Language (SQL) is a computer language designed for managing data in a relational database system. The relational database is simply a collection of tables (consisting of rows, which hold individual fields containing data) tied together using some common field (key) that you can update and query. Each table has a name given to it that is referenced when you perform queries or updates. SQL comes into play when you are adding, deleting, moving, updating, or viewing the data in those tables and fields.

SQL queries generally begin with the SELECT command. SELECT is used to choose the data you’d like to perform an action on. In addition to SELECT, there are several additional options and commands of great interest to a hacker. For example, DROP TABLE tablename will delete the table tablename from the database. INSERT and UPDATE are also easy to understand.

SQL injection occurs when the attacker injects SQL queries directly into the input form. Properly constructed, the SQL command bypasses the intent of the front end and executes directly on the SQL database. To find out whether a site is susceptible to SQL injection, check your target for a web login page, and instead of entering what’s asked for on the web form, simply try a single quote (') and see what kind of error message, if any, you receive. If that doesn’t work, try entering anything'or 1=1- and see what you get. The attack names and definitions for SQL are union query, tautology, blind SQL injection, and error-based SQL injection.

Another neat little attack is called HTTP response splitting. The attack works by adding header response data to an input field so the server splits the response in a couple directions. If it works, the attacker controls the content of the second header, which can be used for any number of things—like redirecting the user to a malicious site the attacker runs.

A common method of security testing (hacking) a web application is to simply try using it in a manner in which it wasn’t intended to be used.

Countermeasures for web server and application attacks include correct placement of the servers and maintaining a strong patch management effort. Others include turning off unnecessary services, ports, and protocols; removing outdated, unused accounts and properly configuring default accounts that must remain; setting up appropriate file and folder permissions and disabling directory listing as much as possible; and ensuring you have a means to detect attacks and to respond to them.

Sqlmap, Havij, and sqlninja are all automated scanners designed to look specifically for injection vulnerabilities. SQLBrute is a tool that allows you to blast through predefined SQL injection queries against a target. Others tools include Pangolin, SQLExec, Absinthe, and BobCat.

Questions

1.   You are examining log files and notice several connection attempts to a hosted web server. Many attempts appear as such:

Images

What type of attack is in use?

A.   SQL injection

B.   Unicode parameter tampering

C.   Directory traversal

D.   Cross-site scripting

2.   The accounting department of a business notices several orders that seem to have been made erroneously. In researching the concern, you discover it appears the prices of items on several web orders do not match the listed prices on the public site. You verify the web server and the ordering database do not seem to have been compromised. Additionally, no alerts have displayed in the Snort logs concerning a possible attack on the web application. Which of the following might explain the attack in play?

A.   The attacker has copied the source code to his machine and altered hidden fields to modify the purchase price of the items.

B.   The attacker has used SQL injection to update the database to reflect new prices for the items.

C.   The attacker has taken advantage of a server-side include that altered the price.

D.   The attacker used Metasploit to take control of the web application.

3.   A pen test team member uses the following entry at the command line:

Images

Which of the following is true regarding the intent of the command?

A.   The team member is attempting to see which HTTP methods are supported by somesystem.com.

B.   The team member is attempting XSS against somesystem.com.

C.   The team member is attempting HTTP response splitting against somesystem.com.

D.   The team member is attempting to site-mirror somesystem.com.

4.   You are examining IDS logs and come across the following entry:

Images

What can you infer from this log entry?

A.   The attacker, using address 192.168.119.56, is attempting to connect to 64.118.55.64 using a DNS port.

B.   The attacker, using address 64.118.55.64, is attempting a directory traversal attack.

C.   The attacker is attempting a known SQL attack against 192.168.119.56.

D.   The attacker is attempting a buffer overflow against 192.168.119.56.

5.   Which of the following would be the best protection against XSS attacks?

A.   Invest in top-of-the-line firewalls.

B.   Perform vulnerability scans against your systems.

C.   Configure input validation on your systems.

D.   Have a pen test performed against your systems.

6.   Which of the following is true regarding n-tier architecture?

A.   Each tier must communicate openly with every other tier.

B.   N-tier always consists of presentation, logic, and data tiers.

C.   N-tier is usually implemented on one server.

D.   N-tier allows each tier to be configured and modified independently.

7.   Which character is the best choice to start a SQL injection attempt?

A.   Colon

B.   Semicolon

C.   Double quote

D.   Single quote

8.   Which of the following is a true statement?

A.   Configuring the web server to send random challenge tokens is the best mitigation for XSS attacks.

B.   Configuring the web server to send random challenge tokens is the best mitigation for buffer overflow attacks.

C.   Configuring the web server to send random challenge tokens is the best mitigation for parameter manipulation attacks.

D.   Configuring the web server to send random challenge tokens is the best mitigation for CSRF attacks.

9.   Which of the following is a true statement?

A.   SOAP cannot bypass a firewall.

B.   SOAP encrypts messages using HTTP methods.

C.   SOAP is compatible with HTTP and SMTP.

D.   SOAP messages are usually bidirectional.

10.   An attacker inputs the following into the Search text box on an entry form:

Images

The attacker then clicks the Search button and a pop-up appears stating, “It Worked.” What can you infer from this?

A.   The site is vulnerable to buffer overflow.

B.   The site is vulnerable to SQL injection.

C.   The site is vulnerable to parameter tampering.

D.   The site is vulnerable to XSS.

11.   SOAP is used to package and exchange information for web services. What does SOAP use to format this information?

A.   XML

B.   HTML

C.   HTTP

D.   Unicode

12.   A security administrator monitoring logs comes across a user login attempt that reads UserJoe)(&). What can you infer from this username login attempt?

A.   The attacker is attempting SQL injection.

B.   The attacker is attempting LDAP injection.

C.   The attacker is attempting SOAP injection.

D.   The attacker is attempting directory traversal.

13.   A security administrator sets the HttpOnly flag in cookies. Which of the following is he most likely attempting to mitigate against?

A.   CSRF

B.   CSSP

C.   XSS

D.   Buffer overflow

E.   SQL injection

14.   Your organization is deploying a new web-based software package requiring application and database support. The department has agreed on a three-server approach to make the service accessible from the Internet. Of the following choices, which would be the best option for server placement?

A.   A web, application, and database server on the internal network only

B.   A web, application, and database server facing the Internet

C.   A web server facing the Internet, and application and database server on the internal network

D.   An application and database server facing the Internet, with a web server internal

Answers

1.   C. This connection is attempting to traverse the directory from the Inetpub folders to a command shell for the attacker. Instead of dot-dot-slash, Unicode is used in this example to bypass potential IDS signatures.

2.   A. In this case, because the logs and IDSs show no direct attack, it’s most likely the attacker has copied the source code directly to his machine and altered the hidden “price” fields on the order form. All other types of attack would have, in some form or fashion, shown themselves easily.

3.   A. The http-methods script tests a target to see what HTTP methods are supported (by sending an HTTP OPTIONS request). Why would an attacker do this? If you know what GET, POST and PUT do, then you know the answer to this question already.

4.   D. The log file shows that the NOP sled signature is being used against 192.168.119.56. There is no indication in the log file about SQL or directory traversal.

5.   C. “Best” is always a tricky word. In this case, configuring server-side operations to validate what’s being put in the input field is by far the best mitigation. Could vulnerability scans and pen tests tell you something is wrong? Sure, but by themselves they don’t do anything to protect you.

6.   D. While usually implemented in three tiers, n-tier simply means you have three or more independently monitored, managed, and maintained collection of servers, each providing a specific service or tasking.

7.   D. The single quote should begin SQL injection attempts, even though in many database systems it’s not always an absolute.

8.   D. The requests from the bad guy masquerading with your session ID through your browser can be largely stopped by making sure each request has a challenge token—if the server gets one without a token, it’s deemed bad and dropped.

9.   C. SOAP is compatible with HTTP and SMTP, and usually the messages are “one way” in nature.

10.   D. This indicates a cross-site scripting vulnerability.

11.   A. SOAP formats its information exchange in XML.

12.   B. The)(&) indicates an LDAP injection attempt.

13.   C. Of the answers provided, XSS is the only one that makes sense. This setting prevents cookies from being accessible by a client-side script.

14.   C. Of the choices provided and with no other data, C is the best option. You have to have the web server available for clients to access, but your “back-end” processes should be internal if at all possible.

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

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