Common Web development vulnerability Solutions

Source: Internet
Author: User
Tags xml attribute

Most of my daily work is to develop Web projects. Because it is generally used to develop internal business systems, security is generally not very important, basically it is the Intranet system, generally, it is rarely attacked, but sometimes some system platforms need to be used over the Internet. In this case, the security requirements of various aspects are relatively high, therefore, it is often delivered to some third-party organizations dedicated to security testing for testing, and then repaired based on the feedback. If you do not know enough about some security vulnerabilities, then the feedback results are often cruel, forcing you to fix and improve in many details. Based on some third-party security testing results of my project and my solutions for fixing these vulnerabilities, I will introduce some of my experience in this area and hope to help you.
Basically, the websites that participate in the security test (penetration test) may have the following vulnerabilities: SQL Injection Vulnerability, cross-site scripting vulnerability, logon to the background management page, IIS short file/Folder Vulnerability, and system sensitive information leakage.
1Test steps and contentThese security tests are generally conducted by collecting data first, then performing penetration tests to obtain sensitive data from websites or systems, so as to control or damage the system.
The first step is to collect information, such as IP addresses, DNS records, software version information, and IP segments. The following methods can be used:
1) obtain basic network information;
2) Ping the target network to obtain information such as the IP address and TTL;
3) results of Tcptraceroute and Traceroute;
4) Whois result;
5) Netcraft obtains the possible domain name, Web and server information of the target;
6) Curl obtains basic information about the target Web;
7) Nmap scans the website port and determines the operating system type;
8) search engines such as Google, Yahoo, and Baidu can obtain target information;
9) FWtester, Hping3 and other tools for firewall rule detection;
10) others.
Step 2: Perform penetration testing to further obtain sensitive website data based on the data obtained above. If this stage is successful, you may obtain normal permissions. The following methods are used:
1) regular vulnerability scanning and inspection using commercial software;
2) vulnerability scanning using commercial or free scanning tools such as ISS and Nessus;
3) Use SolarWinds to search and discover network devices;
4) scan common Web vulnerabilities using software such as Nikto and Webinspect;
5) use commercial software such as AppDetectiv to scan and analyze databases;
6) Analyze Web and database applications;
7) use tools such as WebProxy, SPIKEProxy, Webscarab, ParosProxy, and Absinthe for analysis;
8) Capture packets with Ethereal to assist in analysis;
9) Use Webscan and Fuzzer for SQL injection and preliminary analysis of XSS vulnerabilities;
10) manually detect SQL injection and XSS vulnerabilities;
11) use OSS-like tools to analyze databases;
12) Attacks Based on General devices, databases, operating systems and applications. various public and private Buffer Overflow program codes are used, and exploitation programs such as MetasploitFramework are also used.
13) Application-based attacks. Attacks are initiated based on vulnerabilities in Web, database, or network applications with a specific B/S or C/S structure.
14) password cracking technology. Tools such as X-Scan, Brutus, Hydra, and qingxue can be used for password cracking.
Step 3 is to escalate normal permissions to administrator permissions to gain full control over the system. If time permits, re-proceed from the first phase if necessary. Method used
1) password sniffing and key record. Software, such as sniffing, keylogging, and Trojans, has simple functions, but must not be detected by antivirus software. Therefore, it is generally necessary to develop or modify the software on its own.
2) password cracking. There are many well-known password cracking software, such as L0phtCrack, John the Ripper, And Cain.
The above are their testing steps, but we don't have to pay attention to these procedural things. We may pay more attention to their feedback, this may cause many security vulnerabilities to be fixed.
2,SQLEmergence and repair of Injection Vulnerabilities1) SQL Injection definition:
SQL injection attacks are one of the common means for hackers to attack databases. With the development of B/S application development, more and more programmers are writing applications using this mode. However, due to the varying levels and experience of programmers, a considerable number of programmers did not judge the legitimacy of user input data when writing code, posing a security risk to the application. You can submit a piece of database query code and obtain the desired data based on the results returned by the program. This is called SQL Injection, that is, SQL Injection.
Sometimes, SQL injection can be performed in address parameter input or control input. For example, if you add the "Number" after the link, the page reports an error and exposes the physical path of the website. In many cases, it is very common. Of course, if you disable the Web. config's mermerrors may not be seen.

In addition, SQL injection is a common attack. Therefore, if the page parameters are converted or not processed, data is directly transferred to the SQL statement for execution, then sensitive information may be exposed to the other party. For example, the following two pages may be injected.
① HTTP: // xxx. xxx. xxx/abc. asp? P = YY and (select top 1 name from TestD... type = 'U' and status> 0)> 0 to get the name of the table created by the first user and compare it with an integer. asp is abnormal, but the table name can be found in the exception. If the table name is xyz
② HTTP: // xxx. xxx. xxx/abc. asp? P = YY and (select top 1 name from TestDB. dbo. sysobjects &... tatus> 0 and name not in ('xyz')> 0 to get the name of the table created by the second user. Similarly, you can get the names of all created tables.
To prevent execution of dangerous SQL statements, strict conversions may be required. For example, if an integer is used, it must be converted to an integer and then operated, this can avoid some potential risks. In addition, the constructed SQL statements must be filtered by SQL Injection statements, such as my framework (Winform development framework and Web development framework) it has built-in cleaning of these harmful statements and symbols, because the filter is performed on the base class, therefore, the common attacks can be avoided even if the subclass is not concerned.

///


/// Verify whether the injection code exists (Condition Statement)
///
///
Public bool HasInjectionData (string inputData)
{
If (string. IsNullOrEmpty (inputData ))
Return false;
 
// Define Malicious character set combination
// Verify whether inputData contains a malicious set
If (Regex. IsMatch (inputData. ToLower (), GetRegexString ()))
{
Return true;
}
Else
{
Return false;
}
}
 
///
/// Obtain the Regular Expression
///
///
Private static string GetRegexString ()
{
// Construct key characters for SQL Injection
String [] strBadChar =
{
// "Select \ s ",
// "From \ s ",
"Insert \ s ",
"Delete \ s ",
"Update \ s ",
"Drop \ s ",
"Truncate \ s ",
"Exec \ s ",
"Count \\(",
"Declare \ s ",
"Asc \\(",
"Mid \\(",
"Char \\(",
"Net user ",
"Xp_cmdshell ",
"/Add \ s ",
"Exec master. dbo. xp_mongoshell ",
"Net localgroup administrators"
};
 
// Construct a regular expression
String str_Regex = ".*(";
For (int I = 0; I <strBadChar. Length-1; I ++)
{
Str_Regex + = strBadChar [I] + "| ";
}
Str_Regex + = strBadChar [strBadChar. Length-1] + ").*";
 
Return str_Regex;
}

The preceding statement is used to identify common SQL attack characters. In the base class of database operations, you only need to identify them. The following is a function used to search for database records based on the condition statements.

///
/// Query the database based on the condition and return the object set
///
/// Query Conditions
/// A custom sorting statement, such as Order By Name Desc. If not specified, the default sorting statement is used.
/// Parameter List
/// Set of specified objects
Public virtual List Find (string condition, string orderBy, IDbDataParameter [] paramList)
{
If (HasInjectionData (condition ))
{
LogTextHelper. Error (string. Format ("malicious SQL Injection data detected, {0}", condition ));
Throw new Exception ("detecting malicious SQL Injection data ");
}
 
...........................
}

The above is only one aspect of preventing SQL attacks. In addition, we insist on assigning values through parameterization, which greatly reduces the possibility of being attacked by SQL injection.
Database db = CreateDatabase ();
DbCommand command = db. GetSqlStringCommand (SQL );
Command. Parameters. AddRange (param );
 
3 , Cross-site scripting vulnerability occurrence and repairXSS code attacks are also common script injection attacks. For example, on the following interface, many input boxes can enter content at will, especially in some text editing boxes, such as <script> Alert (' This is a page pop-up warning ');</Script> if there are many such content on some home pages that are not processed, the page will pop up continuously. What's more, execute an infinite loop Script Function in it until the page consumes resources. Such attacks are common. If we release programs on the Internet or on dangerous networks, generally, you need to fix these problems.

XSS code attacks may also steal or manipulate customer sessions and cookies, which may be used to mimic legitimate users, so that hackers can view or change user records and execute transactions as such users.
[Recommended measures]
Clear user input and filter out JavaScript code. We recommend that you filter out the following characters:
[1] <> (angle brackets)
[2] "(quotation marks)
[3] '(single quotes)
[4] % (percent sign)
[5]; (semicolon)
[6] () (parentheses)
[7] & (& Symbol)
[8] + (plus sign)
To avoid the above XSS code attacks, the solution is to use HttpUitility's HtmlEncode or the AntiXSSLibrary released by Microsoft for processing, which is safer.
The anti-Cross-Site Scripting Library (AntiXSSLibrary) is an encoding library designed to help developers protect their Web-based applications from XSS attacks.
Encoding Method Use Cases Example
HtmlEncode (String) Untrusted HTML code. Click Here [untrusted input]
HtmlAttributeEncode (String)
 
Untrusted HTML attributes
JavaScriptEncode (String) Untrusted input used in JavaScript <Script type = "text/javascript">
...
[Untrusted input]
...
</Script>
UrlEncode (String)
 
Untrusted URL Cnblogs.com
VisualBasicScriptEncode (String) Untrusted input used in VBScript <Script type = "text/vbscript" language = "vbscript">
...
[Untrusted input]
...
</Script>
XmlEncode (String) Untrusted input for XML output [Untrusted input]
XmlAttributeEncode (String)
 
Untrusted input is used as XML Attribute Some Text
Protected void Page_Load (object sender, EventArgs e)
{
This. lblName. Text = Encoder. HtmlEncode ("<script> alert ('OK'); </script> ");
}
For example, if the above content is assigned to a Lable control, no dialog box operation will appear.

However, even if we set escape characters when displaying them, what should we do if we want to restrict them? We also use the HtmlSanitizationLibrary library Sanitizer. GetSafeHtmlFragment in the AntiXSSLibrary.
Protected void btnPost_Click (object sender, EventArgs e)
{
This. lblName. Text = Sanitizer. GetSafeHtmlFragment (txtName. Text );
}
In this way, the content of the special script will be automatically filtered out, instead of recorded, so as to achieve our purpose.

4 , IIS Short File / Appearance and repair of folder Vulnerabilities
By guessing, some important webpage file addresses may be obtained. For example, the UserList. aspx and MenuList. aspx files may exist under/Pages/Security.
[Recommended measures]
1) Disable "~" in the url Or its Unicode encoding.
2) Disable windows 8.3 format.
You can refer to the following practices for repair, or contact the relevant O & M department for troubleshooting.
Http://sebug.net/vuldb/ssvid-60252
Http://webscan.360.cn/vul/view/vulid/1020
Http://www.bitscn.com/network/security/200607/36285.html
5 , System sensitive information leakage and repairIf a page inherits a general page without Session judgment, attackers may obtain the page address and obtain important data such as the user name.
This method is generally avoided for some pages that can be accessed only after logon. Session judgment is required and may be easily missed. For example, in the Web framework, a BasePage is inherited, And the BasePage performs a logon judgment on the page.
Public partial class UserList: BasePage
{
Protected void Page_Load (object sender, EventArgs e)
{
...............

///
/// The BasePage is integrated with the basic permission abstract class FPage, while the other pages are integrated with the BasePage
///
Public class BasePage: FPage
{
///
/// Default constructor
///
Public BasePage ()
{
This. IsFunctionControl = true; // permission authentication is enabled on the default page.
}
 
///
/// Check whether the user logs on
///
Private void CheckLogin ()
{
If (string. IsNullOrEmpty (Permission. Identity ))
{
String url = string. Format ("{0}/Pages/CommonPage/Login. aspx? UserRequest = {1 }",
Request. ApplicationPath. TrimEnd ('/'), HttpUtility. UrlEncode (Request. Url. ToString ()));
Response. Redirect (url );
}
}
 
///
/// Override the HasFunction method so that the permission class can determine whether it has the permission for a certain function.
///
///
///
Protected override bool HasFunction (string functionId)
{
CheckLogin ();
 
Bool breturn = false;
Try
{
Breturn = Permission. HasFunction (functionId );
}
Catch (Exception)
{
Helper. Alerts (this, "An error occurred while calling the HasFunction function of the permission system BasePage ");
}
Return breturn;
}
 
Protected override void OnInit (EventArgs e)
{
Response. Cache. SetNoStore (); // clear the Cache
Base. OnInit (e );
 
CheckLogin ();
}

Otherwise, the website may be attacked, and page data may be found through the packet capture software to obtain important user names or related information.
It is worth noting that, in general, this is not a very secure network, it is better to enter a more complex password (mandatory ), for example, a single password cannot be a digital password or a single character, and a bit more is required for the number of digits, because many people enter passwords such as 12345678,123456 and 123, which can be easily guessed and logged on to the system, cause unnecessary losses.
6 Summative suggestionsThe following suggestions are provided for the problems found above.
1) configure a firewall at the server and network interfaces to block external users from scanning and detecting the server.
2) restrict the website background access permissions, for example, prohibit public IP addresses from accessing the background, and prohibit waiters from using weak passwords.
3) perform a comprehensive security check or filter on user input data, especially check whether SQL or XSS special characters are contained. These checks or filters must be completed on the server side.
4) disable the format function of windows 8.3.
5) restrict access to sensitive pages or directories.
 

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.