'Hacking'에 해당되는 글 266건

  1. 2008.11.12 SQL injection by CEOinIRVINE
  2. 2008.11.07 TCP flags by CEOinIRVINE
  3. 2008.11.06 Basic of Reverse Engineering by CEOinIRVINE
  4. 2008.11.06 Basic of Reverse Engineering by CEOinIRVINE
  5. 2008.10.31 CentOS Update Server and Local Repository by CEOinIRVINE
  6. 2008.10.29 OpenLDAP structure by CEOinIRVINE
  7. 2008.10.28 Linux open files by CEOinIRVINE
  8. 2008.10.25 Microsoft Urgent Patch by CEOinIRVINE
  9. 2008.10.15 SSH without PASSWORD by CEOinIRVINE
  10. 2008.10.04 Reverse Engineering Tutoring 1 by CEOinIRVINE

SQL injection

Hacking 2008. 11. 12. 01:14

SQL injection

From Wikipedia, the free encyclopedia

Jump to: navigation, search

SQL injection is a technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed. It is in fact an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another.

Contents

[hide]

[edit] Forms of SQL injection vulnerabilities

[edit] Incorrectly filtered escape characters

This form of SQL injection occurs when user input is not filtered for escape characters and is then passed into a SQL statement. This results in the potential manipulation of the statements performed on the database by the end user of the application.

The following lines of code illustrates this vulnerability:

statement = "SELECT * FROM users WHERE name = '" + userName + "';"

This SQL code is designed to pull up the records of a specified username from its table of users. However, if the "userName" variable is crafted in a specific way by a malicious user, the SQL statement may do more than the code author intended. For example, setting the "userName" variable as

a' or 't'='t

renders this SQL statement by the parent language:

SELECT * FROM users WHERE name = 'a' OR 't'='t';

If this code were to be used in an authentication procedure then this example could be used to force the selection of a valid username because the evaluation of 't'='t' is always true.

While most SQL Server implementations allow multiple statements to be executed with one call, some SQL APIs such as php's mysql_query do not allow this for security reasons. This prevents hackers from injecting entirely separate queries, but doesn't stop them from modifying queries. The following value of "userName" in the statement below would cause the deletion of the "users" table as well as the selection of all data from the "data" table (in essence revealing the information of every user):

a';DROP TABLE users; SELECT * FROM data WHERE name LIKE '%

This input renders the final SQL statement as follows:

SELECT * FROM Users WHERE name = 'a';DROP TABLE users; SELECT * FROM DATA WHERE name LIKE '%';

[edit] Incorrect type handling

This form of SQL injection occurs when a user supplied field is not strongly typed or is not checked for type constraints. This could take place when a numeric field is to be used in a SQL statement, but the programmer makes no checks to validate that the user supplied input is numeric. For example:

statement := "SELECT * FROM data WHERE id = " + a_variable + ";"

It is clear from this statement that the author intended a_variable to be a number correlating to the "id" field. However, if it is in fact a string then the end user may manipulate the statement as they choose, thereby bypassing the need for escape characters. For example, setting a_variable to

1;DROP TABLE users

will drop (delete) the "users" table from the database, since the SQL would be rendered as follows:

SELECT * FROM DATA WHERE id=1;DROP TABLE users;

[edit] Vulnerabilities inside the database server

Sometimes vulnerabilities can exist within the database server software itself, as was the case with the MySQL server's mysql_real_escape_string() function[1]. This would allow an attacker to perform a successful SQL injection attack based on bad Unicode characters even if the user's input is being escaped.

[edit] Blind SQL Injection

Blind SQL Injection is used when a web application is vulnerable to SQL injection but the results of the injection are not visible to the attacker. The page with the vulnerability may not be one that displays data but will display differently depending on the results of a logical statement injected into the legitimate SQL statement called for that page. This type of attack can become time-intensive because a new statement must be crafted for each bit recovered. There are several tools that can automate these attacks once the location of the vulnerability and the target information has been established.[2]

[edit] Conditional Responses

One type of blind SQL injection forces the database to evaluate a logical statement on an ordinary application screen.

SELECT booktitle FROM booklist WHERE bookId = 'OOk14cd' AND 1=1

will result in a normal page while

SELECT booktitle FROM booklist WHERE bookId = 'OOk14cd' AND 1=2

will likely give a different result if the page is vulnerable to a SQL injection. An injection like this will prove that a blind SQL injection is possible, leaving the attacker to devise statements that evaluate to true or false depending on the contents of a field in another table.[3]

[edit] Conditional Errors

This type of blind SQL injection causes a SQL error by forcing the database to evaluate a statement that causes an error if the WHERE statement is true. For example,

SELECT 1/0 FROM users WHERE username='Ralph'

the division by zero will only be evaluated and result in an error if user Ralph exists.

[edit] Time Delays

Time Delays are a type of blind SQL injection that cause the SQL engine to execute a long running query or a time delay statement depending on the logic injected. The attacker can then measure the time the page takes to load to determine if the injected statement is true.

[edit] Preventing SQL Injection

To protect against SQL injection, user input must not directly be embedded in SQL statements. Instead, user input must be escaped or filtered or parameterized statements must be used.

[edit] Using Parameterized Statements

In some programming languages such as Java and .NET parameterized statements can be used that work with parameters (sometimes called placeholders or bind variables) instead of embedding user input in the statement. In many cases, the SQL statement is fixed. The user input is then assigned (bound) to a parameter. This is an example using Java and the JDBC API:

PreparedStatement prep = conn.prepareStatement("SELECT * FROM USERS WHERE USERNAME=? AND PASSWORD=?");
prep.setString(1, username);
prep.setString(2, password);

The same goes for C#:

using (SqlCommand myCommand = new SqlCommand("select * from Users where UserName=@username and Password=@password", myConnection))
{
myCommand.Parameters.AddWithValue("@username", user);
myCommand.Parameters.AddWithValue("@password", pass);

myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader())
...................
}

In ASP:

userName=replace(request.querystring("username"))     
userPassword=replace(request.querystring("Password"))

userName=replace(userName,"'","\'")

'userPassword it's a numeric value.
userPassword=cdbl(userPassword)

myConn.execute "select * from users where name='" & userName & _
"' and userPassword=" & userPassword & " limit 1"


In PHP, it's usual to just escape the parameters before sending the SQL query:

$query = sprintf("SELECT * FROM Users where UserName='%s' and Password='%s'", 
mysql_real_escape_string($Username),
mysql_real_escape_string($Password));
mysql_query($query);

For PHP version 5 and MySQL version 4.1 and above, however, you can use a vendor specific extension like mysqli for "true" prepared statement queries.[4] Example:[5]

$db = new mysqli("localhost", "user", "pass", "database");
$stmt = $db -> prepare("SELECT priv FROM testUsers WHERE username=? AND password=?");
$stmt -> bind_param("ss", $user, $pass);
$stmt -> execute();

The mysql_real_escape_string adds backslashes (\) to escaped characters like single quotes ' and double quotes ". Though, you should read this

The magic_quotes_gpc PHP configuration directive affects Get, Post and Cookie values. If turned on, value (It's "PHP!") will automagically become (It\'s \"PHP!\").

In ColdFusion, the CFQUERYPARAM statement is useful in conjunction with the CFQUERY statement to nullify the effect of SQL code passed within the CFQUERYPARAM value as part of the SQL clause.[6] [7]. An example is below.

<cfquery name="Recordset1" datasource="cafetownsend">
SELECT *
FROM COMMENTS


WHERE COMMENT_ID =<cfqueryparam value="#URL.COMMENT_ID#" cfsqltype="cf_sql_numeric">
</cfquery>

[edit] Enforcing the Use of Parameterized Statements

There are two ways to ensure an application is not vulnerable to SQL injection: using code reviews (which is a manual process), and enforcing the use of parameterized statements. Enforcing the use of parameterized statements means that SQL statements with embedded user input are rejected at runtime. Currently only the H2 Database Engine supports this feature.

'Hacking' 카테고리의 다른 글

Snort Configuration : Linux  (0) 2008.11.18
TOP SQL injection tool lists [15]  (0) 2008.11.12
TCP flags  (0) 2008.11.07
Basic of Reverse Engineering  (0) 2008.11.06
Basic of Reverse Engineering  (0) 2008.11.06
Posted by CEOinIRVINE
l

TCP flags

Hacking 2008. 11. 7. 03:57

TCP Analysis - Section 4: TCP Flag Options

Introduction

As we have seen in the previous pages, some TCP segments carry data while others are simple acknowledgements for previously received data. The popular 3-way handshake utilises the SYNs and ACKs available in the TCP to help complete the connection before data is transferred.

Our conclusion is that each TCP segment has a purpose, and this is determined with the help of the TCP flag options, allowing the sender or receiver to specify which flags should be used so the segment is handled correctly by the other end.

Let's take a look at the TCP flags field to begin our analysis:

You can see the 2 flags that are used during the 3-way handshake (SYN, ACK) and data transfers.

As with all flags, a value of '1' means that a particular flag is 'set' or, if you like, is 'on'. In this example, only the "SYN" flag is set, indicating that this is the first segment of a new TCP connection.

In addition to this, each flag is one bit long, and since there are 6 flags, this makes the Flags section 6 bits in total.

You would have to agree that the most popular flags are the "SYN", "ACK" and "FIN", used to establish connections, acknowledge successful segment transfers and, lastly, terminate connections. While the rest of the flags are not as well known, their role and purpose makes them, in some cases, equally important.

We will begin our analysis by examining all six flags, starting from the top, that is, the Urgent Pointer:

1st Flag - Urgent Pointer

The first flag is the Urgent Pointer flag, as shown in the previous screen shot. This flag is used to identify incoming data as 'urgent'. Such incoming segments do not have to wait until the previous segments are consumed by the receiving end but are sent directly and processed immediately.

An Urgent Pointer could be used during a stream of data transfer where a host is sending data to an application running on a remote machine. If a problem appears, the host machine needs to abort the data transfer and stop the data processing on the other end. Under normal circumstances, the abort signal will be sent and queued at the remote machine until all previously sent data is processed, however, in this case, we need the abort signal to be processed immediately.

By setting the abort signal's segment Urgent Pointer flag to '1', the remote machine will not wait till all queued data is processed and then execute the abort. Instead, it will give that specific segment priority, processing it immediately and stopping all further data processing.

If you're finding it hard to understand, consider this real-life example:

At your local post office, hundreds of trucks are unloading bags of letters from all over the world. Because the amount of trucks entering the post office building are abundant, they line up one behind the other, waiting for their turn to unload their bags.

As a result, the queue ends up being quite long. However, a truck with a big red flag suddenly joins the queue and the security officer, whose job it is to make sure no truck skips the queue, sees the red flag and knows it's carrying very important letters that need to get to their destination urgently. By following the normal procedures, the security officer signals to the truck to skip the queue and go all the way up to the front, giving it priority over the other the trucks.

In this example, the trucks represent the segments that arrive at their destination and are queued in the buffer waiting to be processed, while the truck with the red flag is the segment with the Urgent Pointer flag set.

A further point to note is the existence of theUrgent Pointer field. This field is covered in section 5, but we can briefly mention that when the Urgent Pointer flag is set to '1' (that's the one we are analysing here), then the Urgent Pointer field specifies the position in the segment where urgent data ends.

2nd Flag - ACKnowledgement

The ACKnowledgement flag is used to acknowledge the successful receipt of packets.

If you run a packet sniffer while transferring data using the TCP, you will notice that, in most cases, for every packet you send or receive, an ACKnowledgement follows. So if you received a packet from a remote host, then your workstation will most probably send one back with the ACK field set to "1".

In some cases where the sender requires one ACKnowledgement for every 3 packets sent, the receiving end will send the ACK expected once (the 3rd sequential packet is received). This is also called Windowing and is covered extensively in the pages that follow.

3rd Flag - PUSH

The Push flag, like the Urgent flag, exists to ensure that the data is given the priority (that it deserves) and is processed at the sending or receiving end. This particular flag is used quite frequently at the beginning and end of a data transfer, affecting the way the data is handled at both ends.

When developers create new applications, they must make sure they follow specific guidelines given by the RFC's to ensure that their applications work properly and manage the flow of data in and out of the application layer of the OSI model flawlessly. When used, the Push bit makes sure the data segment is handled correctly and given the appropriate priority at both ends of a virtual connection.

When a host sends its data, it is temporarily queued in the TCP buffer, a special area in the memory, until the segment has reached a certain size and is then sent to the receiver. This design guarantees that the data transfer is as efficient as possible, without waisting time and bandwidth by creating multiple segments, but combining them into one or more larger ones.

When the segment arrives at the receiving end, it is placed in the TCP incoming buffer before it is passed onto the application layer. The data queued in the incoming buffer will remain there until the other segments arrive and, once this is complete, the data is passed to the application layer that's waiting for it.

While this procedure works well in most cases, there are a lot of instances where this 'queueing' of data is undesirable because any delay during queuing can cause problems to the waiting application. A simple example would be a TCP stream, e.g real player, where data must be sent and processed (by the receiver) immediately to ensure a smooth stream without any cut offs.

A final point to mention here is that the Push flag is usually set on the last segment of a file to prevent buffer deadlocks. It is also seen when used to send HTTP or other types of requests through a proxy - ensuring the request is handled appropriately and effectively.

4th Flag - Reset (RST) Flag

The reset flag is used when a segment arrives that is not intended for the current connection. In other words, if you were to send a packet to a host in order to establish a connection, and there was no such service waiting to answer at the remote host, then the host would automatically reject your request and then send you a reply with the RST flag set. This indicates that the remote host has reset the connection.

While this might prove very simple and logical, the truth is that in most cases this 'feature' is used by most hackers in order to scan hosts for 'open' ports. All modern port scanners are able to detect 'open' or 'listening' ports thanks to the 'reset' function.

The method used to detect these ports is very simple: When attempting to scan a remote host, a valid TCP segment is constructed with the SYN flag set (1) and sent to the target host. If there is no service listening for incoming connections on the specific port, then the remote host will reply with ACK and RST flag set (1). If, on the other hand, there is a service listening on the port, the remote host will construct a TCP segment with the ACK flag set (1). This is, of course, part of the standard 3-way handshake we have covered.

Once the host scanning for open ports receives this segment, it will complete the 3-way handshake and then terminate it using the FIN (see below) flag, and mark the specific port as "active".

5th Flag - SYNchronisation Flag

The fifth flag contained in the TCP Flag options is perhaps the most well know flag used in TCP communications. As you might be aware, the SYN flag is initialy sent when establishing the classical 3-way handshake between two hosts:

In the above diagram, Host A needs to download data from Host B using TCP as its transport protocol. The protocol requires the 3-way handshake to take place so a virtual connection can be established by both ends in order to exchange data.

During the 3-way handshake we are able to count a total of 2 SYN flags transmitted, one by each host. As files are exchanged and new connections created, we will see more SYN flags being sent and received.

6th Flag - FIN Flag

The final flag available is the FIN flag, standing for the word FINished. This flag is used to tear down the virtual connections created using the previous flag (SYN), so because of this reason, the FIN flag always appears when the last packets are exchanged between a connection.

It is important to note that when a host sends a FIN flag to close a connection, it may continue to receive data until the remote host has also closed the connection, although this occurs only under certain circumstances. Once the connection is teared down by both sides, the buffers set aside on each end for the connection are released.

A normal teardown procedure is depicted below:

The above diagram represents an existing connection betwen Host A and B, where the two hosts are exchanging data. Once the data transfer is complete, Host A sends a packet with the FIN, ACK flags set (STEP 1).

With this packet, Host A is ACKnowledging the previous stream while at the same time initiating the TCP close procedure to kill this connection. At this point, Host A's application will stop receiving any data and will close the connection from this side.

In response to Host A's request to close the connection, Host B will send an ACKnowledgement (STEP 2) back, and also notify its application that the connection is no longer available. Once this is complete, the host (B) will send its own FIN, ACK flags (STEP 3) to close their part of the connection.

If you're wondering why this procedure is required, then you may need to recall that TCP is a Full Duplex connection, meaning that there are two directions of data flow. In our example this is the connection flow from Host A to Host B and vice versa. In addition, it requires both hosts to close the connection from their side, hence the reason behind the fact that both hosts must send a FIN flag and the other host must ACKnowledge it.

Lastly, at Step 4, Host A willl acknowledge the request Host B sent at STEP 3 and the closedown procedure for both sides is now complete!

Summary

This page dealt with the TCP Flag Options available to make life either more difficult, or easy, depending on how you look at the picture :)

Perhaps the most important information given on this page that is beneficial to remember is the TCP handshake procedure and the fact that TCP is a Full Duplex connection.

The following section will examine the TCP Window size, Checksum and Urgent Pointer fields, all of which are relevant and very important. For this reason we strongly suggest you read through these topics, rather than skip over them.

'Hacking' 카테고리의 다른 글

TOP SQL injection tool lists [15]  (0) 2008.11.12
SQL injection  (0) 2008.11.12
Basic of Reverse Engineering  (0) 2008.11.06
Basic of Reverse Engineering  (0) 2008.11.06
CentOS Update Server and Local Repository  (0) 2008.10.31
Posted by CEOinIRVINE
l

Assembler : The Basics In Reversing

 

 

Indeed: the basics!! This is all far from complete but covers about everything you need to know about assembler to start on your reversing journey! Assembler is the start and the end of all programming languages. After all, all (computer LOL) languages are translated to assembler. In most languages we deal with relatively clear syntaxes. However, it's a completely other story in assembler where we use abbreviations and numbers and where it all seems so weird …

 

 

I. Pieces, bits and bytes:

 

·         BIT - The smallest possible piece of data. It can be either a 0 or a 1. If you put a bunch of bits together, you end up in the 'binary number system'

 

i.e. 00000001 = 1       00000010 = 2             00000011 = 3     etc.

 

·         BYTE - A byte consists of 8 bits. It can have a maximal value of 255 (0-255). To make it easier to read binary numbers, we use the 'hexadecimal number system'. It's a 'base-16 system', while binary is a 'base-2 system'

 

·         WORD - A word is just 2 bytes put together or 16 bits. A word can have a maximal value of 0FFFFh (or 65535d).

 

·         DOUBLE WORD - A double word is 2 words together or 32 bits. Max value = 0FFFFFFFF (or 4294967295d).

 

·         KILOBYTE - 1000 bytes? No, a kilobyte does NOT equal 1000 bytes! Actually, there are 1024 (32*32) bytes.

 

·         MEGABYTE - Again, not just 1 million bytes, but 1024*1024 or 1,048,578 bytes.

 

 

---------------------------------------------------------------------------------------------

 

 

II. Registers:

 

Registers are “special places” in your computer's memory where we can store data. You can see a register as a little box, wherein we can store something: a name, a number, a sentence. You can see a register as a placeholder.

 

On today’s average WinTel CPU you have 9 32bit registers (w/o flag registers). Their names are:

 

EAX:   Extended Accumulator Register

EBX:   Extended Base Register

ECX:   Extended Counter Register

EDX:   Extended Data Register

ESI:    Extended Source Index

EDI:   Extended Destination Index

EBP:   Extended Base Pointer

ESP:   Extended Stack Pointer

EIP:    Extended Instruction Pointer

 

Generally the size of the registers is 32bit (=4 bytes). They can hold data from 0-FFFFFFFF (unsigned). In the beginning most registers had certain main functions which the names imply, like ECX = Counter, but in these days you can - nearly - use whichever register you like for a counter or stuff (only the self defined ones, there are counter-functions which need to be used with ECX). The functions of EAX, EBX, ECX, EDX, ESI and EDI will be explained when I explain certain functions that use those registers. So, there are EBP, ESP, EIP left:

 

EBP:   EBP has mostly to do with stack and stack frames. Nothing you really need to worry about, when you start. ;)

 

ESP:   ESP points to the stack of a current process. The stack is the place where data can be stored for later use (for more information, see the explanation of the push/pop instructions)

 

EIP:    EIP always points to the next instruction that is to be executed.

 

 

There's one more thing you have to know about registers: although they are all 32bits large, some parts of them (16bit or even 8bit) can not be addressed directly.

 

The possibilities are:

 

32bit Register                       16bit Register                      8bit Register

EAX                                  AX                             AH/AL

EBX                                  BX                              BH/BL

ECX                                  CX                             CH/CL

EDX                                  DX                             DH/DL

ESI                                   SI                              -----

EDI                                   DI                              -----

EBP                        BP                             -----

ESP                                  SP                             -----

EIP                                   IP                              -----

 

A register looks generally this way:

 

     |--------------------------- EAX: 32bit (=1 DWORD =4BYTES) -------------------------|

 

                                               |------- AX: 16bit (=1 WORD =2 BYTES) ----|

 

                                               |- AH:8bit (=1 BYTE)-|- AL:8bit (=1 BYTE)-|

 

     |-----------------------------------------|--------------------|--------------------|

     |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXX|

     |-----------------------------------------|--------------------|--------------------|

 

So, EAX is the name of the 32bit register, AX is the name of the "Low Word" (16bit) of EAX and AL/AH (8bit) are the “names” of the "Low Part" and “High Part” of AX. BTW, 4 bytes is 1 DWORD, 2 bytes is 1 WORD.

 

REMARK: make sure you at least read the following about registers. It’s quite practical to know it although not that important.

 

All this makes it possible for us to make a distinction regarding size:

 

·         i. byte-size registers: As the name says, these registers all exactly 1 byte in size. This does not mean that the whole (32bit) register is fully loaded with data! Eventually empty spaces in a register are just filled with zeroes. These are the byte-sized registers, all 1 byte or 8 bits in size:

o    AL  and AH

o    BL  and BH

o    CL  and CH

o    DL  and DH

·         ii. word-size registers: Are 1 word (= 2 bytes = 16 bits) in size. A word-sized register is constructed of 2 byte-sized registers. Again, we can divide these regarding their purpose:

 

o    1. general purpose registers:

 

AX (word-sized) = AH + AL -> the '+' does *not* mean: 'add them up'. AH and AL exist independently, but together they form AX. This means that if you change AH or AL (or both), AX will change too!

 

-> 'accumulator':               used to mathematical operations, store strings,..

BX -> 'base':                         used in conjunction with the stack (see later)

CX -> 'counter'

DX -> 'data':                         mostly, here the remainder of mathematical operations is stored

DI  -> 'destination index':         i.e. a string will be copied to DI

SI  -> 'source index':              i.e. a string will be copied from SI

 

o    2. index registers:

 

BP  -> 'base pointer':               points to a specified position on the stack (see later)
     SP  -> 'stack pointer':              points to a specified position on the stack (see later)

 

o    3. segment registers:


     CS -> 'code segment':             instructions an application has to execute (see later)
     DS -> 'data segment':             the data your application needs (see later)
     ES -> 'extra segment':            duh! (see later)
     SS -> 'stack segment':            here we'll find the stack (see later)

 

o    4. special:
  

IP  -> 'instruction pointer':       points to the next instruction. Just leave it alone ;)

 

·         iii. Doubleword-size registers:

 

2 words = 4 bytes = 32 bits. EAX, EBX, ECX, EDX, EDI…

 

If you find an 'E' in front of a 16-bits register, it means that you are dealing with a 32-bits register. So, AX = 16-bits; EAX = the 32-bits version of EAX.

 

 

---------------------------------------------------------------------------------------------

 

 

III. The flags:

 

Flags are single bits which indicate the status of something. The flag register on modern 32bit CPUs is 32bit large. There are 32 different flags, but don't worry. You will mostly only need 3 of them in reversing. The Z-Flag, the O-Flag and the C-Flag. For reversing you need to know these flags to understand if a jump is executed or not. This register is in fact a collection of different 1-bit flags. A flag is a sign, just like a green light means: 'ok' and a red one 'not ok'. A flag can only be '0' or '1', meaning 'not set' or 'set'.

 

·         The Z-Flag:

o    The Z-Flag (zero flag) is the most useful flag for cracking. It is used in about 90% of all cases. It can be set (status: 1) or cleared (status: 0) by several opcodes when the last instruction that was performed has 0 as result. You might wonder why "CMP" (more on this later) could set the zero flag, because it compares something - how can the result of the comparison be 0? The answer on this comes later ;)

 

·         The O-Flag:

o    The O-Flag (overflow flag) is used in about 4% of all cracking attempts. It is set (status: 1) when the last operation changed the highest bit of the register that gets the result of an operation. For example: EAX holds the value 7FFFFFFF. If you use an operation now, which increases EAX by 1 the O-Flag would be set, because the operation changed the highest bit of EAX (which is not set in 7FFFFFFF, but set in 80000000 - use calc.exe to convert hexadecimal values to binary values). Another need for the O-Flag to be set, is that the value of the destination register is neither 0 before the instruction nor after it.

 

·         The C-Flag:

o    The C-Flag (Carry flag) is used in about 1% of all cracking attempts. It is set, if you add a value to a register, so that it gets bigger than FFFFFFFF or if you subtract a value, so that the register value gets smaller than 0.

 

 

---------------------------------------------------------------------------------------------

 

 

IV. Segments en offsets

 

A segment is a piece in memory where instructions (CS), data (DS), the stack (SS) or just an extra segment (ES) are stored. Every segment is divided in 'offsets'. In 32-bits applications (Windows 95/98/ME/2000), these offsets are numbered from 00000000 to FFFFFFFF. 65536 pieces of memory thus 65536 memory addresses per segment. The standard notation for segments and offsets is:

 

SEGMENT                                  :        OFFSET        =       Together, they point to a specific place (address) in memory.

 

See it like this:

 

A segment is a page in a book     :        An offset is a specific line at that page.

 

 

---------------------------------------------------------------------------------------------

 

 

V. The stack:

 

The Stack is a part in memory where you can store different things for later use. See t as a pile of books in a chest where the last put in is the first to grab out. Or imagine the stack as a paper basket where you put in sheets. The basket is the stack and a sheet is a memory address (indicated by the stack pointer) in that stack segment. Remember following rule: the last sheet of paper you put in the stack, is the first one you'll take out! The command 'push' saves the contents of a register onto the stack. The command 'pop' grabs the last saved contents of a register from the stack and puts it in a specific register.

 

 

---------------------------------------------------------------------------------------------

 

 

VI. INSTRUCTIONS (alphabetical)

 

Please note, that all values in ASM mnemonics (instructions) are *always* hexadecimal.

 

 

Most instructions have two operators (like "add EAX, EBX"), but some have one ("not EAX") or even three ("IMUL EAX, EDX, 64"). When you have an instruction that says something with "DWORD PTR [XXX]" then the DWORD (4 byte) value at memory offset [XXX] is meant. Note that the bytes are saved in reverse order in the memory (WinTel CPUs use the so called “Little Endian” format. The same is for "WORD PTR [XXX]" (2 byte) and "BYTE PTR [XXX]" (1 byte).

 

Most instructions with 2 operators can be used in the following ways (example: add):

 

add eax,ebx                                         ;; Register, Register

add eax,123                                         ;; Register, Value

add eax,dword ptr [404000]                    ;; Register, Dword Pointer [value]

add eax,dword ptr [eax]                         ;; Register, Dword Pointer [register]

add eax,dword ptr [eax+00404000] ;; Register, Dword Pointer [register+value]

add dword ptr [404000],eax                    ;; Dword Pointer [value], Register

add dword ptr [404000],123           ;; Dword Pointer [value], Value

add dword ptr [eax],eax                         ;; Dword Pointer [register], Register

add dword ptr [eax],123                         ;; Dword Pointer [register], Value

add dword ptr [eax+404000],eax             ;; Dword Pointer [register+value], Register

add dword ptr [eax+404000],123             ;; Dword Pointer [register+value], value

 

 

---------------------------------------------------------------------------------------------

 

     ADD (Addition)

     Syntax: ADD destination, source

 

     The ADD instruction adds a value to a register or a memory address. It can be used in

     these ways:

 

     These instruction can set the Z-Flag, the O-Flag and the C-Flag (and some others, which

     are not needed for cracking).

 

---------------------------------------------------------------------------------------------

 

     AND (Logical And)

     Syntax: AND destination, source    

 

     The AND instruction uses a logical AND on two values.

     This instruction *will* clear the O-Flag and the C-Flag and can set the Z-Flag.

     To understand AND better, consider those two binary values:

 

                                    1001010110

                                    0101001101

 

     If you AND them, the result is 0001000100

     When two 1 stand below each other, the result is of this bit is 1, if not: The result

     is 0. You can use calc.exe to calculate AND easily.

 

---------------------------------------------------------------------------------------------

 

     CALL (Call)

     Syntax: CALL something

 

     The instruction CALL pushes the RVA (Relative Virtual Address) of the instruction that

     follows the CALL to the stack and calls a sub program/procedure.

 

     CALL can be used in the following ways:

 

     CALL        404000                             ;; MOST COMMON: CALL ADDRESS

     CALL        EAX                                 ;; CALL REGISTER - IF EAX WOULD BE 404000 IT WOULD BE SAME AS THE ONE ABOVE

     CALL        DWORD PTR [EAX]             ;; CALLS THE ADDRESS THAT IS STORED AT [EAX]

     CALL        DWORD PTR [EAX+5]                   ;; CALLS THE ADDRESS THAT IS STORED AT [EAX+5]

 

---------------------------------------------------------------------------------------------

 

     CDQ (Convert DWord (4Byte) to QWord (8 Byte))

     Syntax: CQD

 

     CDQ is an instruction that always confuses newbies when it appears first time. It is

     mostly used in front of divisions and does nothing else then setting all bytes of EDX

     to the value of the highest bit of EAX. (That is: if EAX <80000000, then EDX will be

     00000000; if EAX >= 80000000, EDX will be FFFFFFFF).

 

---------------------------------------------------------------------------------------------

 

     CMP (Compare)

     Syntax: CMP dest, source

 

     The CMP instruction compares two things and can set the C/O/Z flags if the result fits.

 

     CMP         EAX, EBX                          ;; compares eax and ebx and sets z-flag if they are equal

     CMP         EAX,[404000]                    ;; compares eax with the dword at 404000

     CMP         [404000],EAX                    ;; compares eax with the dword at 404000

 

---------------------------------------------------------------------------------------------

 

     DEC (Decrement)

     Syntax: DEC something

 

     dec is used to decrease a value (that is: value=value-1)

 

     dec can be used in the following ways:

     dec eax                                          ;; decrease eax

     dec [eax]                                        ;; decrease the dword that is stored at [eax]

     dec [401000]                                   ;; decrease the dword that is stored at [401000]

     dec [eax+401000]                            ;; decrease the dword that is stored at [eax+401000]

 

     The dec instruction can set the Z/O flags if the result fits.

   

---------------------------------------------------------------------------------------------

 

     DIV (Division)

     Syntax: DIV divisor

 

     DIV is used to divide EAX through divisor (unsigned division). The dividend is always

     EAX, the result is stored in EAX, the modulo-value in EDX.

 

     An example:

     mov eax,64                                     ;; EAX = 64h = 100

     mov ecx,9                                       ;; ECX = 9

     div ecx                                           ;; DIVIDE EAX THROUGH ECX

 

     After the division EAX = 100/9 = 0B and ECX = 100 MOD 9 = 1

 

     The div instruction can set the C/O/Z flags if the result fits.

 

---------------------------------------------------------------------------------------------

 

     IDIV (Integer Division)

     Syntax: IDIV divisor

 

     The IDIV works in the same way as DIV, but IDIV is a signed division.

     The idiv instruction can set the C/O/Z flags if the result fits.

 

---------------------------------------------------------------------------------------------

 

     IMUL (Integer Multiplication)

     Syntax:    IMUL value

                   IMUL dest,value,value

                   IMUL dest,value

 

     IMUL multiplies either EAX with value (IMUL value) or it multiplies two values and puts

     them into a destination register (IMUL dest, value, value) or it multiplies a register

     with a value (IMUL dest, value).

 

     If the multiplication result is too big to fit into the destination register, the

     O/C flags are set. The Z flag can be set, too.

 

---------------------------------------------------------------------------------------------

 

     INC (Increment)

     Syntax: INC register

 

     INC is the opposite of the DEC instruction; it increases values by 1.

     INC can set the Z/O flags.

 

 

---------------------------------------------------------------------------------------------

 

      INT

     Syntax: int dest

 

     Generates a call to an interrupt handler. The dest value must be an integer (e.g., Int 21h).

     INT3 and INTO are interrupt calls that take no parameters but call the handlers for

     interrupts 3 and 4, respectively.

 

---------------------------------------------------------------------------------------------

 

     JUMPS

     These are the most important jumps and the condition that needs to be met, so that

     they'll be executed (Important jumps are marked with * and very important with **):

 

JA*     -        Jump if (unsigned) above                        - CF=0 and ZF=0

JAE     -        Jump if (unsigned) above or equal            - CF=0

JB*     -        Jump if (unsigned) below                        - CF=1

JBE     -        Jump if (unsigned) below or equal            - CF=1 or ZF=1

JC       -        Jump if carry flag set                             - CF=1

JCXZ   -        Jump if CX is 0                                      - CX=0

JE**    -        Jump if equal                                        - ZF=1

JECXZ  -        Jump if ECX is 0                                    - ECX=0

JG*     -        Jump if (signed) greater                         - ZF=0 and SF=OF (SF = Sign Flag)

JGE*   -        Jump if (signed) greater or equal             - SF=OF

JL*      -        Jump if (signed) less                              - SF != OF (!= is not)

JLE*    -        Jump if (signed) less or equal                  - ZF=1 and OF != OF

JMP**  -        Jump                                                   - Jumps always

JNA     -        Jump if (unsigned) not above                   - CF=1 or ZF=1

JNAE   -        Jump if (unsigned) not above or equal       - CF=1

JNB     -        Jump if (unsigned) not below                   - CF=0

JNBE   -        Jump if (unsigned) not below or equal       - CF=0 and ZF=0

JNC     -        Jump if carry flag not set                        - CF=0

JNE**  -        Jump if not equal                                   - ZF=0

JNG     -        Jump if (signed) not greater                    - ZF=1 or SF!=OF

JNGE   -        Jump if (signed) not greater or equal        - SF!=OF

JNL     -        Jump if (signed) not less                         - SF=OF

JNLE    -        Jump if (signed) not less or equal             - ZF=0 and SF=OF

JNO     -        Jump if overflow flag not set                   - OF=0

JNP     -        Jump if parity flag not set                       - PF=0

JNS     -        Jump if sign flag not set                         - SF=0

JNZ     -        Jump if not zero                                    - ZF=0

JO       -        Jump if overflow flag is set                     - OF=1

JP       -        Jump if parity flag set                            - PF=1

JPE     -        Jump if parity is equal                            - PF=1

JPO     -        Jump if parity is odd                              - PF=0

JS       -        Jump if sign flag is set                            - SF=1

JZ       -        Jump if zero                                         - ZF=1

 

---------------------------------------------------------------------------------------------

 

     LEA (Load Effective Address)

     Syntax: LEA dest,src

 

     LEA can be treated the same way as the MOV instruction. It isn't used too much for its

     original function, but more for quick multiplications like this:

 

     lea eax, dword ptr [4*ecx+ebx]

     which gives eax the value of 4*ecx+ebx

 

---------------------------------------------------------------------------------------------

 

     MOV (Move)

     Syntax: MOV dest,src

 

     This is an easy to understand instruction. MOV copies the value from src to dest and src

     stays what it was before.

 

     There are some variants of MOV:

 

     MOVS/MOVSB/MOVSW/MOVSD EDI, ESI: Those variants copy the byte/word/dword ESI points to,

to the space EDI points to.

 

     MOVSX:   MOVSX expands Byte or Word operands to Word or Dword size and keeps the sign of the

value.

 

     MOVZX:   MOVZX expands Byte or Word operands to Word or Dword size and fills the rest of the

space with 0.

 

---------------------------------------------------------------------------------------------

 

     MUL (Multiplication)

     Syntax: MUL value

 

     This instruction is the same as IMUL, except that it multiplies unsigned. It can set the

     O/Z/F flags.

 

---------------------------------------------------------------------------------------------

 

     NOP (No Operation)

     Syntax: NOP

 

     This instruction does absolutely nothing

     That's the reason why it is used so often in reversing ;)

 

---------------------------------------------------------------------------------------------

 

     OR (Logical Inclusive Or)

     Syntax: OR dest,src

 

     The OR instruction connects two values using the logical inclusive or.

     This instruction clears the O-Flag and the C-Flag and can set the Z-Flag.

 

     To understand OR better, consider those two binary values:

 

                                    1001010110

                                    0101001101

    

     If you OR them, the result is 1101011111

 

     Only when there are two 0 on top of each other, the resulting bit is 0. Else the resulting

     bit is 1. You can use calc.exe to calculate OR. I hope you understand why, else

     write down a value on paper and try ;)

 

---------------------------------------------------------------------------------------------

 

     POP

     Syntax: POP dest

 

     POP loads the value of byte/word/dword ptr [esp] and puts it into dest. Additionally it

     increases the stack by the size of the value that was popped of the stack, so that the next

     POP would get the next value.

 

---------------------------------------------------------------------------------------------

 

     PUSH

     Syntax: PUSH operand

 

     PUSH is the opposite of POP. It stores a value on the stack and decreases it by the size

     of the operand that was pushed, so that ESP points to the value that was PUSHed.

 

---------------------------------------------------------------------------------------------

 

    REP/REPE/REPZ/REPNE/REPNZ

     Syntax: REP/REPE/REPZ/REPNE/REPNZ ins

 

     Repeat Following String Instruction: Repeats ins until CX=0 or until indicated condition

     (ZF=1, ZF=1, ZF=0, ZF=0) is met. The ins value must be a string operation such as CMPS, INS,

     LODS, MOVS, OUTS, SCAS, or STOS.

 

---------------------------------------------------------------------------------------------

 

     RET (Return)

     Syntax: RET

             RET digit

 

     RET does nothing but return from a part of code that was reached using a CALL instruction.

     RET digit cleans the stack before it returns.

 

---------------------------------------------------------------------------------------------

 

     SUB (Subtraction)

     Syntax: SUB dest,src

 

     SUB is the opposite of the ADD command. It subtracts the value of src from the value of

     dest and stores the result in dest.

 

     SUB can set the Z/O/C flags.

 

---------------------------------------------------------------------------------------------

 

     TEST

     Syntax: TEST operand1, operand2

 

     This instruction is in 99% of all cases used for "TEST EAX, EAX". It performs a Logical

     AND(AND instruction) but does not save the values. It only sets the Z-Flag, when EAX is 0

     or clears it, when EAX is not 0. The O/C flags are always cleared.

 

---------------------------------------------------------------------------------------------

 

     XOR

     Syntax: XOR dest,src

 

     The XOR instruction connects two values using logical exclusive OR (remember OR uses

     inclusive OR).

 

     This instruction clears the O-Flag and the C-Flag and can set the Z-Flag.

     To understand XOR better, consider those two binary values:

 

                                    1001010110

                                    0101001101

 

     If you OR them, the result is 1100011011

 

     When two bits on top of each other are equal, the resulting bit is 0. Else the resulting

     bit is 1. You can use calc.exe to calculate XOR.

     The most often seen use of XOR is “XOR, EAX, EAX”. This will set EAX to 0, because when

     you XOR a value with itself, the result is always 0. I hope you understand why, else

     write down a value on paper and try ;)

 

---------------------------------------------------------------------------------------------

 

VII.  Logical Operations

 
 
Here follow the most used in a reference table.
 
 
                   Reference Table
 
     operation        src     dest    result
        AND            1        1       1
                       1        0       0
                       0        1       0
                       0        0       0   
        OR             1        1       1
                       1        0       1
                       0        1       1
                       0        0       0   
        XOR            1        1       0
                       1        0       1
                       0        1       1
                       0        0       0  
        NOT            0       N/A      1
                       1       N/A      0  

 

---------------------------------------------------------------------------------------------

 

 

 

Yep, indeed, this is already the END J Sorry if there are mistakes in this text.

 

 

 

'Hacking' 카테고리의 다른 글

SQL injection  (0) 2008.11.12
TCP flags  (0) 2008.11.07
Basic of Reverse Engineering  (0) 2008.11.06
CentOS Update Server and Local Repository  (0) 2008.10.31
OpenLDAP structure  (0) 2008.10.29
Posted by CEOinIRVINE
l

Assembler : The Basics In Reversing

 

 

Indeed: the basics!! This is all far from complete but covers about everything you need to know about assembler to start on your reversing journey! Assembler is the start and the end of all programming languages. After all, all (computer LOL) languages are translated to assembler. In most languages we deal with relatively clear syntaxes. However, it's a completely other story in assembler where we use abbreviations and numbers and where it all seems so weird …

 

 

I. Pieces, bits and bytes:

 

·         BIT - The smallest possible piece of data. It can be either a 0 or a 1. If you put a bunch of bits together, you end up in the 'binary number system'

 

i.e. 00000001 = 1       00000010 = 2             00000011 = 3     etc.

 

·         BYTE - A byte consists of 8 bits. It can have a maximal value of 255 (0-255). To make it easier to read binary numbers, we use the 'hexadecimal number system'. It's a 'base-16 system', while binary is a 'base-2 system'

 

·         WORD - A word is just 2 bytes put together or 16 bits. A word can have a maximal value of 0FFFFh (or 65535d).

 

·         DOUBLE WORD - A double word is 2 words together or 32 bits. Max value = 0FFFFFFFF (or 4294967295d).

 

·         KILOBYTE - 1000 bytes? No, a kilobyte does NOT equal 1000 bytes! Actually, there are 1024 (32*32) bytes.

 

·         MEGABYTE - Again, not just 1 million bytes, but 1024*1024 or 1,048,578 bytes.

 

 

---------------------------------------------------------------------------------------------

 

 

II. Registers:

 

Registers are “special places” in your computer's memory where we can store data. You can see a register as a little box, wherein we can store something: a name, a number, a sentence. You can see a register as a placeholder.

 

On today’s average WinTel CPU you have 9 32bit registers (w/o flag registers). Their names are:

 

EAX:   Extended Accumulator Register

EBX:   Extended Base Register

ECX:   Extended Counter Register

EDX:   Extended Data Register

ESI:    Extended Source Index

EDI:   Extended Destination Index

EBP:   Extended Base Pointer

ESP:   Extended Stack Pointer

EIP:    Extended Instruction Pointer

 

Generally the size of the registers is 32bit (=4 bytes). They can hold data from 0-FFFFFFFF (unsigned). In the beginning most registers had certain main functions which the names imply, like ECX = Counter, but in these days you can - nearly - use whichever register you like for a counter or stuff (only the self defined ones, there are counter-functions which need to be used with ECX). The functions of EAX, EBX, ECX, EDX, ESI and EDI will be explained when I explain certain functions that use those registers. So, there are EBP, ESP, EIP left:

 

EBP:   EBP has mostly to do with stack and stack frames. Nothing you really need to worry about, when you start. ;)

 

ESP:   ESP points to the stack of a current process. The stack is the place where data can be stored for later use (for more information, see the explanation of the push/pop instructions)

 

EIP:    EIP always points to the next instruction that is to be executed.

 

 

There's one more thing you have to know about registers: although they are all 32bits large, some parts of them (16bit or even 8bit) can not be addressed directly.

 

The possibilities are:

 

32bit Register                       16bit Register                      8bit Register

EAX                                  AX                             AH/AL

EBX                                  BX                              BH/BL

ECX                                  CX                             CH/CL

EDX                                  DX                             DH/DL

ESI                                   SI                              -----

EDI                                   DI                              -----

EBP                        BP                             -----

ESP                                  SP                             -----

EIP                                   IP                              -----

 

A register looks generally this way:

 

     |--------------------------- EAX: 32bit (=1 DWORD =4BYTES) -------------------------|

 

                                               |------- AX: 16bit (=1 WORD =2 BYTES) ----|

 

                                               |- AH:8bit (=1 BYTE)-|- AL:8bit (=1 BYTE)-|

 

     |-----------------------------------------|--------------------|--------------------|

     |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXX|

     |-----------------------------------------|--------------------|--------------------|

 

So, EAX is the name of the 32bit register, AX is the name of the "Low Word" (16bit) of EAX and AL/AH (8bit) are the “names” of the "Low Part" and “High Part” of AX. BTW, 4 bytes is 1 DWORD, 2 bytes is 1 WORD.

 

REMARK: make sure you at least read the following about registers. It’s quite practical to know it although not that important.

 

All this makes it possible for us to make a distinction regarding size:

 

·         i. byte-size registers: As the name says, these registers all exactly 1 byte in size. This does not mean that the whole (32bit) register is fully loaded with data! Eventually empty spaces in a register are just filled with zeroes. These are the byte-sized registers, all 1 byte or 8 bits in size:

o    AL  and AH

o    BL  and BH

o    CL  and CH

o    DL  and DH

·         ii. word-size registers: Are 1 word (= 2 bytes = 16 bits) in size. A word-sized register is constructed of 2 byte-sized registers. Again, we can divide these regarding their purpose:

 

o    1. general purpose registers:

 

AX (word-sized) = AH + AL -> the '+' does *not* mean: 'add them up'. AH and AL exist independently, but together they form AX. This means that if you change AH or AL (or both), AX will change too!

 

-> 'accumulator':               used to mathematical operations, store strings,..

BX -> 'base':                         used in conjunction with the stack (see later)

CX -> 'counter'

DX -> 'data':                         mostly, here the remainder of mathematical operations is stored

DI  -> 'destination index':         i.e. a string will be copied to DI

SI  -> 'source index':              i.e. a string will be copied from SI

 

o    2. index registers:

 

BP  -> 'base pointer':               points to a specified position on the stack (see later)
     SP  -> 'stack pointer':              points to a specified position on the stack (see later)

 

o    3. segment registers:


     CS -> 'code segment':             instructions an application has to execute (see later)
     DS -> 'data segment':             the data your application needs (see later)
     ES -> 'extra segment':            duh! (see later)
     SS -> 'stack segment':            here we'll find the stack (see later)

 

o    4. special:
  

IP  -> 'instruction pointer':       points to the next instruction. Just leave it alone ;)

 

·         iii. Doubleword-size registers:

 

2 words = 4 bytes = 32 bits. EAX, EBX, ECX, EDX, EDI…

 

If you find an 'E' in front of a 16-bits register, it means that you are dealing with a 32-bits register. So, AX = 16-bits; EAX = the 32-bits version of EAX.

 

 

---------------------------------------------------------------------------------------------

 

 

III. The flags:

 

Flags are single bits which indicate the status of something. The flag register on modern 32bit CPUs is 32bit large. There are 32 different flags, but don't worry. You will mostly only need 3 of them in reversing. The Z-Flag, the O-Flag and the C-Flag. For reversing you need to know these flags to understand if a jump is executed or not. This register is in fact a collection of different 1-bit flags. A flag is a sign, just like a green light means: 'ok' and a red one 'not ok'. A flag can only be '0' or '1', meaning 'not set' or 'set'.

 

·         The Z-Flag:

o    The Z-Flag (zero flag) is the most useful flag for cracking. It is used in about 90% of all cases. It can be set (status: 1) or cleared (status: 0) by several opcodes when the last instruction that was performed has 0 as result. You might wonder why "CMP" (more on this later) could set the zero flag, because it compares something - how can the result of the comparison be 0? The answer on this comes later ;)

 

·         The O-Flag:

o    The O-Flag (overflow flag) is used in about 4% of all cracking attempts. It is set (status: 1) when the last operation changed the highest bit of the register that gets the result of an operation. For example: EAX holds the value 7FFFFFFF. If you use an operation now, which increases EAX by 1 the O-Flag would be set, because the operation changed the highest bit of EAX (which is not set in 7FFFFFFF, but set in 80000000 - use calc.exe to convert hexadecimal values to binary values). Another need for the O-Flag to be set, is that the value of the destination register is neither 0 before the instruction nor after it.

 

·         The C-Flag:

o    The C-Flag (Carry flag) is used in about 1% of all cracking attempts. It is set, if you add a value to a register, so that it gets bigger than FFFFFFFF or if you subtract a value, so that the register value gets smaller than 0.

 

 

---------------------------------------------------------------------------------------------

 

 

IV. Segments en offsets

 

A segment is a piece in memory where instructions (CS), data (DS), the stack (SS) or just an extra segment (ES) are stored. Every segment is divided in 'offsets'. In 32-bits applications (Windows 95/98/ME/2000), these offsets are numbered from 00000000 to FFFFFFFF. 65536 pieces of memory thus 65536 memory addresses per segment. The standard notation for segments and offsets is:

 

SEGMENT                                  :        OFFSET        =       Together, they point to a specific place (address) in memory.

 

See it like this:

 

A segment is a page in a book     :        An offset is a specific line at that page.

 

 

---------------------------------------------------------------------------------------------

 

 

V. The stack:

 

The Stack is a part in memory where you can store different things for later use. See t as a pile of books in a chest where the last put in is the first to grab out. Or imagine the stack as a paper basket where you put in sheets. The basket is the stack and a sheet is a memory address (indicated by the stack pointer) in that stack segment. Remember following rule: the last sheet of paper you put in the stack, is the first one you'll take out! The command 'push' saves the contents of a register onto the stack. The command 'pop' grabs the last saved contents of a register from the stack and puts it in a specific register.

 

 

---------------------------------------------------------------------------------------------

 

 

VI. INSTRUCTIONS (alphabetical)

 

Please note, that all values in ASM mnemonics (instructions) are *always* hexadecimal.

 

 

Most instructions have two operators (like "add EAX, EBX"), but some have one ("not EAX") or even three ("IMUL EAX, EDX, 64"). When you have an instruction that says something with "DWORD PTR [XXX]" then the DWORD (4 byte) value at memory offset [XXX] is meant. Note that the bytes are saved in reverse order in the memory (WinTel CPUs use the so called “Little Endian” format. The same is for "WORD PTR [XXX]" (2 byte) and "BYTE PTR [XXX]" (1 byte).

 

Most instructions with 2 operators can be used in the following ways (example: add):

 

add eax,ebx                                         ;; Register, Register

add eax,123                                         ;; Register, Value

add eax,dword ptr [404000]                    ;; Register, Dword Pointer [value]

add eax,dword ptr [eax]                         ;; Register, Dword Pointer [register]

add eax,dword ptr [eax+00404000] ;; Register, Dword Pointer [register+value]

add dword ptr [404000],eax                    ;; Dword Pointer [value], Register

add dword ptr [404000],123           ;; Dword Pointer [value], Value

add dword ptr [eax],eax                         ;; Dword Pointer [register], Register

add dword ptr [eax],123                         ;; Dword Pointer [register], Value

add dword ptr [eax+404000],eax             ;; Dword Pointer [register+value], Register

add dword ptr [eax+404000],123             ;; Dword Pointer [register+value], value

 

 

---------------------------------------------------------------------------------------------

 

     ADD (Addition)

     Syntax: ADD destination, source

 

     The ADD instruction adds a value to a register or a memory address. It can be used in

     these ways:

 

     These instruction can set the Z-Flag, the O-Flag and the C-Flag (and some others, which

     are not needed for cracking).

 

---------------------------------------------------------------------------------------------

 

     AND (Logical And)

     Syntax: AND destination, source    

 

     The AND instruction uses a logical AND on two values.

     This instruction *will* clear the O-Flag and the C-Flag and can set the Z-Flag.

     To understand AND better, consider those two binary values:

 

                                    1001010110

                                    0101001101

 

     If you AND them, the result is 0001000100

     When two 1 stand below each other, the result is of this bit is 1, if not: The result

     is 0. You can use calc.exe to calculate AND easily.

 

---------------------------------------------------------------------------------------------

 

     CALL (Call)

     Syntax: CALL something

 

     The instruction CALL pushes the RVA (Relative Virtual Address) of the instruction that

     follows the CALL to the stack and calls a sub program/procedure.

 

     CALL can be used in the following ways:

 

     CALL        404000                             ;; MOST COMMON: CALL ADDRESS

     CALL        EAX                                 ;; CALL REGISTER - IF EAX WOULD BE 404000 IT WOULD BE SAME AS THE ONE ABOVE

     CALL        DWORD PTR [EAX]             ;; CALLS THE ADDRESS THAT IS STORED AT [EAX]

     CALL        DWORD PTR [EAX+5]                   ;; CALLS THE ADDRESS THAT IS STORED AT [EAX+5]

 

---------------------------------------------------------------------------------------------

 

     CDQ (Convert DWord (4Byte) to QWord (8 Byte))

     Syntax: CQD

 

     CDQ is an instruction that always confuses newbies when it appears first time. It is

     mostly used in front of divisions and does nothing else then setting all bytes of EDX

     to the value of the highest bit of EAX. (That is: if EAX <80000000, then EDX will be

     00000000; if EAX >= 80000000, EDX will be FFFFFFFF).

 

---------------------------------------------------------------------------------------------

 

     CMP (Compare)

     Syntax: CMP dest, source

 

     The CMP instruction compares two things and can set the C/O/Z flags if the result fits.

 

     CMP         EAX, EBX                          ;; compares eax and ebx and sets z-flag if they are equal

     CMP         EAX,[404000]                    ;; compares eax with the dword at 404000

     CMP         [404000],EAX                    ;; compares eax with the dword at 404000

 

---------------------------------------------------------------------------------------------

 

     DEC (Decrement)

     Syntax: DEC something

 

     dec is used to decrease a value (that is: value=value-1)

 

     dec can be used in the following ways:

     dec eax                                          ;; decrease eax

     dec [eax]                                        ;; decrease the dword that is stored at [eax]

     dec [401000]                                   ;; decrease the dword that is stored at [401000]

     dec [eax+401000]                            ;; decrease the dword that is stored at [eax+401000]

 

     The dec instruction can set the Z/O flags if the result fits.

   

---------------------------------------------------------------------------------------------

 

     DIV (Division)

     Syntax: DIV divisor

 

     DIV is used to divide EAX through divisor (unsigned division). The dividend is always

     EAX, the result is stored in EAX, the modulo-value in EDX.

 

     An example:

     mov eax,64                                     ;; EAX = 64h = 100

     mov ecx,9                                       ;; ECX = 9

     div ecx                                           ;; DIVIDE EAX THROUGH ECX

 

     After the division EAX = 100/9 = 0B and ECX = 100 MOD 9 = 1

 

     The div instruction can set the C/O/Z flags if the result fits.

 

---------------------------------------------------------------------------------------------

 

     IDIV (Integer Division)

     Syntax: IDIV divisor

 

     The IDIV works in the same way as DIV, but IDIV is a signed division.

     The idiv instruction can set the C/O/Z flags if the result fits.

 

---------------------------------------------------------------------------------------------

 

     IMUL (Integer Multiplication)

     Syntax:    IMUL value

                   IMUL dest,value,value

                   IMUL dest,value

 

     IMUL multiplies either EAX with value (IMUL value) or it multiplies two values and puts

     them into a destination register (IMUL dest, value, value) or it multiplies a register

     with a value (IMUL dest, value).

 

     If the multiplication result is too big to fit into the destination register, the

     O/C flags are set. The Z flag can be set, too.

 

---------------------------------------------------------------------------------------------

 

     INC (Increment)

     Syntax: INC register

 

     INC is the opposite of the DEC instruction; it increases values by 1.

     INC can set the Z/O flags.

 

 

---------------------------------------------------------------------------------------------

 

      INT

     Syntax: int dest

 

     Generates a call to an interrupt handler. The dest value must be an integer (e.g., Int 21h).

     INT3 and INTO are interrupt calls that take no parameters but call the handlers for

     interrupts 3 and 4, respectively.

 

---------------------------------------------------------------------------------------------

 

     JUMPS

     These are the most important jumps and the condition that needs to be met, so that

     they'll be executed (Important jumps are marked with * and very important with **):

 

JA*     -        Jump if (unsigned) above                        - CF=0 and ZF=0

JAE     -        Jump if (unsigned) above or equal            - CF=0

JB*     -        Jump if (unsigned) below                        - CF=1

JBE     -        Jump if (unsigned) below or equal            - CF=1 or ZF=1

JC       -        Jump if carry flag set                             - CF=1

JCXZ   -        Jump if CX is 0                                      - CX=0

JE**    -        Jump if equal                                        - ZF=1

JECXZ  -        Jump if ECX is 0                                    - ECX=0

JG*     -        Jump if (signed) greater                         - ZF=0 and SF=OF (SF = Sign Flag)

JGE*   -        Jump if (signed) greater or equal             - SF=OF

JL*      -        Jump if (signed) less                              - SF != OF (!= is not)

JLE*    -        Jump if (signed) less or equal                  - ZF=1 and OF != OF

JMP**  -        Jump                                                   - Jumps always

JNA     -        Jump if (unsigned) not above                   - CF=1 or ZF=1

JNAE   -        Jump if (unsigned) not above or equal       - CF=1

JNB     -        Jump if (unsigned) not below                   - CF=0

JNBE   -        Jump if (unsigned) not below or equal       - CF=0 and ZF=0

JNC     -        Jump if carry flag not set                        - CF=0

JNE**  -        Jump if not equal                                   - ZF=0

JNG     -        Jump if (signed) not greater                    - ZF=1 or SF!=OF

JNGE   -        Jump if (signed) not greater or equal        - SF!=OF

JNL     -        Jump if (signed) not less                         - SF=OF

JNLE    -        Jump if (signed) not less or equal             - ZF=0 and SF=OF

JNO     -        Jump if overflow flag not set                   - OF=0

JNP     -        Jump if parity flag not set                       - PF=0

JNS     -        Jump if sign flag not set                         - SF=0

JNZ     -        Jump if not zero                                    - ZF=0

JO       -        Jump if overflow flag is set                     - OF=1

JP       -        Jump if parity flag set                            - PF=1

JPE     -        Jump if parity is equal                            - PF=1

JPO     -        Jump if parity is odd                              - PF=0

JS       -        Jump if sign flag is set                            - SF=1

JZ       -        Jump if zero                                         - ZF=1

 

---------------------------------------------------------------------------------------------

 

     LEA (Load Effective Address)

     Syntax: LEA dest,src

 

     LEA can be treated the same way as the MOV instruction. It isn't used too much for its

     original function, but more for quick multiplications like this:

 

     lea eax, dword ptr [4*ecx+ebx]

     which gives eax the value of 4*ecx+ebx

 

---------------------------------------------------------------------------------------------

 

     MOV (Move)

     Syntax: MOV dest,src

 

     This is an easy to understand instruction. MOV copies the value from src to dest and src

     stays what it was before.

 

     There are some variants of MOV:

 

     MOVS/MOVSB/MOVSW/MOVSD EDI, ESI: Those variants copy the byte/word/dword ESI points to,

to the space EDI points to.

 

     MOVSX:   MOVSX expands Byte or Word operands to Word or Dword size and keeps the sign of the

value.

 

     MOVZX:   MOVZX expands Byte or Word operands to Word or Dword size and fills the rest of the

space with 0.

 

---------------------------------------------------------------------------------------------

 

     MUL (Multiplication)

     Syntax: MUL value

 

     This instruction is the same as IMUL, except that it multiplies unsigned. It can set the

     O/Z/F flags.

 

---------------------------------------------------------------------------------------------

 

     NOP (No Operation)

     Syntax: NOP

 

     This instruction does absolutely nothing

     That's the reason why it is used so often in reversing ;)

 

---------------------------------------------------------------------------------------------

 

     OR (Logical Inclusive Or)

     Syntax: OR dest,src

 

     The OR instruction connects two values using the logical inclusive or.

     This instruction clears the O-Flag and the C-Flag and can set the Z-Flag.

 

     To understand OR better, consider those two binary values:

 

                                    1001010110

                                    0101001101

    

     If you OR them, the result is 1101011111

 

     Only when there are two 0 on top of each other, the resulting bit is 0. Else the resulting

     bit is 1. You can use calc.exe to calculate OR. I hope you understand why, else

     write down a value on paper and try ;)

 

---------------------------------------------------------------------------------------------

 

     POP

     Syntax: POP dest

 

     POP loads the value of byte/word/dword ptr [esp] and puts it into dest. Additionally it

     increases the stack by the size of the value that was popped of the stack, so that the next

     POP would get the next value.

 

---------------------------------------------------------------------------------------------

 

     PUSH

     Syntax: PUSH operand

 

     PUSH is the opposite of POP. It stores a value on the stack and decreases it by the size

     of the operand that was pushed, so that ESP points to the value that was PUSHed.

 

---------------------------------------------------------------------------------------------

 

    REP/REPE/REPZ/REPNE/REPNZ

     Syntax: REP/REPE/REPZ/REPNE/REPNZ ins

 

     Repeat Following String Instruction: Repeats ins until CX=0 or until indicated condition

     (ZF=1, ZF=1, ZF=0, ZF=0) is met. The ins value must be a string operation such as CMPS, INS,

     LODS, MOVS, OUTS, SCAS, or STOS.

 

---------------------------------------------------------------------------------------------

 

     RET (Return)

     Syntax: RET

             RET digit

 

     RET does nothing but return from a part of code that was reached using a CALL instruction.

     RET digit cleans the stack before it returns.

 

---------------------------------------------------------------------------------------------

 

     SUB (Subtraction)

     Syntax: SUB dest,src

 

     SUB is the opposite of the ADD command. It subtracts the value of src from the value of

     dest and stores the result in dest.

 

     SUB can set the Z/O/C flags.

 

---------------------------------------------------------------------------------------------

 

     TEST

     Syntax: TEST operand1, operand2

 

     This instruction is in 99% of all cases used for "TEST EAX, EAX". It performs a Logical

     AND(AND instruction) but does not save the values. It only sets the Z-Flag, when EAX is 0

     or clears it, when EAX is not 0. The O/C flags are always cleared.

 

---------------------------------------------------------------------------------------------

 

     XOR

     Syntax: XOR dest,src

 

     The XOR instruction connects two values using logical exclusive OR (remember OR uses

     inclusive OR).

 

     This instruction clears the O-Flag and the C-Flag and can set the Z-Flag.

     To understand XOR better, consider those two binary values:

 

                                    1001010110

                                    0101001101

 

     If you OR them, the result is 1100011011

 

     When two bits on top of each other are equal, the resulting bit is 0. Else the resulting

     bit is 1. You can use calc.exe to calculate XOR.

     The most often seen use of XOR is “XOR, EAX, EAX”. This will set EAX to 0, because when

     you XOR a value with itself, the result is always 0. I hope you understand why, else

     write down a value on paper and try ;)

 

---------------------------------------------------------------------------------------------

 

VII.  Logical Operations

 
 
Here follow the most used in a reference table.
 
 
                   Reference Table
 
     operation        src     dest    result
        AND            1        1       1
                       1        0       0
                       0        1       0
                       0        0       0   
        OR             1        1       1
                       1        0       1
                       0        1       1
                       0        0       0   
        XOR            1        1       0
                       1        0       1
                       0        1       1
                       0        0       0  
        NOT            0       N/A      1
                       1       N/A      0  

 

---------------------------------------------------------------------------------------------

 

 

 

Yep, indeed, this is already the END J Sorry if there are mistakes in this text.

 

 

 

'Hacking' 카테고리의 다른 글

TCP flags  (0) 2008.11.07
Basic of Reverse Engineering  (0) 2008.11.06
CentOS Update Server and Local Repository  (0) 2008.10.31
OpenLDAP structure  (0) 2008.10.29
Linux open files  (0) 2008.10.28
Posted by CEOinIRVINE
l

CentOS Update Server and Local Repository

If you have a large number of CentOS servers, it is probably a good idea to have private update repositories on the local network. If each server has to download the same update over the public network connection, it will waste a lot of bandwidth. Not only will having private repos save network through-put, but there will also be a place to distribute your own custom RPM software packages.

The first thing to do is get a full copy of the release version of the OS from the installation media. Find a mirror that has the DVD image at CentOS isos downloads. Here, we are working with CentOS 5.2 64-bit.
# mkdir -p /repo/CentOS/5.2/iso
# cd /repo/CentOS/5.2/iso
# wget -c http://ftp.usf.edu/pub/centos/5.2/isos/x86_64/CentOS-5.2-x86_64-bin-DVD.iso
# mkdir -p /repo/CentOS/5.2/os
# mount -o loop /repo/CentOS/5.2/iso/x86_64/CentOS-5.2-x86_64-bin-DVD.iso /mnt
# rsync -avP /mnt/CentOS /repo/CentOS/5.2/os/
# umount /mnt


Now let's pull down all the latest updates from a mirror. You can find a good rsync mirror at the CentOS mirror list.
# mkdir -p /repo/CentOS/5.2/updates
# rsync -iqrtCO --exclude="*debuginfo*" --exclude="debug/" rsync://mirror.cogentco.com/CentOS/5.2/updates/x86_64 /repo/CentOS/5.2/updates/


Now that you have a local copy of the install media and all the latest RPMs, they should be shared out via http. For http access to the repo, install apache httpd and edit /etc/httpd/conf/httpd.conf, replacing instances of "/var/www/html" with "/repo". Make sure to update the "DocumentRoot" and "Directory" entries.
# yum -y install httpd
# vim /etc/httpd/conf/httpd.conf
# chkconfig httpd on ; service httpd start


We will also have to allow access through the repo server firewall for the local network. Edit /etc/sysconfig/iptables and add in the bellow line before the final DROP statement, substituting in your own subnet.
-A RH-Firewall-1-INPUT -s 192.168.1.0/255.255.255.0 -p tcp --dport 80 -j ACCEPT

and reload iptables:
# service iptables restart

On the systems where we wish to receive updates, we will need to create a .repo file, so our new repositories are used. Substitute in the IP of your own repo server. You may also have to disable the default repo file placed in by the installer, CentOS-Base.repo.
# cat /dev/null > /etc/yum.repos.d/CentOS-Base.repo
# vim /etc/yum.repos.d/internal.repo

# CentOS base from installation media
[base]
name=CentOS-$releasever - Base
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
baseurl=http://192.168.1.100/CentOS/$releasever/os/$basearch/
gpgcheck=1
gpgkey=http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
protect=1

# CentOS updates via rsync mirror
# rsync://mirror.cogentco.com/CentOS/5/updates/i386
# rsync://mirror.cogentco.com/CentOS/5/updates/x86_64
[update]
name=CentOS-$releasever - Updates
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
baseurl=http://192.168.1.100/CentOS/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
protect=1

# localy built and misc collected RPMs
[local]
name=CentOS-$releasever - Local
baseurl=http://192.168.1.100/local/el$releasever/$basearch
enabled=1
gpgcheck=0
protect=0


I prefer to use yum via cron and on boot. Enable this with the following:
# yum -y install yum-protectbase yum-updateonboot yum-cron
# chkconfig yum-updatesd off ; service yum-updatesd stop
# chkconfig yum-updateonboot on
# chkconfig yum-cron on


Notice that there is a "local" repository in the repo config above. This is a directory to hold our own custom RPMs. Any RPMs placed here can be installed via yum on other systems. Once new RPMs are place in, run createrepo to generate the metadata required by yum.
# mkdir -p /repo/local/el5/x86_64
# mv *.rpm /repo/local/el5/x86_64/
# createrepo -v --update /repo/local/el5/x86_64


Once there is a working repo server, updates to the repo dirs can be automated
# touch /etc/cron.daily/update_repo
# chmod +x /etc/cron.daily/update_repo
# vim /etc/cron.daily/update_repo

# CentOS updates
echo "####### rsync://mirror.cogentco.com/CentOS/5.2/updates/x86_64"
/usr/bin/rsync -iqrtCO --exclude="*debuginfo*" --exclude="debug/" rsync://mirror.cogentco.com/CentOS/5.2/updates/x86_64 /repo/CentOS/5.2/updates/


Now the repo will rsync daily with the latest updates. Then your other systems will do a yum-cron and install the updates. Make sure to substitute in your favorite and closest mirror. Enjoy your yum!

'Hacking' 카테고리의 다른 글

Basic of Reverse Engineering  (0) 2008.11.06
Basic of Reverse Engineering  (0) 2008.11.06
OpenLDAP structure  (0) 2008.10.29
Linux open files  (0) 2008.10.28
Microsoft Urgent Patch  (0) 2008.10.25
Posted by CEOinIRVINE
l

OpenLDAP structure

Hacking 2008. 10. 29. 03:39

A Technical Overview of OpenLDAP

This book is a practically oriented technical book. It is designed to help you get OpenLDAP up and running, and to help you integrate LDAP into your own applications.

We will now begin this transition from the high-level material presented earlier to a more practical examination of the OpenLDAP suite of packages. First, let's take a brief look at the technical structure of OpenLDAP.

The OpenLDAP suite can be broken up into four components:

  • Servers: Provide LDAP services

  • Clients: Manipulate LDAP data

  • Utilities: Support LDAP servers

  • Libraries: provide programming interfaces to LDAP

In the course of this book, we will look at all four of these categories. Here, we will just get an overview:

Image from book Click to collapse

This diagram explains how these four elements relate to each other.

The Server

The main server in the LDAP suite is SLAPD (the Stand-Alone LDAP Daemon). This server provides access to one or more directory information trees. Clients connect to the server over the LDAP protocol, usually using a network-based connection (though SLAPD provides a UNIX socket listener, too).

A server can store directory data locally, or simply access (or proxy access) to external sources. Typically, it provides authentication and searching services, and may also support adding, removing, and modifying directory data. It provides fine-grained access control to the directory.

SLAPD is a major focus of this book, and we will discuss it in detail in the chapters to come.

Clients

Clients access LDAP servers over the LDAP network protocol. They function by requesting that the server performs operations on their behalf. Typically, a client will first connect to the directory server, then bind (authenticate), and then perform zero or more other operations (searches, modifications, additions, deletions, and so on) before finally unbinding and disconnecting.

Utilities

Unlike clients, utilities do not perform operations using the LDAP protocol. Instead, they manipulate data at a lower level, and without mediation by the server. They are used primarily to help maintain the server.

Libraries

There are several OpenLDAP libraries that are shared between LDAP applications. The libraries provide LDAP functions to these applications. The clients, utilities, and servers all share access to some of these libraries.

Application Programming Interfaces (APIs) are provided to allow software developers to write their own LDAP-aware applications without having to re-write fundamental LDAP code.

While the APIs provided with OpenLDAP are written in C, the OpenLDAP project also provides two Java APIs. These Java libraries are not included in the OpenLDAP suite, and are not covered in this book. Both however, can be retrieved from the OpenLDAP website: http://openldap.org.

As we move on through this book we will examine each of these components of the LDAP architecture in detail.

'Hacking' 카테고리의 다른 글

Basic of Reverse Engineering  (0) 2008.11.06
CentOS Update Server and Local Repository  (0) 2008.10.31
Linux open files  (0) 2008.10.28
Microsoft Urgent Patch  (0) 2008.10.25
SSH without PASSWORD  (0) 2008.10.15
Posted by CEOinIRVINE
l

Linux open files

Hacking 2008. 10. 28. 06:12

spacerspacer
We knew the answer to this question once, back when the world was young and full of truth. Without hesitation, we'd have spouted "Just take the output of lsof | wc -l!" And it's true enough, in a general sort of way. But if you asked me the same question now, my answer would be: "Why do you want to know?"

Are you, for instance, attempting to determine whether the number of open files is exceeding the limit set in the kernel? Then the output of lsof will be practically useless.

Let's back up...

On *nix systems, there is a limit set in the kernel on how many open file descriptors are allowed on the system. This may be compiled in, or it may be tunable on the fly. In Linux, the value of this parameter can be read from and written to the proc filesystem.

[root@srv-4 proc]# cat /proc/sys/fs/file-max 
52427

On this system 52,427 open file descriptors are permitted. We are unlikely to run out. If we wanted to change it, we'd do something like this:

[root@srv-4 proc]# echo "104854" > /proc/sys/fs/file-max 
[root@srv-4 proc]# cat /proc/sys/fs/file-max 
104854

(Warning, change kernel parameters on the fly only with great caution and good cause)

But how do we know how many file descriptors are being used?

[root@srv-4 proc]# cat /proc/sys/fs/file-nr
3391    969     52427
|	 |       |
|	 |       |
|        |       maximum open file descriptors
|        total free allocated file descriptors
total allocated file descriptors
(the number of file descriptors allocated since boot)

The number of open file descriptors is column 1 - column 2; 2325 in this case. (Note: we have read contradictory definitions of the second column in newsgroups. Some people say it is the number of used allocated file descriptors - just the opposite of what we've stated here. Luckily, we can prove that the second number is free descriptors. Just launch an xterm or any new process and watch the second number go down.)

What about the method we mentioned earlier, running lsof to get the number of open files?

[root@srv-4 proc]# lsof | wc -l
4140

Oh my. There is quite a discrepancy here. The lsof utility reports 4140 open files, while /proc/sys/fs/file-nr says, if our math is correct, 2325. So how many open files are there?

What is an open file?

Is an open file a file that is being used, or is it an open file descriptor? A file descriptor is a data structure used by a program to get a handle on a file, the most well know being 0,1,2 for standard in, standard out, and standard error. The file-max kernel parameter refers to open file descriptors, and file-nr gives us the current number of open file descriptors. But lsof lists all open files, including files which are not using file descriptors - such as current working directories, memory mapped library files, and executable text files. To illustrate, let's examine the difference between the output of lsof for a given pid and the file descriptors listed for that pid in /proc.

Pick a PID, any PID

Let's look at this process:

usr-4    2381  0.0  0.5  5168 2748 pts/14   S    14:42   0:01 vim openfiles.html
[root@srv-4 usr-4]# lsof | grep 2381
vim        2381 usr-4  cwd    DIR        3,8    4096   2621517 /n
vim        2381 usr-4  rtd    DIR        3,5    4096         2 /
vim        2381 usr-4  txt    REG        3,2 2160520     34239 /usr/bin/vim
vim        2381 usr-4  mem    REG        3,5   85420    144496 /lib/ld-2.2.5.so
vim        2381 usr-4  mem    REG        3,2     371     20974 /usr/lib/locale/LC_IDENTIFICATION
vim        2381 usr-4  mem    REG        3,2   20666    192622 /usr/lib/gconv/gconv-modules.cache
vim        2381 usr-4  mem    REG        3,2      29     20975 /usr/lib/locale/LC_MEASUREMENT
vim        2381 usr-4  mem    REG        3,2      65     20979 /usr/lib/locale/LC_TELEPHONE
vim        2381 usr-4  mem    REG        3,2     161     19742 /usr/lib/locale/LC_ADDRESS
vim        2381 usr-4  mem    REG        3,2      83     20977 /usr/lib/locale/LC_NAME
vim        2381 usr-4  mem    REG        3,2      40     20978 /usr/lib/locale/LC_PAPER
vim        2381 usr-4  mem    REG        3,2      58     51851 /usr/lib/locale/LC_MESSAGES/SYSL
vim        2381 usr-4  mem    REG        3,2     292     20976 /usr/lib/locale/LC_MONETARY
vim        2381 usr-4  mem    REG        3,2   22592     99819 /usr/lib/locale/LC_COLLATE
vim        2381 usr-4  mem    REG        3,2    2457     20980 /usr/lib/locale/LC_TIME
vim        2381 usr-4  mem    REG        3,2      60     35062 /usr/lib/locale/LC_NUMERIC
vim        2381 usr-4  mem    REG        3,2  290511     64237 /usr/lib/libncurses.so.5.2
vim        2381 usr-4  mem    REG        3,2   24565     64273 /usr/lib/libgpm.so.1.18.0
vim        2381 usr-4  mem    REG        3,5   11728    144511 /lib/libdl-2.2.5.so
vim        2381 usr-4  mem    REG        3,5   22645    144299 /lib/libcrypt-2.2.5.so
vim        2381 usr-4  mem    REG        3,5   10982    144339 /lib/libutil-2.2.5.so
vim        2381 usr-4  mem    REG        3,5  105945    144516 /lib/libpthread-0.9.so
vim        2381 usr-4  mem    REG        3,5  169581    144512 /lib/libm-2.2.5.so
vim        2381 usr-4  mem    REG        3,5 1344152    144297 /lib/libc-2.2.5.so
vim        2381 usr-4  mem    REG        3,2  173680    112269 /usr/lib/locale/LC_CTYPE
vim        2381 usr-4  mem    REG        3,5   42897    144321 /lib/libnss_files-2.2.5.so
vim        2381 usr-4    0u   CHR     136,14                16 /dev/pts/14
vim        2381 usr-4    1u   CHR     136,14                16 /dev/pts/14
vim        2381 usr-4    2u   CHR     136,14                16 /dev/pts/14
vim        2381 usr-4    4u   REG        3,8   12288   2621444 /n/.openfiles.html.swp
[root@srv-4 usr-4]# lsof | grep 2381 | wc -l
30
[root@srv-4 fd]# ls -l /proc/2381/fd/
total 0
lrwx------    1 usr-4   usr-4         64 Jul 30 15:16 0 -> /dev/pts/14
lrwx------    1 usr-4   usr-4         64 Jul 30 15:16 1 -> /dev/pts/14
lrwx------    1 usr-4   usr-4         64 Jul 30 15:16 2 -> /dev/pts/14
lrwx------    1 usr-4   usr-4         64 Jul 30 15:16 4 -> /n/.openfiles.html.swp



Quite a difference. This process has only four open file descriptors, but there are thirty open files associated with it. Some of the open files which are not using file descriptors: library files, the program itself (executable text), and so on as listed above. These files are accounted for elsewhere in the kernel data structures (cat /proc/PID/maps to see the libraries, for instance), but they are not using file descriptors and therefore do not exhaust the kernel's file descriptor maximum.

'Hacking' 카테고리의 다른 글

CentOS Update Server and Local Repository  (0) 2008.10.31
OpenLDAP structure  (0) 2008.10.29
Microsoft Urgent Patch  (0) 2008.10.25
SSH without PASSWORD  (0) 2008.10.15
Reverse Engineering Tutoring 1  (0) 2008.10.04
Posted by CEOinIRVINE
l

Microsoft Urgent Patch

Hacking 2008. 10. 25. 03:24
Microsoft posts emergency defense for new attack

Susan Bradley By Susan Bradley

A remote-code exploit that could spread rapidly like the 2003 MSBlaster worm is putting all versions of Windows at risk.

I recommend that you immediately install a patch that Microsoft has just issued to protect your system from a vulnerability in the Server service.

MS08-067 (958644)
Rare out-of-cycle patch emphasizes the risk

With little warning, Microsoft released yesterday an unscheduled or "out-of-cycle" patch for a highly critical vulnerability that affects all versions of Windows. Security bulletin MS08-067 (patch 958644) was posted to warn of a remote-code attack that could spread wildly across the Internet.

Microsoft says it found evidence two weeks ago of an RPC (remote procedure call) attack that can potentially infect Windows machines across the Net with no user action required.

Windows Server 2003, 2000, and XP (even with Service Pack 2 or 3 installed) are particularly vulnerable. Vista and Server 2008 gain some protection via User Account Control, data-execution protection, and other safeguards, as explained in an
article by Dan Goodin in the Register.

While firewalls are a first line of defense against this attack, don't think you're secure just because you have a firewall. Malware and viruses use many different techniques to wiggle their way into our systems.

For example, my office's networks are protected by firewalls on the outside, but inside the network, PCs have file and printer sharing enabled. If a worm got loose inside the office network (and the patch hadn't been installed), the attack would spread like wildfire.

Many antivirus vendors have already issued definition updates that protect against this attack. Your antivirus program, however, may not protect you completely even if your AV definitions are up-to-date. Early reports indicate that there are already nine different strains of viruses trying to take advantage of this vulnerability. We can expect more to come, so even the best AV application may not be able to update fast enough.

I've tested this patch and have had no problems applying it. I strongly urge you to download and install this patch manually. Restart your PC before installing any patch to verify that your machine is bootable. Then be sure to reboot again after installing the patch, so the patched binaries completely replace the vulnerable components.

Microsoft has posted several versions of the patch that apply to different operating systems:
Microsoft has posted several versions of the patch that apply to different operating systems:

• Windows 2000 with Service Pack 4
patch download
• Windows XP with Service Pack 2 or 3 patch download
• Windows XP 64-bit Edition patch download
• Windows Server 2003 with Service Pack 1 or 2 patch download
• Windows Server 2003 64-bit Edition patch download
• Windows Vista with or without Service Pack 1 patch download
• Windows Vista 64-bit Edition with or without Service Pack 1 patch download
• Windows Server 2008 32-bit Edition patch download
• Windows Server 2008 64-bit Edition patch download

More information: Please read security bulletin MS08-067. For an excellent technical explanation of the vulnerability and possible mitigations, read TechNet's Oct. 23 description. (TechNet incorrectly refers to MS08-067 as "out-of-band," but the patch is simply out-of-cycle, because it wasn't released on Microsoft's usual Patch Tuesday monthly cycle.)

The Patch Watch column reveals problems with patches for Windows and major Windows applications. Susan Bradley recently received an MVP (Most Valuable Professional) award from Microsoft for her knowledge in the areas of Small Business Server and network security. She's also a partner in a California CPA firm.

'Hacking' 카테고리의 다른 글

OpenLDAP structure  (0) 2008.10.29
Linux open files  (0) 2008.10.28
SSH without PASSWORD  (0) 2008.10.15
Reverse Engineering Tutoring 1  (0) 2008.10.04
Testing Injection Exposures  (0) 2008.10.03
Posted by CEOinIRVINE
l

SSH without PASSWORD

Hacking 2008. 10. 15. 06:17


SSH Without a Password
The following steps can be used to ssh from one system to another without specifying a password.
Notes:
The system from which the ssh session is started via the ssh command is the client.
The system that the ssh session connects to is the server.
These steps seem to work on systems running OpenSSH.
The steps assume that a DSA key is being used. To use a RSA key substitute 'rsa' for 'dsa'.
The steps assume that you are using a Bourne-like shell (sh, ksh or bash)
Some of this information came from:
http://www.der-keiler.de/Mailing-Lists/securityfocus/Secure_Shell/2002-12/0083.html
Steps:
On the client run the following commands:
$ mkdir -p $HOME/.ssh $ chmod 0700 $HOME/.ssh $ ssh-keygen -t dsa -f $HOME/.ssh/id_dsa -P '' This should result in two files, $HOME/.ssh/id_dsa (private key) and $HOME/.ssh/id_dsa.pub (public key).
Copy $HOME/.ssh/id_dsa.pub to the server.
On the server run the following commands:
$ cat id_dsa.pub >> $HOME/.ssh/authorized_keys2 $ chmod 0600 $HOME/.ssh/authorized_keys2 Depending on the version of OpenSSH the following commands may also be required:
$ cat id_dsa.pub >> $HOME/.ssh/authorized_keys $ chmod 0600 $HOME/.ssh/authorized_keys An alternative is to create a link from authorized_keys2 to authorized_keys:
$ cd $HOME/.ssh && ln -s authorized_keys2 authorized_keys
On the client test the results by ssh'ing to the server:
$ ssh -i $HOME/.ssh/id_dsa server
(Optional) Add the following $HOME/.ssh/config on the client:
Host serverIdentityFile ~/.ssh/id_dsa This allows ssh access to the serverwithout having to specify the path to the id_dsa file as an argument to ssh each time.
Helpful manpages:
ssh(1)
ssh-keygen(1)
ssh_config(5)

 

Valid XHTML and CSS  //  Licensed under a Creative Commons Attribution 2.5 License
$Id: ssh_nopass.html 748 2006-08-06 05:21:59Z ranga $
 

'Hacking' 카테고리의 다른 글

Linux open files  (0) 2008.10.28
Microsoft Urgent Patch  (0) 2008.10.25
Reverse Engineering Tutoring 1  (0) 2008.10.04
Testing Injection Exposures  (0) 2008.10.03
Buffer Overflows  (0) 2008.10.03
Posted by CEOinIRVINE
l

'Hacking' 카테고리의 다른 글

Microsoft Urgent Patch  (0) 2008.10.25
SSH without PASSWORD  (0) 2008.10.15
Testing Injection Exposures  (0) 2008.10.03
Buffer Overflows  (0) 2008.10.03
LDAP Injection  (0) 2008.10.03
Posted by CEOinIRVINE
l