General approach Fortify security vulnerabilities

Some time ago the company has a security review, the requirements of each project security scans, troubleshoot and fix vulnerabilities, there are several historical projects on hand, demand for a full restoration and submit a safety report for a limited period of time, do not know how to do before bug fixes, this time using the tool scanned average every project, there are about 100 vulnerabilities. These vulnerabilities include SQL injection statements, C # backend code, XML files, as well as front-end HTML, JS aspects of the code, as some projects were old, limited time and short, big changes if the test is not in place, it is difficult to ensure not see any problem, and so did some should be treated, but these can be regarded as a means to be a summary on the following to handling of the security vulnerabilities.

The company’s vulnerability scanning is divided into two stages, the first stage is to use this tool to scan Fortify, check out the vulnerabilities repaired and the report, the second stage is APPSCAN line of code to scan Let’s say for the first how a phase out of Fortify vulnerability scanning tool handle, as the second stage, the latter did come up on.

1.SQL injection

When this type of vulnerability is mainly done for a number of dynamic SQL statements stitching, illegal passing a special character, such as SELECT id, name FROM User WHERE deparment = 1000 and {ConditionalExpression} {ConditionalExpression} which wanted to do as a parameter in the query page splicing some dynamic conditions, which would bring the risk of SQL injection, if someone {ConditionalExpression} by means of the value of the parameter into it so 1 = 1 oR 2> 1 or if 1 = 1; drop table deparment that it is a major safety accident.

Upload SQL injection prevention can generally be from several aspects:

1. The connection permission system appropriate permissions assigned account database, general operating system account database operations, do not produce a change of the number of dispensing structure, such as database CREATE TABLE, DROP XXXX etc.

2. For complex queries using stored procedures, pre-defined parameters in SQL statements stored procedure splicing

3. For example to make use of pass parameter values ​​SqlParmater making Specification

4. Do special keyword to the SQL statement or parameter value filter

5. The MyBATIS, Hibernate, other support SQL MAPPER ORM framework

6. Avoid dynamic SQL statement alternative splicing or dynamic LINQ

MyBatis ORM framework Most of the company’s projects have to do with Mapper mapping, vulnerability scanning SQL injection this regard Fortunately, there is no basic stitching SQL in the code, but one thing has several individual code that is used to read and write ADO.NET database, wherein the instantiated place object scanned connectString Connection without making encryption process. Behind the switch to the project in the existing database operation to operate the library and reported no loopholes.

2.Path Manipulation path tampering

The most frequent is the Path Manipulation path tamper security vulnerabilities in the screening and treatment process, the hands of several projects in which there are two projects used to generate static pages, involves a lot of file operations, if not treated will reported a lot of loopholes. First of all is that my understanding of the Path Manipulation Vulnerability: by the code of the operating system files if you do not set up a whitelist, blacklist checks and filters is a safety hazard, such as a common method used in the, System.IO .File.Delete file (path) .NET provided to delete this method, path is passed through parameters, if not checked, in some places the call, was changed to a critical file system, you may direct the system to crash, this is a big thing.

Remedy of such vulnerabilities general practice is as follows:

1. Set whitelist or blacklist

Common practice is to set the white list, the risk of non-enumerable, we can consider what is safe, including them in the list of allowed operations

2. Set the folder security permissions

Only read and write permissions to the file folder settings allow operation. The entire site must not shut folder permissions writable

.Net sample code processing path Path Manipulation tampering vulnerability:

 private static  Dictionary<string,string> CreateFortifyDictionary()
            Dictionary<string, string> fortifyDictionary = new Dictionary<string, string>();

            for(char c1 = 'a'; c1 <= 'z'; c1++)
                fortifyDictionary.Add(c1.ToString(), c1.ToString());

            for (char c2 = 'A'; c2 <= 'Z'; c2++)
                fortifyDictionary.Add(c2.ToString(), c2.ToString());

            for (int c3 = 0; c3 < 10; c3++)
                fortifyDictionary.Add(c3.ToString(), c3.ToString());

            fortifyDictionary.Add(".", ".");
            fortifyDictionary.Add(":", ":");
            fortifyDictionary.Add("/", "/");            
            fortifyDictionary.Add(Separator, Separator);

            return fortifyDictionary;

        public static string SecurityPathFilter(string path)
            path = path.ToLower();
            path = path.Replace("c:"+ Separator + "windows", "");
            path = path.Replace("c:" + Separator + "program files", "");
            path = path.Replace("c:" + Separator + "", "");

            char[] characters = path.ToCharArray();
            StringBuilder resultStringBuilder = new StringBuilder();
            var dictionary = CreateFortifyDictionary();
            foreach (Char character in characters)
                string value = string.Empty;
                if (dictionary.TryGetValue(character.ToString(), out value))
            return resultStringBuilder.ToString();

3.Cross-site Scripting: Persistent XSS

XSS is defined references: transfer to the Web browser malicious content typically takes the form of JavaScript code fragments, but may also contain some code HTML, Flash or any other browser can be executed. The XSS-based attacks tricks, almost endless, but usually they will contain private data transmission to the attacker (such as Cookie or other session information). Under the control of the attacker, redirecting the victim to malicious web content; or the use of vulnerable sites on the user’s machine perform other malicious actions. Generally it means that during the reception of a page due to the parameter, no calibration parameters, there may be loopholes executable code parameter.

Approach generally escaped the parameters cited System.Web.HttpUtility.DLL overweight .NET assemblies, call the following method:

string str= System.Web.HttpUtility.HtmlEncode(html)

The need to reverse one use in decoding meaning:

string html= System.Web.HttpUtility.HtmlDecode(str);

4.System Information Leak information disclosure system

As the name suggests is the internal information system of the leak, and a security risk to the system, what does that mean? Here is the excerpt passage:

When the system debug information or data via the network to make the program flow sockets or remote machine, external leakage of information occurs. External information disclosure of which would be exposed to the operating system, the full path name, user name or an existing profile location-specific data, so that the attacker can take advantage of its internal information leakage ratio (harder for an attacker to access) and more serious

Debugging information is abnormal and our system captures information can not be exposed, such as the code directly Fortify will detect vulnerabilities.

 catch(Exception ex)

Or we can change this to solve

catch(Exception ex)

System exception:

"+ex.Message,ex); }

Error message should not be directly thrown to the terminal, handed over the log to record.

The idea about the general system information leakage measures in this regard:

Close Debug remote debugging mode when the publishing site 1.IIS

2. Define error page specification error message

3. Custom Client class exception information, an internal exception digest information, logs, filtered and treated thrown exception information may allow the client to

Refer to the following Example:

  <compilation debug="false" />   
    <customErrors defaultRedirect="GenericError.htm"
       mode="RemoteOnly" xdt:Transform="Replace">
      <error statusCode="500" redirect="InternalError.htm"/>
      <error statusCode="403" redirect="NoAccess.htm" />
      <error statusCode="404" redirect="FileNotFound.htm" />

Wherein the mode as follows:

1. On representation see the custom error messages in local and remote users will be. 2. Off to disable custom error messages, local and remote users will see a detailed error message. 3. RemoteOnly local user will see the detailed error information, and remote users will see the custom error messages

string message = "";
catch(WTSError ee)
     message = ee.OutMessage;

System exception:

" + ee.Message, ee); } catch(Exception ex) { message = "

System abnormalities, error type is unknown

"; //System.Console.WriteLine(ex.Message); logger.Logger("

System exception:

"+ex.Message,ex); }

5. Non-Serializable Object Stored objects written in the Session Session not be serialized

The security report also described the process of a lot of these vulnerabilities, writing object Session is unclear why the session should be serialized “objects stored in the session is the best serialization, otherwise easily lead to conversion class when an exception occurs, “this is what I find most short answer, as I understand it probably is, Session objects in memory and automatically read when the serialization and de-serialization, non-general for non-similar data Int, String, etc. complex types and data structures stored objects, attributes and state read data conversion error-prone.

For handling such issues may refer to the following:

For example, the following piece of code will be reported vulnerabilities:

Session["UserToken"] = "sessionObjectValue";

Session can customize a storage object marked sequence to be instantiated, and implement the ISerializable interface

    public class SessionObject : ISerializable
        private string data;

        public string Data
            get { return data; }
            set { data = value; }

        public SessionObject(string data)
   = data;

        public void GetObjectData(SerializationInfo info, StreamingContext context)
            info.AddValue("Data", data);
            Type basetype = this.GetType().BaseType;
            MemberInfo[] mi = FormatterServices.GetSerializableMembers(basetype, context);
            for (int i = 0; i < mi.Length; i++)

Since the value of the same name can not be added AddValue, in order to avoid subclass variable name and the variable name the same base class, the base class name with a variable sequence of base class name

info.AddValue(basetype.FullName + "+" + mi[i].Name, ((FieldInfo)mi[i]).GetValue(this)); } } }

Session then written so that when writing and reading

1 //Session["UserToken"] = new SessionObject("sessionObjectValue");
2  Session["UserToken"] = new SessionObject("sessionObjectValue");
4  //string sessionObjectValue = Session["UserToken"].ToString();
5  string sessionObjectValue = ((SessionObject)Session["UserToken"]).Data;

6.File Separator File.separator

Also appeared inevitable description of these vulnerabilities, usually in the Window environment, will not be a problem to bring these vulnerabilities, if your system can be deployed on Linux or Unix environment Bug may have appeared, such the problem is not the same finger in the path of the split symbol file under a different operating system environments. If such a path: “C: \ tmp \ test.txt” Windows environment is: “C: \ tmp \ test.txt” Linux environment is: “/ tmp / test.txt” In order to take into account the different operating system environments are recommended System such combinations of the above objects .IO.Path.DirectorySeparatorChar path:

"C:" + System.IO.Path.DirectorySeparatorChar + "tmp" + System.IO.Path.DirectorySeparatorChar + "test.txt"

Newline There are similar: the windows is \ other systems r \ n Linux and the like are \ n System.Environment.NewLine used in .NET objects.

7.Insecure Randomness secure random number

Cited explanation on the network:

Insecure random number: PC is a deterministic machine, it is impossible to produce true randomness. Pseudo-random number generator (pRNG) approximates random algorithm, starts with a seed subsequent values ​​are calculated. PRNG includes two types: statistical and cryptographic PRNG PRNG. Statistical PRNG can provide useful statistics, but its output is easy to predict, and therefore easy to copy data stream. Where security depends on the unpredictability of the generated values, then this type does not apply. Cryptography PRNG by generating output that is less predictable to address this issue. In order to make more secure the encrypted value, it must allow an attacker can not, or will it highly unlikely that distinguish the true random number. In general, if a PRNG algorithm declared not encrypted, then it is probably a statistical PRNG, should not require a higher security environments, with which its use may cause serious vulnerabilities (such as easy-to-guess passwords, encryption keys and predictable, session hijacking attacks and DNS spoofing).

We generally use the random function is not truly random, may have certain speculative, may bring some security issues, to tell the truth hard to deal with such issues related to cryptography. If you are interested in, then can look for information in this regard can also take a look at this article, personally I think that the general system can use the GUID scheme.

These are the Fortify security vulnerability scanning encountered in several types, basically have been solved by the methods described above. Remember which also encountered a computer to obtain domain account to call C ++ class library methods unsafe code execution vulnerability, but fortunately do not find another way to call C ++ class library to replace, if not ways to avoid a C ++ class library to call, if Park Friends can report such vulnerabilities do not know what a good way to deal with, there is hope that the experience of hesitate to let us know.

Address and reference cited herein is as follows:

1. Fortify vulnerability scanning solutions

2. Fortify tool for scanning a settlement of several major vulnerabilities summary –1

3. open source Math.NET basic mathematics library use (14) C # generates secure random number

Leave a Reply