Jump to content

Search the Community

Showing results for tags 'input'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Informatii generale
    • Anunturi importante
    • Bine ai venit
    • Proiecte RST
  • Sectiunea tehnica
    • Exploituri
    • Challenges (CTF)
    • Bug Bounty
    • Programare
    • Securitate web
    • Reverse engineering & exploit development
    • Mobile security
    • Sisteme de operare si discutii hardware
    • Electronica
    • Wireless Pentesting
    • Black SEO & monetizare
  • Tutoriale
    • Tutoriale in romana
    • Tutoriale in engleza
    • Tutoriale video
  • Programe
    • Programe hacking
    • Programe securitate
    • Programe utile
    • Free stuff
  • Discutii generale
    • RST Market
    • Off-topic
    • Discutii incepatori
    • Stiri securitate
    • Linkuri
    • Cosul de gunoi
  • Club Test's Topics
  • Clubul saraciei absolute's Topics
  • Chernobyl Hackers's Topics
  • Programming & Fun's Jokes / Funny pictures (programming related!)
  • Programming & Fun's Programming
  • Programming & Fun's Programming challenges
  • Bani pă net's Topics
  • Cumparaturi online's Topics
  • Web Development's Forum
  • 3D Print's Topics

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website URL


Yahoo


Jabber


Skype


Location


Interests


Biography


Location


Interests


Occupation

Found 5 results

  1. In previous articles, we got to know the basics of the Stack Based Buffer Overflow and changing the address in the run time by modifying the register value using the debugger. In this article, we will analyze another simple C program which takes the user input and prints the same input data on the screen. In this article, we will not change any values by modifying the value through debugger like we did in the last article, but we will learn how to do it by user input values. Let us have a look at the program. In the program shown in the above screen shot, we have created two functions marked as 1 and 2. The 1st is the main function of the program from where the program execution will start. In the main function, there is a command to print message on the screen, then it is calling the V1 function. The 2nd one is defining the V1 function in which we have defined an array of size 10, then there are commands to take the user input and print it back to the output screen. In the V1 function, we have used the ‘gets’ function to take the user input. The ‘gets’ function is vulnerable to buffer overflow as it cannot check whether the size of the value entered by the user is lesser or greater than the size of the buffer. So, ‘gets’ would take whatever value the user enters and would write it into the buffer. If the buffer size is small, then it would write beyond the buffer and corrupt the rest of the stack. So, let’s analyze this with a debugger. Note: You can download the EXE file here: Download Now, let’s run this program normally. We can see that our program runs perfectly and it asks to “Enter the name”. When we enter the name and hit the enter key it accepts the value without crashing the program, as the input string is less than the size of the buffer we have created. Now, let us run the program again in the same manner, but this time we will enter a value which is greater in size than the buffer size. For this we enter 35 A’s (41 is the hexadecimal representation of A), then the program throws an error and our program gets crashed. We can see the same in the below screen shot. If we click on “click here” in the window shown in the above screenshot, we can see the following type of window on the screen. By closely looking into the red box, we can see the offset is written as ‘41414141’, which is actually the hexadecimal value of A. This clearly indicates that the program is vulnerable to buffer overflow. Note: In many cases, an application crash does not lead to exploitation, but sometimes it does. So, let us open the program with the debugger and create a break point just before the function ‘V1? is called and note down the return address. The return address is actually the next instruction address from where the function call happened. We can see the same in the below screen shot. (We have already mentioned all the basics in previous articles, so we are not going to discuss basics in detail again.) We can create the break point by selecting the address and pressing the F2 key. Run the program by hitting the F9 key and then click on F7 which is Step Into. It means we have created a break point before the V1 function call, after that the function ‘V1? is called and execution control has switched to the V1 function, and the Top of the Stack is now pointing to the return address of the main function, which can be seen in the screen shot given below. Now, we will note down the written address position as well as the written address from the Top of the Stack, which is the following. Table 1 Return Address Position Address Return Address to the Main Program 0022FF5C 004013FC We will overwrite this return address with the user input data in the next step of the article. If we look at the program screen we can see ‘Main Function is called’ is being shown on the screen. Now, hit Step Over until we reach the ‘gets’ function. This can be done by pressing the F8 key. As can be seen in the above screenshot, we have reached the gets function, now the program has continued to run. When we look at the program screen, we can see the program is asking to enter the name, so enter the name and hit the enter key. As can be seen, when we enter the name and hit the enter key, then execution control has moved to the next instruction and the program has again reached the Paused state. Now, hit the Step Over (F8 Key) until we reach the RETN instruction. If we look into the window 4 now, we can see that the top of the stack is pointing to the return address which is the following. Table 2 Return Address Position Address Return Address to the Main Program 0022FF5C 004013FC Now, we will have to compare the addresses of Table 1 and Table 2. Till now nothing caused any change in the tables we created, as we did not input anything wrong in the program. So, let us restart the program again and input a very long string value into the program input and analyze the return address when the program execution control reaches the RETN instruction. We can restart the program by pressing CTRL+F2 and input 35 A’s into the program. As can be seen in the above screenshot, we have entered a very long input value in the program, now hit the F8 key (Step Over) until we will reach the RETN instruction. Now, we will create another table and note down the Top of the Stack values into the table. Table 3 Return Address Position Address Return Address to the Main Program 0022FF5C 41414141 If we compare Table 2 and Table 3 addresses, we can see return address to the main program has been replaced to 41414141 in Table 3. 41 is actually the ASCII HEX value of A. So, we can see the return address has been overwritten by the user input value A. Now think, what if we could modify the input value at this position, and write some different address which points it to a location in the memory that contains your own piece of code. In this way, we can actually change the program flow and make it execute something different. The code that we want to execute after controlling the flow is often referred to as a “SHELLCODE”. We will discuss shellcode in later articles. But the string that we have entered contains 35 A’s, we do not know which ones have overwritten the stack. We will have to identify the positions in the user input where the stack is overwritten into the memory. We can do it by entering some pattern instead of A’s. The input pattern could be anything. We will use the following pattern. A1B2C3D4E5F6G7H8I9J0K1L2M3N4O5P6Q7U8S9T0U1V2W3X4Y5Z6 In this article, we have created this pattern manually, but in further articles we will use automated Metasploit scripts to generate the pattern. Now, we need to restart the program again in the debugger and enter the above pattern as an input in the program we created. As can be seen in the above screenshot, we have entered the pattern when the program asked for the input. Now, press F8 (Step Over) until we reach the RETN instruction. As we can see in the screenshot, we have reached the RETN instruction which can be seen in screen 1, and the Top of the Stack address has been overwritten by the user input and is pointing to the value “O5P6?. So, this 4 byte data is actually the return address in the user input. So, let us verify this by replacing the “O5P6? to “BBBB” in our pattern before entering the user input. So, now according to our logic, the return address should point to “BBBB” in the memory when we reach the RETN instruction. As can be seen in the above screenshot, our B’s have been successfully written in the position where the return address should be. So, if we change our B’s to the address somewhere else in the memory, then the program execution would go to that address and execute that instruction. In this way, we can control the program flow and run our own code just by manipulating the input data. So we have understood the following things by completing this exercise: Finding and Analyzing Buffer Overflow Overwriting Stack by User Input Data Identifying the Return Address Position in User Input References https://www.owasp.org/index.php/Buffer_overflow_attack http://en.wikipedia.org/wiki/C_file_input/output http://www.exploit-db.com/ http://www.pentesteracademy.com/ https://www.corelan.be/ Source
  2. Affected software: GoAhead Web Server Affected versions: 3.0.0 - 3.4.1 (3.x.x series before 3.4.2) CVE ID: CVE-2014-9707 Description: The server incorrectly normalizes HTTP request URIs that contain path segments that start with a "." but are not entirely equal to "." or ".." (eg. ".x"). By sending a request with a URI that contains these incorrectly handled segments, it is possible for remote attackers to cause a heap overflow with attacker-controlled content or perform a directory traversal attack. Fixed version: 3.4.2 Bug entry: https://github.com/embedthis/goahead/issues/106 Fix: https://github.com/embedthis/goahead/commit/eed4a7d177bf94a54c7b06ccce88507fbd76fb77 Reported by: Matthew Daley Detail: The vulnerability lies in the websNormalizeUriPath function. This function correctly handles the normalization of URIs consisting of normal segments as well as "." and ".." segments, but fails to handle other segments that start with a '.' character. A quick runthrough of the important parts of this function: The function starts by splitting up the URI into segments (at forward slashes) into an array. At the same time, it calculates the total length of these segments. The function then iterates through the resulting array in order to perform an in-place normalization (both the input and output pointers point to the same array): * If a given segment does not start with a '.', it is simply copied from the current input pointer to the current output pointer. The for loop's increment code will then advance both the input and output pointers. * Otherwise, if the segment is "." or "..", the input and output pointers are adjusted appropriately (taking into account the for loop's increment code) but (correctly) no segment is copied. * Otherwise the segment starts with a '.' but is not "." nor ".."; in this case the function incorrectly does nothing and both the input and output pointers are simply advanced by the for loop's increment code. This effectively skips over a segment in the segment array without any modification by the function. After this iteration has completed, a string buffer for the final output is allocated. The size used for this allocation comes from the previously-calculated total segment length, with the addition of space for forward slashes to join the segments back together again and a null terminator. The segments in the array up to the final output pointer are joined together in this buffer with forward slashes separating them. There are two ways to exploit this incorrect handling of certain segments: 1) Heap overflow The heap overflow exploitation lies in the possibility to create a disconnect between the lengths of the segments left in the segment array after the iteration has completed and the previously-calculated total segment length. The previously-calculated length should, in theory, be the worst-case (longest) final output string buffer size required (when all segments are left and none are removed by the normalization iteration). However, since we can force the iteration to skip over certain segments in the array, it is possible to effectively duplicate segments in the resulting array; this is done by having the segment copied from one location to another but then also having the original copy skipped over, making it appear in the resulting array twice. When this is done, the previously-calculated length is no longer long enough for the final output's string buffer, and a heap overflow occurs while joining together the final result. As an example, take the following URI as input to the function: "/./AAAAAAAA/.x". The URI is first split into the segments "", ".", "AAAAAAAA" and ".", with the total segment length calculated as 0 + 1 + 8 + 2 = 11 bytes. The normalization iteration proceeds as follows: * The "" segment is simply copied from input to output, and hence remains unchanged. Both the input and output pointers are then advanced. * The "." segment causes the output pointer to stay in place while the input pointer advances forward. * The "AAAAAAAA" segment is simply copied from input to output, and hence overwrites the previous "." segment. Both the input and output pointers are then advanced. * Finally, the ".x" segment is incorrectly handled: no modification of segments is performed but both the input and output pointers are still advanced, moving the output pointer over the original "AAAAAAAA" segment. Hence, the resulting segments in the array that are left up to the final output pointer are "", "AAAAAAAA" and "AAAAAAAA". Note that the "AAAAAAAA" segment has been duplicated. These segments, including space for forward slashes to join them together with and a null terminator, have a total length of 0 + 8 + 8 + 2 + 1 = 19 bytes. A string buffer is then allocated for the final output, which uses the previously-calculated total segment length of 11 bytes plus 3 bytes for forward slashes and 1 byte for a null terminator, giving a total size of 11 + 3 + 1 = 15 bytes. The resulting segments are finally joined together into this final output string buffer. In doing so in this case, however, the buffer is overflowed by 19 - 15 = 4 bytes. So, a remote attacker can make (ie.) a simple HTTP GET request for the URI in question and cause a heap overflow. ASAN gives the following output in this case, which shows the exact moment that the heap overflow occurs: ================================================================= ==2613==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60200000d47f at pc 0x7ffff6f34020 bp 0x7fffffffd410 sp 0x7fffffffcbd0 WRITE of size 9 at 0x60200000d47f thread T0 #0 0x7ffff6f3401f in __interceptor_strcpy (/usr/lib/x86_64-linux-gnu/libasan.so.1+0x2f01f) #1 0x7ffff63a7d6d in websNormalizeUriPath src/http.c:3320 #2 0x7ffff639b4de in parseFirstLine src/http.c:969 #3 0x7ffff639a905 in parseIncoming src/http.c:880 #4 0x7ffff639a4c9 in websPump src/http.c:829 #5 0x7ffff639a19c in readEvent src/http.c:802 #6 0x7ffff6399de7 in socketEvent src/http.c:740 #7 0x7ffff6399cbc in websAccept src/http.c:719 #8 0x7ffff63ac8ed in socketAccept src/socket.c:327 #9 0x7ffff63ade95 in socketDoEvent src/socket.c:638 #10 0x7ffff63add5f in socketProcess src/socket.c:622 #11 0x7ffff639daf8 in websServiceEvents src/http.c:1307 #12 0x401b5c in main src/goahead.c:153 #13 0x7ffff597ab44 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b44) #14 0x4011d8 (/home/matthew/goahead-3.4.1/build/linux-x64-debug/bin/goahead+0x4011d8) 0x60200000d47f is located 0 bytes to the right of 15-byte region [0x60200000d470,0x60200000d47f) allocated by thread T0 here: #0 0x7ffff6f5973f in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.1+0x5473f) #1 0x7ffff63a7d04 in websNormalizeUriPath src/http.c:3318 #2 0x7ffff639b4de in parseFirstLine src/http.c:969 #3 0x7ffff639a905 in parseIncoming src/http.c:880 #4 0x7ffff639a4c9 in websPump src/http.c:829 #5 0x7ffff639a19c in readEvent src/http.c:802 #6 0x7ffff6399de7 in socketEvent src/http.c:740 #7 0x7ffff6399cbc in websAccept src/http.c:719 #8 0x7ffff63ac8ed in socketAccept src/socket.c:327 #9 0x7ffff63ade95 in socketDoEvent src/socket.c:638 #10 0x7ffff63add5f in socketProcess src/socket.c:622 #11 0x7ffff639daf8 in websServiceEvents src/http.c:1307 #12 0x401b5c in main src/goahead.c:153 #13 0x7ffff597ab44 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b44) (... snip ...) As with all heap overflows, it's likely that this can then go on to be exploited in order to gain full remote code execution, especially in embedded systems which are less likely to have heap allocators with modern hardening techniques. 2) Directory traversal The directory traversal exploitation lies in the fact that we can force the normalization iteration to skip over certain segments in the array; namely, we can force it to skip over a ".." segment. The ".." segment will pass through unchanged into the final output string buffer, where it is treated by the rest of the server as an actual parent-directory relative segment. As an example, take the following URI as input to the function: "/../../../../../.x/.x/.x/.x/.x/.x/etc/passwd". The URI is first split into the segments "", "..", "..", "..", "..", "..", ".x", ".x", ".x", ".x", ".x", ".x", "etc", and "passwd". (The total segment length that is calculated during this operation is irrelevant for this mode of exploitation.) When the normalization iteration reaches the ".x" segments, the contents of the segment array are still untouched (as all the previous segments are either empty or are "..") and the output pointer is still pointing back at the "" segment. The incorrect handling of the ".x" segments only causes the output (and input) pointers to be advanced forward over the "" and ".." segments. When the iteration reaches the "etc" segment, all the "" and ".." segments have been skipped over; the output pointer is now pointing at the first ".x" segment. The "etc" is copied over the first ".x" segment, and the "passwd" segment is copied over the second ".x" segment. Hence, the resulting segments in the array that are left up to the final output pointer are "", "..", "..", "..", "..", "..", "etc" and "passwd"; note that the ".." segments are still present. The final output string buffer is created and the resulting segments are joined together to give a string of "/../../../../../etc/passwd". The rest of the server is expecting that the result from the function is normalized and that it contains no relative segments. Hence, the ".." segments go unnoticed when opening the content file while handling the HTTP request. The end result is that the local filesystem is traversed up from the administrator-configured web root until reaching the filesystem's root directory and back down again into the "/etc/passwd" file. Hence, the file "/etc/passwd" is given in response to the HTTP request, regardless of the configured web root. So, a remote attacker can make (ie.) a simple HTTP GET request for the URI in question and get the contents of the "/etc/passwd" file: $ echo -ne 'GET /../../../../../.x/.x/.x/.x/.x/.x/etc/passwd HTTP/1.0\r\n\r\n' | nc localhost 4700 HTTP/1.0 200 OK Server: GoAhead-http Date: Sun Nov 16 17:21:01 2014 Content-Length: 1346 Connection: close Last-Modified: Sat Oct 25 17:07:25 2014 root: x: 0: 0:root:/root:/bin/bash daemon: x:1:1: daemon:/usr/sbin:/usr/sbin/nologin bin: x : 2 : 2 : bin:/bin:/usr/sbin/nologin sys: x : 3 : 3 :sys:/dev:/usr/sbin/nologin sync: x:4:65534:sync:/bin:/bin/sync games: x:5:60:games:/usr/games:/usr/sbin/nologin man: x:6:12:man:/var/cache/man:/usr/sbin/nologin lp: x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin mail: x:8:8:mail:/var/mail:/usr/sbin/nologin (... snip ...) Of course, 5 ".." segments may not be enough to reach the filesystem's root directory in all cases and so the crafted URI may have to be extended with more ".." and ".x" segments. - Matthew Daley Source: http://dl.packetstormsecurity.net/1503-exploits/goahead341-overflowtraversal.txt
  3. ########################### #Exploit Title: # Script Cisco Network Academy - Stored XSS vulnerability #Date: 017/03/2015 #Author: kabanni bntdzdz@gmail.com #Product web page: www.cisco.com #Tested on: Windows 8.1 #OSVDB-ID: ########################### 0-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-1 1 ______ 0 0 .-" "-. 1 1 / HaChkerz_Dz \ =-=-=-=-=-=-=-=-=-=-=-=| 0 0 Algerian HaCker | | > Site : GDGBordj.org | 1 1 --------------- |, .-. .-. ,| > fb : @kabanni | 0 0 | )(_o/ \o_)( | > [email]kacily2008@gmail.com[/email]| 1 1 |/ /\ \| =-=-=-=-=-=-=-=-=-=-=-| 0 0 (@_ (_ ^^ _) 0X00 Team 1 1 _ ) \_______\__|IIIIII|__/_______________________ 0 0 (_)@8@8{}<________|-\IIIIII/-|________________________> 1 1 )_/ \ / 0 0 (@ `--------` 2015, 0x00 Team 1 1-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-0 0 Script Cisco Network Academy XSS vulnerability 1 1-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-0 ########################## Description A vulnerability in the web framework of Cisco Netacad could allow an unauthenticated, remote attacker to conduct a cross-site scripting (XSS) attack against a user of the web interface on the affected system. The vulnerability is due to insufficient input validation of several parameters in the input fields Quarantine web page. An attacker could exploit this vulnerability by persuading a user to access a malicious link. # Sample Payload for Stored XSS: "<script>alert(0);</script> " # Solution Fix & Patch: Filter the input fields aganist to XSS attacks & Upgrade the the script. #Security Risk: The risk of the vulnerabilities above estimated as high. #Proof of Concept (PoC): <input type="TEXT" maxlength="250" size="50" name="ANSWERrt_239101" disabled=""> #Details of the attack: The web site netacd.com , is allowed to the users pass the exams of CCNA . The questions compose in many format like Check box , Radio , and Input field . When enter the code malicious to a question witch content an input field , finally if submit the answers ,and when go to show the assessment , the user appear a message java script . --==[[ Greetz To ]]==-- ############################################################################################ #0x00 , Alhack , Mr.elhdj Google , Hakim_Ghorb , Mohamed Ramaden , Team Anonymous . #Mr.Zaki ,Dr.Ben Taleb,Nas_unknown ,Dahmani,Good_person ,Boud_Sah ,Moh_Dz ,Yass_assasine. #Amin-Biskra , Bouhlel ,Meliani, Najmo & All students TIC & Informatics at Univ-Msila ############################################################################################# --==[[Love to]]==-- # My Father & Mother ,All Kacem(bira9i9) ,my Ex Teacher , My wife . --==[[ All Muslims Hachers ]]==-- <3 0x00 Team <3 Source
  4. What is OWASP ProActive Controls? In one line, this project can be explained as “Secure Coding Practices by Developers for Developers“. OWASP ProActive Controls is a document prepared for developers who are developing or are new to developing software/application with secure software development. This OWASP project lists 10 controls that can help a developer implement secure coding and better security inside the application while it is being developed. Following these secure application development controls ensures that the key areas of the development cycle have secure coding along with traditional coding practices. The strength of this project is not just in the listed 10 controls but in the key references associated with it. Every control extends the knowledge and capabilities by mentioning existing OWASP or other open source projects that can be used to strengthen the security of an application. The ten controls defined by this project are: Parameterize Queries Encode Data Validate All Inputs Implement Appropriate Access Controls Establish Identity and Access Controls Protect Data and Privacy Implement Logging, Error Handling and Intrusion Detection Leverage Security Features of Frameworks and Security Libraries Include Security-Specific Requirements Design and Architect Security In Let us go deeper into each ProActive Control and see what it takes for us to implement it in the real world. PARAMETERIZE QUERIES One of the most dangerous attacks on a Web application and its backend data storage is SQL injection. It occurs when a user sends malicious data to an interpreter as an SQL query, which then manipulates the backend SQL statement. It is easy for an attacker to find a SQLi vulnerability using automated tools like SQLMap or by manual testing. The simplest and most popular attack vector used is: 1? or ‘1’= ‘1 Submitting it as a username and password or in any other field can lead to an authentication bypass in many cases. Here is an example of typical SQL injection in a user authentication module: String username= request.getParameter(“username”); String password= request.getParameter(“password”); Class.forName("com.mysql.jdbc.Driver"); Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://database-server:3306/securitydb:", "root" ,"root"); Statement st= con.createStatement(); ResultSet rs=st.executeQuery("select * from users where username='"+username+"' and password='"+password+"' limit 0,1"); In this vulnerable code, the ‘Statement’ class is used to create a SQL statement, and at the same time it is modified by directly adding user input to it, then it is executed to fetch results from the database. Performing a simple SQLi attack in the username field will manipulate the SQL query, and an authentication bypass can take place. To stop a SQLi vulnerability, developers must prevent untrusted input from being interpreted as a part of a SQL query. It will lead to an attacker not being able to manipulate the SQL logic implemented on the server side. OWASP ProActive Controls recommends that developers should use parameterized queries only in combination with input validation when dealing with database operations. Here is an example of SQL query parameterization: String username=request.getParameter(“username”); String password=request.getParameter(“password”); Class.forName(“com.mysql.jdbc.Driver”); Connection con=( Connection) DriverManager.getConnection("jdbc:mysql://database-server:3306/securitydb:", "root" ,"root"); PreparedStatement ps=(PreparedStatement) con.prepareStatement("select * from users where username=? and password=? limit 0,1"); ps.setString(1,username); ps.setString(2,password); ResultSet rs=ps.executeQuery(); if(rs.next()) out.println("Login success"); else out.println("Login failed"); Using a parameterized query makes sure that the SQL logic is defined first and locked. Then the user input is added to it where it is needed, but treated as a particular data type string, integer, etc. as whole. In a database operation with a parameterized query in the backend, an attacker has no way to manipulate the SQL logic, leading to no SQL injection and database compromise. SQL injection vulnerability has been found and exploited in applications of very popular vendors like Yahoo! too. ENCODE DATA Data encoding helps to protect a user from different types of attacks like injection and XSS. Cross Site Scripting (XSS) is the most popular and common vulnerability in Web applications of smallest to biggest vendors with a Web presence or in their products. Web applications take user input and use it for further processing and storing in the database when ever needed. Also user input could be part of the HTTP response sent back to the user. Developers should always treat user input data as untrusted data. If user input at any point of time will be part of the response to user, then it should be encoded. If proper output encoding has been implemented, then even if malicious input was sent, it will not be executed and will be shown as plain text on the client side. It will help to solve a major web application vulnerability like XSS. Here is an example of XSS vulnerability: if(request.getMethod().equalsIgnoreCase("post")) { String name = request.getParameter("name"); if(!name.isEmpty()) { out.println("<br>Hi "+name+". How are you?"); } } In the above code, user input is not filtered and used, as it is part of message to be displayed to the user without implementing any sort of output encoding. Most common XSS vulnerabilities that affect users and are found in applications are of two types: Stored XSS Reflected XSS Stored XSS are those XSS which get stored on a sever like in a SQL database. Some part of the application fetches that information from the database and sends it to the user without properly encoding it. It then leads to malicious code being executed by the browser on the client side. Stored XSS can be carried out in public forums to conduct mass user exploitation. In Reflected XSS, the XSS script does not get stored on the server but can be executed by the browser. These attacks are delivered to victims via common communication mediums like e-mail or some other public website. By converting input data into its encoded form, this problem can be solved, and client side code execution can be prevented. Here is an example of output encoding of user input: if(request.getMethod().equalsIgnoreCase("post")) { String name = StringEscapeUtils.escapeHtml(request.getParameter("name")); if(!name.isEmpty()) { out.println("<br>Hi "+name+". How are you?"); } } In the next section you will see how input validation can secure an application. Combining input validation with data encoding can solve many problems of malicious input and safeguard the application and its users from attackers. OWASP has a project named OWASP ESAPI, which allows users to handle data in a secure manner using industry tested libraries and security functions. VALIDATE ALL INPUTS One of the most important ways to build a secure web application is to restrict what type of input a user is allowed to submit. This can be done by implementing input validation. Input validation means validating what type of input is acceptable and what is not. Input validation is important because it restricts the user to submit data in a particular format only, no other format is acceptable. This is beneficial to an application, because a valid input cannot contain malicious data and can be further processed easily. Important and common fields in a web application which require input validation are: First Name, Last Name, Phone Number, Email Address, City, Country and Gender. These fields have a particular format which has to be followed, especially email and phone number, which is very common. It is a known fact that first name and last name cannot have numbers in them; you cannot have a name as John39 *Bri@n. Such user input is treated as malicious and thus requires input validation. Input validation can be implemented on client side using JavaScript and on the server side using any server side language like Java, PHP etc. Implementing server side input validation is compulsory, whereas client side is optional but good to have. Now input validation is again of two types: Blacklist Whitelist The simplest example to explain the two can be: A security guard stops all guys wearing a red t-shirt who are trying to enter a mall, but anyone else can enter. This is a blacklist, because we are saying the red color is blocked. Whereas a whitelist says that guys wearing white, black and yellow t-shirt are allowed, and the rest all are denied entry. Similarly in programming, we define for a field what type of input and format it can have. Everything else is invalid. It is called whitelisting. Blacklisting is invalidating an input by looking for specific things only. For example, specifying that a phone number should be of 10 digits with only numbers is whitelist. Searching input for A-Z and then saying it is valid or not is blacklisting, because we are invalidating using alphabet characters only. Blacklisting has been proven to be weaker than whitelisting. In the above case, if a user enters 123456+890, then a blacklist will say it is valid because it does not contain A-Z. But it is wrong. Whereas a whitelist will say it contains a character that is not a number, and only numbers are allowed, so it is invalid. Input validation can be implemented in a web application using regular expressions. A regular expression is an object that describes a pattern of characters. These are used to perform pattern based matching on input data. Here is the example of a regular expression for first name: ^[a-zA-Z ]{3,30}$ This regular expression ensures that first name should include characters A-Z and a-z. The size of first name should be limited to 3-30 characters only. Let’s take another example of regular expression for username: ^[a-z0-9_]{3,16}$ Here this expression shows that username should include alphabets ‘a-z’, numbers ‘0-9? and special characters underscore ‘_’ only. The input length should be limited to 3-16 only. Email address validation can be performed using the following regular expression: ^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$ Depending upon the programming language a developer uses to build an application, regular expression can easily be implemented in it. Another advantage of regular expressions is that there are many industry tested regular expressions for all popular input types. So you don’t have to write one from scratch and then get it security tested. It is better to use industry tested regular expressions than writing one on your own (which in most cases will be flawed). OWASP has an Input Validation Cheat Sheet to help you implement proper input validation in your application. IMPLEMENT APPROPRIATE ACCESS CONTROLS Before we begin, it should be crystal clear that authentication is not same as authorization. Authentication takes care of your identity, whereas authorization makes sure that you have the authority or privilege to access a resource like data or some sensitive information. A simple real world example to show this can be: Alice visits Bob’s home. Her identity is known to Bob, so he allows her to enter her home (if she was not known to Bob then entry would have been denied, aka authentication failure). Alice is now inside Bob’s home. But she cannot open Bob’s family safe at home, because she is not authorized to do so. On the other hand, Bob’s sister Eve is known, so successful authentication occurs, and she is a family member, so she is authorized to access the family safe, aka successful authorization. Implementing authorization is one of the key components of application development. It has to be ensured at all times that access certain parts of the application should be accessible to users with certain privileges only. Authorization is the process of giving someone permission to do or have something. It is to be noted again that authentication is not equivalent to authorization. Many developers have a tough time handling authorization, and at some point leave a gap that gets exploited, leading to unauthorized data access. To solve this problem, access control or authorization checks should always be centralized. All user requests to access some page or database or any information should pass through the central access control check only. Access control checks should not be implemented at different locations in different application codes. If at any point in time you have to modify an access control check, then you will have to change it at multiple locations, which is not feasible for large applications. Access control should by default deny all requests which are from a user for a resource for which either access is restricted or an authorized entry has not been made. Layered Authorization Checks should be implemented. It means that the user’s request should be checked for authorization in layered manner instead of a haphazard manner. Below is an example: User requests “/protected” file access. Is user logged-in? Is user normal user or privileged user? Is user allowed access to the resource? Is resource marked as locked? f the access control check at any point in 1-5 fails, then the user will be denied access to the requested resource. OWASP Access Control Cheat Sheet can prove to be good resource for implementing access control in an application. ESTABLISH IDENTITY AND AUTHENTICATION CONTROLS Authentication is the process by which it is verified that someone is who they claim to be, or we can say it is the process of identifying individuals. Authentication is performed by entering username or password or any sensitive information. Authentication and identity are two components of accessing any kind of information that goes hand-in-hand. For example, if you want to access your bank account details or perform a transaction, you need to login into your bank account website. Successfully authenticating to your bank account proves that you are the owner of that account. From this discussion, it is clear that username and password are the elements of authentication that prove your identity. OWASP ProActive: Establish Identity and Authentication Controls says that all the modules of an application which are related to authentication and identity management should have proper security in place and secure all sensitive information. Also, an application should request for and store only the information which is absolutely needed, and nothing else. Sensitive information like password and account number should be either stored in encrypted or hashed format inside a database, so that it cannot be misused by a malicious user if he or she gains unauthorized access and decrypts it easily. Below is an example of an application that stores the user’s password in plaintext inside a MySQL database. String username=request.getParameter("username"); String password=request.getParameter("password"); PreparedStatement ps = (PreparedStatement) con.prepareStatement("insert into login_users values(?,?)"); ps.setString(1,username); ps.setString(2,password); Here the password is stored in plain text. If the database is compromised at the same time, the attacker will be able to access the user account easily. The attacker will be able to login to the user’s account using the username and password from the database, which is stored in plain text. But this vulnerability can be exploited by converting sensitive information into a hashed format, like in salted MD5 or SHA2 hash format or in encrypted form. Here is an example of hashing sensitive information before storing it in a SQL database: String username=request.getParameter("username"); String password=request.getParameter("password"); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(),0,s.length()); String calc_hash = new BigInteger(1,m.digest()).toString(16); if(calc_hash.length()<32) { calc_hash = "0"+calc_hash; } PreparedStatement ps = (PreparedStatement) con.prepareStatement("insert into login_users values(?,?,?)"); ps.setString(1,username); ps.setString(2,password); ps.setString(3,calc_hash); The above code shows that here sensitive information (i.e. password) is stored in a salted MD5 format. The salt is different for every new registration. If the database is compromised, then the attacker will have to find clear text for the hashed passwords, or else it will be of no use. Broken Session Management is also a type of vulnerability which exists in a web application that does not properly implement session management. For example, if a user logs out from his/her account, but he/she is redirected to some page, but session is not invalidated properly, a post-login page is opened without asking for re-authentication. Another example can be a session cookie for pre- and post-login being same. Vulnerable code: String username = request.getParameter("username"); String password = request.getParameter("password"); PreparedStatement ps=(PreparedStatement) con.prepareStatement("select * from users where username=? and password=? limit 0,1"); ps.setString(1,username); ps.setString(2,password); ResultSet rs=ps.executeQuery(); if(rs.next()) { session.setAttribute("useracc", rs.getString("username")); out.println("Login success"); } else { out.println("Login failed"); } Observe in the above code that the session cookie JSESSIONID remains the same for pre- and post-login. This vulnerability can be exploited by an attacker who has physical access to the machine and notes the value of session cookie pre-authentication. This attack is known as Session Fixation. This patched code will invalidate the session when authentication is successful and creates a new session cookie value. This changes the post-login session cookie value, and Session Fixation vulnerability cannot be exploited. String username=request.getParameter(“username”); String password=request.getParameter(“password”); PreparedStatement ps=(PreparedStatement) con.prepareStatement("select * from users where username=? and password=? limit 0,1"); ps.setString(1,username); ps.setString(2,password); ResultSet rs=ps.executeQuery(); if(rs.next()) { session.invalidate(); request.getSession(true); session.setAttribute("useracc", rs.getString("username")); out.println("Login success"); } else { out.println("Login failed"); } The session cookie value should never be predictable, and should comply with strong complexity for better security. Authentication and secure storage is not just limited to the username-password module of an application. Other key modules like forgot password and change password are also part of authentication. Financial data and personal information like SSN are some of the most important details a person is concerned with, so an application storing that data should make sure it is encrypted securely. OWASP has some key resources like: Authentication Cheat Sheet Session Management Cheat Sheet In this part of OWASP ProActive Controls, we discussed in depth how ProActive Controls 1-5 can be used in an application as a secure coding practice to safeguard it from well-known attacks. The controls discussed do not modify application development lifecycle, but ensure that application security is given the same priority as other tasks and can be carried out easily by developers. We will see the last 5 ProActive Controls in the next and final part. Reference: https://www.owasp.org/index.php/OWASP_Proactive_Controls Source
  5. Introduction In this last part of the Website Hacking series, we are going to list 18 common web vulnerabilities and flaws and we are going to briefly provide solutions to them. Some of them are described for the first time in the Website Hacking series and some we have discussed before but in greater depth. 1. Saving all user input If you are using a framework, for example, a PHP framework, you might be tempted to save all user input to your model or database since it has already been validated and escaped. Let us say that you are using CakePHP and have included a registration form using CakePHP’s Form helper. SNIPPET 1 Now, you might be tempted to save all data from CakePHP’s $this->request->data array/method as is if you do not read the docs carefully or view some of the examples provided there (the live blog site). SNIPPET 2 You just save all data and thank the framework creators. However, there are at least two things you did wrong: $this->request->data does not contain escaped/sanitized input, just the input from the superglobals. Firstly, you should use CakePHP’s h() function to prevent people inserting tags in their username: like this h($this->request->data) However, this is not enough and a wrong approach. If you save all user input in your Model (database) the user can add new input tags directly in his browser and try to guess some columns in your users table for which you have not provided an input in the website’s form. For example, many CakePHP’s applications have “role” column set to user/admin or something similar (it is used in the docs as well). The user can just open his Developer Tools, find the registration form or right click and select Inspect Element, click on Edit as HTML and add a new input like this: <input name=”data[user][role]” type=”text”> <input name=” [user][role]” type=”text”> Or whatever the current way for forms to interact with your Models is, guess column names and insert values to them. One way to solve this is to change your column that defines user’s roles and permissions name to something unpredictable. However, that is not the safest approach you can take. You can either insert the data into the database manually, which will ensure no extra columns will be saved: SNIPPET 3 Or alternatively, you could still save all user data but set explicitly the values of columns not found in the form: SNIPPET 4 2. Allowing user access to assets Many sites work with user input and user data and store this data. Clients can see where their assets are stored, so there is no need for them to guess. For example, a client could see that the images he uploaded were stored in /uploads/{username} because the images he uploaded were loaded to the page from that directory, so if he knows some usernames of different people he could just change the directory name to another user and browse through all of his data without having to brute-force directory names. The first way to tackle this issue that we discussed before is not enough (adding Options All –Indexes to the .htaccess file).It would prevent users from browsing directories and opening whatever they want but they would still know the directory exists and they can still guess directory names because the server will return a 403 Forbidden (which shows something exists in that path). Furthermore, they could guess file names from some patterns that the file names follow and open them. Therefore, you need to block access to the files in your uploads directory. If you are storing text files (let us say users can keep notes and view/edit them whenever they want) you could add to your .htaccess the following rule: RewriteEngine On RewriteRule ^uploads/.*.(txt|doc)$ – [F,L,NC] The F flag would return a 403 Forbidden response, the L flag causes the next rules to stop being processed, and the NC eliminates case-sensitivity. Figure 1: The page with only directory listing disabled. Figure 2: The page with only directory listing disabled. You cannot browse directories, but if each user has a notes.txt file, you can easily view user’s notes by knowing only their username. Figure 3: Trying to access the notes with both directory listing and controlled access to files. If you use the rewrite rule to disable users from browsing other users notes, your back-end would still be able to access the notes, show them to users or edit them. For example: SNIPPET 5 Where the $user variable would come from a session in a real-world application. 3. Running basic WordPress installation Common mistakes here are not limiting the login attempts on your wp-admin page. This would allow anyone to brute-force your credentials and destroy your blog/site. This becomes even easier because most people create their master username to be ‘admin’ which involves only brute-forcing the password to get full access to the WP website. Another mistake is that the wp-admin login page is left without a form of CAPTCHA or a protection against bots. This combined with no limitation of login attempts equals certain death of your online presence at some point in the future. You could avoid all 3 of these things and also change the default wp-admin path to be something different as well (obfuscation). 4. Relying too much on IP addresses while having weak bot protection Most ISPs provide dynamic IP addresses, and the IP address you have banned or stored may already be obsolete in less than a day. Furthermore, it is often not very difficult to change your IP address – use a proxy, release it from the router or from the OS, change locations. There are myriad ways to do it. To prevent bots from causing undesired consequences, it would be better to use alternative ways – enhance your CAPTCHAs, add inputs only bots will fill out, require JavaScript/cookies enabled to submit a form, and so on. 5. Improper redirects Let us say that you have a redirect page or a GET value (for simplicity’s sake) that redirects users to another page of your site or to another website. However, if you forget to disallow redirects to third-party websites or in case you allow those, if you do not create a warning page before redirecting that will tell the user where they are going and that they are leaving the site – users can easily abuse your site by giving links that seem to be pointing to your site but will redirect users to malicious websites. if (isset($_GET['redirect'])) { header("Location: " . $_GET['redirect']); } If we have something as simple as this, then users can easily get fooled to enter bad sites by following an URL like this: http://localhost:8079/articles/Website%20Hacking%20Part%20VII/?redirect=http://www.somemalicioussitehere.com 6. Cross Site Request Forgery If your site allows users to add comments/posts and insert tags such as <img> and load a third-party image, they can provide a link that is not an image but will fool the clients’ browsers (the users that will be reading them) to load the resource and perform an action on a website if they are authenticated in it. For example, if Facebook was sufficed with a couple of GET parameters or a particular URL to follow someone/something on their network, we could have added an image like that: my image And if the user is currently logged in he would have followed an arbitrary person. Of course, this would not work in this particular situation. 7. Insecure file handling A common mistake is to trust that a file does not contain something inappropriate. Code can be disguised as an image, so checking the file extension is not enough. At the very least, the MIME type should also be checked. Also, ASCII / text files should be escaped. Here is an example of such a vulnerability: SNIPPET 6 The vulnerability arises when at some point we display the contents of the .txt file in our page: SNIPPET 7 If the file we submit contains the following code: <script> alert(document.cookie); </script> Then all user cookies for that website will be shown in an alert. 8. Displaying and trusting HTTP headers These can be modified by users and can be malicious. For example, if you display the client’s User-Agent header, it might be changed to consist of code which would then be executed in your back-end. This is also valid for the referrer header, so it should not be used to determine whether the user can access a particular page by itself (for example, checking if the referfer is the login page and assuming the user has logged in successfully since he was redirected to the members area’s index page from the login page). 9. Information disclosure Your live apps should not be in debug mode. Errors should not be shown. 10. Directory traversal If you are using some parameter that opens different files on your website based on user input, your back-end should escape special characters such as the . (dot) or / (slash) from the input and preferably use whitelisting. 11. Using HTTP for semi-confidential data A common flaw is using HTTP for sites that include mechanisms such as registration/login. Even widely used online marketplaces in Bulgaria use simple HTTP (such as OLX.bg - ???? ?? ????????? ????? ). Using HTTP makes it easy for potential attackers in your network to sniff your traffic and get your credentials with no real efforts. For example, if you login to olx while in a Wi-Fi, you are subject to risk. 13. Sessions can be stolen Sessions can be stolen, making the attacker login as someone else. There are multiple vectors of defense here – such as checking the IP address, the user agent, and regenerating session, and adding cookies. 14. Be careful which third-party libraries, CDNs and plugins you use They might be simply outdated, opening a wide variety of security holes, or they might be malicious – giving access to the shady library’s creator to your server. 15. Bots are everywhere Take care of malicious bots not by banning their IP but by enhancing CAPTCHA, adding hidden form fields that users would not fill, and requiring JavaScript or cookies enabled to submit a form. 16. Use HTTP only cookies This would reduce the impact of some other attacks – such as XSS 17. Hashing Hash your passwords and try to avoid md5 or sha-1 algorithms (https://community.qualys.com/blogs/securitylabs/2014/09/09/sha1-deprecation-what-you-need-to-know, hash - Why does some popular software still use md5? - Information Security Stack Exchange ). Use salts to prevent attacks with rainbow tables. 18. XSS Always escape input unless you really, really trust the source (admin panel). You can either remove tags or display them as entities depending on your needs. | PHP: strip_tags($input, $allowedTags); htmlspecialchars($input, ENT_QUOTES); htmlentities($input); | 19. SQL Injection Use prepared statements or do not perform a query which is not hardcoded without sanitizing it (PHP: PDO class or sanitize with mysqli_real_escape_string($conn, $str) if using mysqli. Do not use mysql_*). Conclusion This was the last part of the Website Hacking series. We have introduced some new vulnerabilities and briefly discussed them and have summarized our points for everything that we have talked about so far. We hope that now you will feel more confident when deploying your web apps by putting these strategies in use. Source
×
×
  • Create New...