Embodiment
Below in conjunction with accompanying drawing and embodiments of the invention method of the present invention is described in further detail.
Basic thought of the present invention is: at first read the tested program source code file and carry out pre-service, resolve the security breaches state machine description document of software security flaw pattern correspondence; Again the tested program code is carried out lexical analysis and grammatical analysis, construct the abstract syntax tree of tested program; According to abstract syntax tree, structure control flow graph generates symbol table; Carry out the calculating and the renewal of the interval collection of variable-value then, and according to symbol table, tested program is carried out the function calling relationship analysis, the generating function call graph is set up the ud/du chain again; At last, by setting up the security breaches state machine and calling the ud/du chain, the control flow graph is traveled through, the status change of each node security Vuln Status machine on the calculation control flow graph, if the security breaches state machine enters defect state, then the corresponding checkpoint (IP, Inspective Point) of report generates the software security flaw test report.
Fig. 1 is the detection method schematic flow sheet that the present invention is based on safety bug defect mode; As shown in Figure 1, this method comprises the steps:
Step 101: the security breaches state machine description document that reads tested program source code file and software security flaw pattern correspondence, described tested program is carried out pre-service and resolved the security breaches state machine description document, and tested program carried out lexical analysis and grammatical analysis, generate the abstract syntax tree of tested program.
Here, so-called state machine is meant a behavior, is used to specify an object and in its whole life incident is responded and the various states of priority experience, shows response and action simultaneously.To be called the security breaches state machine corresponding to the state machine of security breaches pattern among the present invention, the corresponding class security breaches state machine of described every kind of security breaches pattern.
The described pre-service that tested program is carried out be meant to tested program to carry out macro substitution before testing, file comprises and conditional compilation.
Described the security breaches state machine description document being resolved, is to utilize analysis program that described security breaches state machine description document is resolved to the internal storage data structure that security breaches pattern analysis engine can be discerned in the subsequent treatment.
Described lexical analysis is that tested program is converted to the mark stream that can carry out grammatical analysis.
Described abstract syntax tree is the software translating technical term, is meant that compiler resolves program source code, is converted to the data structure of being convenient to Computer Processing, because this data structure is generally tree structure, therefore is called abstract syntax tree.Abstract syntax tree described in the inventive method is made up of dissimilar nodes, all nodes are all supported unified visitor's pattern interface, so just can carry out further multi-form processing, traversal visit and output to abstract syntax tree by visitor's pattern easily.
Step 102:, generate the control flow graph of reflection tested program control structure and/or, create the symbol table of tested program according to the abstract syntax tree of being constructed according to the abstract syntax tree of being constructed.
Here, described control flow graph can obtain by adopting visitor's pattern traversal abstract syntax tree, and its method is: on the basis of traversal abstract syntax tree, generate the visitor by a control flow graph and realize.The way that described visitor adopts recurrence to descend generates the control flow graph, promptly represent in visitor's function of statement node to add the code that flow graph is controlled in corresponding generation in each abstract syntax tree.Visitor's function of the corresponding abstract syntax tree node of each control statement is responsible for generating the part control flow graph of this control statement, in the process of traversal with these parts control flow graphs conjunctive tissue control flow graph of getting up and just having constituted tested program one by one.Because the control flow graph and the abstract syntax tree of tested program are corresponding, the statement node of the corresponding abstract syntax tree of each node of control flow graph, can visit abstract syntax tree by the control flow graph, same, also can have access to the respective nodes of control flow graph very easily from the statement node of abstract syntax tree.In addition, a statement in the corresponding tested program of each node of control flow graph.
The symbol table of described tested program is used to write down type, action scope and the binding information of tested program identifier, and tested program is carried out semantic analysis.The generation of described symbol table is similar with the generation of control flow graph, also is by adopting visitor's pattern traversal abstract syntax tree to obtain, and just representing what add in visitor's function of statement node in each abstract syntax tree is the code of corresponding generation symbol table.
Described symbol table with identifier and its type and in program residing position shine upon, when handling the statement of type, variable and function, these identifiers can obtain explaining in symbol table.When finding to have identifier to be used, these identifiers can find in symbol table.
Step 103: according to control flow graph that is generated and the symbol table of being created, along tested program control stream forward traversal control flow graph; Adopt the method for recursive call, carry out the calculating and the renewal of the interval collection of variable-value; And the symbol table according to generating carries out the function calling relationship analysis to tested program, and the generating function call graph is set up the ud/du chain simultaneously.
Here the interval arithmetic of being adopted is expanded basic interval arithmetic, the interval arithmetic of set operation and real number, Boolean variable, handle variable and array variable numerous types of data between supporting area, can carry out the interval to declarative statement, assignment statement and conditional statement calculates, to the control flow graph traversal time, can probably calculate the span of tested program variable by interval arithmetic, this information be used for follow-up based on defect mode test and help the unreachable path of identification.
Describedly tested program is carried out the function calling relationship analysis comprise: the sequencing of position, call relation function between and the function call of analytic function in source code and number of times etc.
Described ud/du chain is use-def and def-use chain, is a kind of data-flow analysis method.Here, variable-definition is appearred being called in the assignment of variable, other variable occurs the variable except definition being called and use; The use relation of definition can be stored in the use-def chain, and promptly for each use of each variable x, the use-def tabulation of x has been preserved all and can have been arrived the definition of the x of current use; The def-use chain has then been preserved all possible use tabulation of current definition.The purpose of described ud/du chain is in order to call for security breaches detected state machine, to be used for the assignment of fast query variable and the use of variable, similarly also having def-undef and undef-def chain also to have close effect.
Step 104: setting up security breaches detected state machine, is unit with the function, according to function calling relationship figure the control flow graph is traveled through, and according to the ud/du chain of described foundation program code is carried out the software vulnerability test, and generate the software vulnerability test report.
Here, described the tested program code is tested, with the function is unit, according to function calling relationship figure the control flow graph is traveled through, and according in the security breaches state machine description document about security breaches state, status change and the description that causes the action of status change, the status change of each node security Vuln Status machine on the calculation control flow graph, if the security breaches state machine enters the software defect state, the checkpoint of then report correspondence.
Here, be to utilize predefined security breaches pattern analysis engine that the control flow graph is traveled through, realize calculating, report check point IP to the status change of security breaches state machine.Checkpoint IP has defined the definition code line of the variable that is associated with safety bug defect, the code line of security breaches generation and the type of leak.
For each node on the control flow graph, its corresponding actions changes the state of security breaches state machine, if there is the security breaches state machine to enter error status (Error), then there are security breaches in report, adds up rate of failing to report, rate of false alarm, accuracy rate etc. according to corresponding index calculating method after end of test (EOT).
Below in conjunction with Java, C/C++ programming language is example, and classification, definition and the solution etc. of software security flaw pattern of the present invention are described respectively for example:
One, with the Java language be example, the defect mode kind that this language exists mainly comprises:
Category-A, not verified input; Comprising following several types:
A1, system function expose: the function of following these high level of securitys relates to the operation to system variable or Java Virtual Machine (JVM, Java Virtual Machine).If malicious attacker is revised systematic parameter or directly JVM is operated, will cause system to carry out unsafe code, perhaps refuse problems such as attack.Described function is exemplified below:
For example: the fault title: not verified system command
public?void?checkHost(ServletRequest?req)
throws?IOException{
String?hostName=req.getParameter("userHostName");
String?command=″nslookup″′+hostName+″″′;
Process?proc=Runtime.getRuntime().exec(command);
//parse?results?of?command
}
The analysis of causes: in application program, carry out the establishment of process or carry out to relate to safety problem usually by external command.The user imports any part as the command string that is performed, and all will produce serious threat.The assailant can inject extra order, thereby and on apps server, carry out and cause process or order to be injected into, this execution ability of order arbitrarily may cause denial of service, data corruption, data security to be destroyed and other risks.
A2, system resource expose: following these functions, relate to operation to the system file resource, and when not verified input,, when being searched or creating, might cause system resource to expose as filename or file path.Described function is exemplified below:
For example, fault title: not verified filename; When the user data that is not verified is used as the part of the filename of creating or revising.
protected?void?doPost(HttpServletRequest?req,HttpServletResponse?resp)
throws?ServletException,IOException{
String?name=req.getParameter("userName");
File?userDir=new?File("userFiles",name);
File?profile=new?File(userDir,"profile");
if(!profile.exists()){
FileOutputStream?stream=new?FileOutputStream(profile);
createFileWithSensitiveInformation(stream);
stream.close();
}
}
The analysis of causes: this situation is injected with data and is combined, just can be used as data are injected in any file, as/etc/passwd.And independent file injects and can be used for creating themselves file of naming or catalogue by victim, so that use in the attack afterwards.For example, the assailant can the mandatory use program create the file that has sensitive information in any one position that can read.
Again for example, fault title: not verified temporary file name or temp directory path; When the user of invalidated imports as the temporary file name, cause unallowed file of system creation.This operation can allow the IOException that dishes out of system unusual, causes occurring being similar to the attack phenomenon of Dos (Denial of Service attack), makes directly that perhaps system file is exposed to malicious attacker.See following program code:
protected?void?doPost(HttpServletRequest?req,HttpServletResponse?resp)
throws?ServletException,IOException{
String?name=req.getParameter("USERNAME");//use?user?Name?as?uniq?prefix
File?file=File.createTempFile(name,".tmp");
dumpSensitiveInfoAndRunSomeApp(file);
file.delete();
}
Again for example, fault title: not verified file path; This class mistake occurs in to work as does not have the data of checking or pollution to be used directly as the file of the method relevant with system or file read-write or the title in path.The assailant can use file separator and relevant pathname to read the file that they can not visit those.See following program code:
public?String?get?UserProfile(ServletRequest?req)
throws?IOException{ //Source?of?data?from?HTTP?request?in?servlet
String?userName=req.getParameter("userName");
//Profile?dir?is?hardcoded?in?the?application?path?relative?to?serlets?installation?dir
String?profile=System.getProperty("PROFILES_DIR")+File.separator+userName;
BufferedReader?reader=new?BufferedReader(new?FileReader(profile));
String?line=reader.readLine();
reader.close();
return?line;
}
The analysis of causes: usually, on host computer system, use application access relevant with security of system with the establishment file.If user input is not checked during as file in the executable program or path string a part of, will there be security threat.At this moment, the assailant can carry out the data of write operation or visit host computer system by operation file or path to data.As, assailant can operate a filename visit come from main frame /the etc/passwd file.Usually, the safety that may injure the file system on the host server is injected in the path.
A3, database information expose.This class mistake mainly is meant, not verified input is as the parameter of data base querying or directly as query statement, will cause SQL (Structured Query Language (SQL)) injection attacks, the consequence that is caused, comprise the data that expose in the database to the assailant, it is medium that perhaps unsafe malicious data has been stored in database.
For example, fault title: not verified SQL information; Not verified data directly are used as SQL query, cause data message to expose.See following program code:
public?ResultSet?getUserData(ServletRequest?req,
Connection?con)throws?SQLException{
//Source?of?data?from?HTTP?request?in?servlet
String?accountNumber=req.getParameter("accountNumber");
//Use?of?string?directly?in?SQL?statement
String?query="SELECT*FROM?user_data?WHERE?userid=″′+accountNumber+""′;
Statement?statement=con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONL?Y);
ResultSet?results=statement.executeQuery(query);
return?results;
}
Analyze: the data tape that SQL is injected in the database is come risk.Because the content invalidated of user's input promptly is used in the SQL statement, the assailant can inject any SQL statement that it wants to carry out.This comprises the operations such as deletion, renewal and establishment to data.Simultaneously, by utilizing these defectives, also can pick up the sensitive data in the database.If order is used to verify that this will cause the not generation of authentication-access.
Again for example, fault title: database stores information exposes; Stored unsafe content in database, this class mistake occurs in unverified user data is inserted in the SQL database inquiry.See following program code:
public?void?setUserLastName(ServletRequest?req,onnection?con)throws?SQLException{
//Source?of?datafrom?HTTP?request?in?servlet
String?lastName=req.getParameter("lastName");
int?userId=Integer.parseInt(req.getParameter("userId"));
//Using?prepared?statements,even?iflast?name?contains′
//like"O′Conner"it?will?be?ok!
//Safe?for?SQL?injections?here
String?query="UPDATE?userData?INTO?lastName=?WHERE
userid=?";
PreparedStatement?statement=con.prepareStatement(query);
statement.setString(1,lastName);
statement.setInt(2,userId);
statement.executeUpdate();
}
Analyze: the data of some malice directly have been updated to the database the inside.
A4, user profile revise and inject: this class mistake is meant that user profile has been exposed to the assailant by unsafe, perhaps assailant's malicious modification user profile.The consequence that causes comprises information leakage, denial of service etc.
Fault title: attribute modification and injection among the Session.This class mistake may occur in ought not authentic storage of subscriber data in half storage of trusting, as the Session attribute.See following program code for details:
protected?void?doPost(HttpServletRequest?req,HttpServletResponse?resp)
throws?ServletException,IOException{
String?name=req.getParameter("userName");
HttpSession?sess=req.getSession();
sess.setAttribute("user",name);
createPage(resp,sess);
}
private?void?createPage(HttpServletResponse?resp,HttpSession?sess)throws?IOException{
resp.getOutputStream().println("Hello"+sess.getAttribute("user"));
}
Analyze: the information among the Session is from unsafe input.Be kept at the information among the Session simultaneously, in system, think safe again.Like this, when unsafe content is taken as security information, cause a series of attacks such as information leakage.
Again for example, fault title: not verified email information; This class mistake occurs in other parts that the user's input that is not verified is used as email address information or email.See following program code for details:
protected?void?doPost(HttpServletRequest?req,HttpServletResponse?res)throws?ServletException,
IOException{
try{ //some?base?work
message.setFrom(new?InternetAddress("admin@my.company.com"));
final?String?email=req.getParameter("email");
Address?addr=new?InternetAddress(email);
message.setRecipient(Message.RecipientType.TO,addr);
message.setSubject("Hello?JavaMail");message.setText("Welcome?to?JavaMail");//Send?message
Transport.send(message);
}
catch(Exception?e){
throw?new?ServletException(e);
}
}
Analyze: the E-mail address is an input domain very common in the weblication.Some the time, the E-mail address is employed program and is used for transfer mail to the user, perhaps shows addresses of items of mail in the website.This class is attacked and can be comprised, transmits the transmission spam that has the mail of malice virus or do not stop, and causes target mailbox collapse etc.
A5, other
The fault title: array indexing overflows.User's input that this class mistake occurs in when non-confirmation is used as the index of an array or passes through the index of a method as an array.See following program code:
ArrayList?myData=new?ArrayList();
boolean?lock=false;
protected?synchronized?void?doPost(HttpServletRequest?req,HttpServletResponse?resp)
throws?ServletException,IOException{
String?sind=req.getParameter("secretIndex");
final?int?index=Integer.parseInt(sind);
if(lock==true)resp.sendError(505,"Try?again");
lock=true;
String?key=(String)myData.get(index);
lock=false;
//do?somethingwith?the?key?here...
resp.getOutputStream().println("Success!"+key);
}
Analyze: if not authentic user input data is used as the index of array, perhaps by the index of method as an array, the method ArrayOutOfBounds that dishes out that can cause under attack is unusual.This may cause denial of service or utilize Obj State to create a control stream favourable to the assailant.
Again for example, fault title: the exposure of system journal; This class mistake occurs in the user who is not verified and writes information in the syslog file.
Again for example, fault title: the http head of validation value not.The http client takes place to work as this class mistake or the next value of database has not been write in the http head by method through checking.
Again for example, fault title: the JS script injects; When this class mistake occurs in when in service, the text that the external world is imported into is directly explained as script and is carried out.
Again for example, fault title: the printf format parameter is annotated.The format parameter of unchecked character string as PrintStream.printf takes place to use in this class mistake.
Category-B, abuse application programming interfaces (API) pattern.Comprising following several subtypes:
For example: the fault title: incorrect object relatively; This class mistake occurs in the class name that program is attempted two objects of comparison, goes the situation of checking whether two classes equate.See following program code:
public?void?privateMethod(Object?object1,Object?object2)
{
if(object1.getClass().getName().equals("anotherClass")){//wrong
//do?work?based?on?the?assumption?we′re?dealing?with?the?right?object
}
Analyze: when by name comparing class (class), allowed the attack of mix and match, just the assailant utilizes the malicious code class to write new code, and is linked in your program code or with two incoherent classes and is linked to together.Need not use the equals method of an object to go for class name, replacement, find first class to have the getClass method earlier, find the class of second object then by loader.
if(object1.getClass()==object2.getClass()){//correct
//do?work?based?on?the?fact?that?the?objects?are?the?of?the?same?class
}
Again for example, fault title: incorrect finalize () method; Here refer to realize that the finalize method but do not call super finalize ().Call superclass finalizer if but a superclass is realized thinking highly of having carried superclass finalizer having forgotten, superclass finalizer will be called never.This means to remove and can not carry out and cause resource leakage for the resource of superclass.
Again for example, fault title: unsafe DNS inquiry; This class mistake occurs in domain name or the IP address of too believing the dns lookup function.Because the assailant can change dns server, so too do not rely on the DNS inquiry at secure context., see following program code:
String?ip=request.getRemoteAddr();
InetAddress?addr=InetAddress.getByName(ip);
if(addr.getCanonicalHostName().endsWith("trustme.com")){
trusted=true;
}
Analyze: code attempts to inquire about to determine by DNS whether an inbound request comes from the trust main frame, if but the assailant can infect DNS buffer memory (also claiming the DNS Cache Poisoning), and they just can gain credit so.
Again for example, fault title: do not check rreturn value; Do not have the rreturn value of inspection method, thereby cause the leakage of information.
Again for example, fault title: equals () and the heavily loaded problem of hashCode (); Among class heavy duty equals () and the hashCode () one.
Again for example, fault title: mistake realizes StateHolder; The class of realization StateHolder interface has only realized among saveState () and the restoreState ().
C class, security feature defect mode.Comprising following several subtypes:
For example, fault title: hard coded cryptographic problem; This class mistake occurs in works as hard coded, when perhaps the part of hard coded is as the summary of password or encryption.See following program code:
public?static?void?main(String[]args)
throws?SQLException{
Properties?info=new?Properties();
info.setProperty("user","root");
info.setProperty("password","^6nR$%_");
DriverManager.getConnection("jdbc:mysql://localhost:3307",info);
}
Analyze: directly the record password is unsafe in source code.At first, it is readable that this allows other developers.The character string password can read from the java bytecode easily, and this makes has the user of bytecode to read.Simultaneously, if upgrade software then cannot revise password not.The hard coded character string is used as the part of summary may give the prompting of assailant about the key generation, so the assailant can attempt to push away in advance key.Not reusable summary should be imported and store to password dynamically, for example uses md5.If the aspect requires password in plain text, the password of storage encryption is in configuration file.
Again for example, fault title: null character string is as cryptographic problem; This class mistake occurs in when null character string is used in the method for accepting password or maintaining secrecy.See following program code:
public?static?void?main(String[]args)throws?SQLException{
Properties?info=new?Properties();
info.setProperty("user","root");
info.setProperty("password","");
DriverManager.getConnection(
"jdbc:mysql://localhost:3307",info);
}
Analyze: empty password can very simply be attacked system.
Again for example, fault title: the plain code character string is as the problem of password; This class mistake appears at from unencrypted file memory or network and follows the tracks of as the method for password to this character string of use.See following program segment:
Public?static?void?main(String[]args)throws?SQLException,
FileNotFoundException,IOException{
Properties?info=new?Properties();
final?FileInputStream?st=new?FileInputStream("config.ini");
info.load(st);
st.close();
DriverManager.getConnection(
"jdbc:mysql://localhost:3307",info);
}
Analyze: if storage or network are not protected by external encryption, then any people that can conduct interviews can obtain the content of password.The way that solves: password should be imported dynamically.If can not do like this, then should with password storage in irreversible summary,,, then will add overstocked password storage in configuration file if method need be obtained password from plain text as md5.
Again for example, fault title: unsafe random number problem; This class mistake occurs in safety requirements than under the higher situation, and program has but been used a unsafe random number.See following program code:
Again for example, fault title: correctly do not handle the private information problem; This class mistake occurs in the place that does not have correct processing private information, such as important informations such as client password are recorded in the daily record of program.
D class, race condition pattern.Comprising following several subtypes:
For example, fault title: non-atom file operation; This class mistake occurs in when non-atom file operation is used, as, carry out creating file again after file.exists () checks.See following program code:
Filefile=new?File(profilesDir,name+".dat");
String?data="New";
if(file.exists()){
data="Existing";
}
FileOutputStream?st=new?FileOutputStream(file,true);
Analyze: this is the race condition (TOCTOU) of typical time check and correction and time utilization.The window that has leak between time detecting and time utilization this means that the state of inspection may no longer be true under the state that uses.This occurs in code when not carried out simultaneously by a plurality of threads by synchronized and identical code.If other external progress utilize this situation, it also might take place in the synchronized piece, as, if another JVM also is in operation, when perhaps having a direct file system operation.This will cause extension, data injection, leakage of information or the data interruption of privilege.Solution: sometimes, the nation method of use language can be more better, and for example, File create NewFile can check and create as atomic operation.In addition, when file operation is security-related, should use low-grade file operation.For example, check the attribute of the file that all have been opened and can not distort, perhaps use file/catalogue lock.
Again for example, fault title: the data leak of cross-thread; The member territory of Servlet program can allow a user to see other user's data.See following program code:
public?class?GuestBook?extends?HttpServlet{
String?name;
protected?void?doPost(HttpServletRequest?req,
HttpServletResponse?res){
name=req.getParameter("name");
...
out.println(name+",thanks?for?visiting!");
}
}
Analyze: in the Servlet/JSP container, general Servlet/JSP example of instantiation only, the thread that starts a plurality of these examples is handled request.And being all threads, shares instance variable, so instance variable is not a thread-safe.
E class, irrational abnormality processing pattern; Comprising following several subtypes:
For example, fault title: unusual deadlock problem; The position of unlock in code is improper, if program is unusual in the inner generation of try, then unlock () can't call, and has gone up to lock not discharge then afterwards to cause deadlock, and this just need explicit release in finally.See following program code:
void?action(){
Lock?l=new?ReentrantLock();
1.lock();
try{
dosomething();
}catch(java.lang.Exception?e){
throw?new?RuntimeException("xxx");
}
l.unlock();
}
Improve one's methods:
1.lock();
try{
...
}finally{
1.unlock();
}
Again for example, fault title: unusual feedback information leaks; Dishing out when unusual, printing too much about system information.See following program code:
protected?void?doPost(HttpServletRequest?req,HttpServletResponse?resp)throwsServletException,IOException{
String?name=req.getParameter("userName");
File?file=new?File(System.getProperty("web.root"),name+".dat");
try{
FileOutputStream?str=new?FileOutputStream(file);
str.close();
}catch(IOException?e){
throw?new?ServletException("Cannot?open?file"+file+":"+e.getMessage());
}
}
Again for example, fault title: avoid using the printStackTrace method; E.printStackTrace () is commonly used to print abnormal information, but the bottom layer realization details of its existence possibility leakage system.
F class, inferior quality code pattern.Comprising following several subtypes:
For example, fault title: the main method problem in the web application; This class mistake occurs in weblication, contains among J2EE application program and the applets under the situation of main method.See following program code:
public?void?doGet(HttpServletRequest?req,HttpServletResponse?res)throws?ServletException,IOException
{
......
}
public?String?getServletInfo(){
return"A?servlet?that?knows?the?name?of?the?person?towhom?it′s"+"saying?hello";
}
private?void?work(){
//test?some?code?within?our?application
}//leaving?this?around?is?unwanted?once?in?production
public?static?void?main(String[]args){
Example_205?ex=new?Example_205();
//test?that?our?code?is?working
ex.work();
}
Analyze: the main method is put into the back door that will cause an easy access of this program existence in the weblication.Safety Design during Web uses trends towards not considering the main way access, so this is a risk.Solution is to remove all main methods in product code.
Again for example, fault title: create temporary file but not deletion; This class problem occurs in when temporary file and is created, and arranges deletion after withdrawing from or using.See following program code:
protected?void?doPost(HttpServletRequest?req,HttpServletResponse?resp)
throws?ServletException,IOException{
File?file=File.createTempFile("aaa",".tmp");
useFile(file);
}
Analyze: first problem is if a temporary file comprises sensitive information, and the assailant can obtain the access right to these information after application program finishes.Second problem is to cause a weblication resource exhaustion because application program may use when presence filename or catalogue can't keep all files.Solution: temporary file should be deleted at once after using.At least all temporary files of mark are deleteOnExit.
Again for example, fault title: temporary file deletion problem; This class mistake occur in when temporary file plan when withdrawing from deleted, but do not have clear and definite deletion again.These class defective great majority are present in the environment of server or servlet.If a file comprises sensitive information, preferably deletion as soon as possible.The problem that is not arranged the temporary file deleted is with by error tracking.
The G class, encapsulate improper pattern.Comprising following several subtypes:
For example, fault title: rreturn value is revealed; This method may be revealed inner expression (EI_EXPOSE_REP) when returning with variable object correlation.Malice applet can revise the internal state of object by revising return results.See following program code:
private?ArrayList?adminUsers;
public?Collection?getAdminUsers()
{
return?adminUsers;
}
void?maliciousUserCode()
{
getAdminUsers().add("myself");
}
Solution: these threats can prevent by do not store the mutable object related content in public method, can use immutable object to replace.
Again for example, fault title: the method authority is provided with; This class mistake occurs in when method and is not defined as when privately owned.This mistake can report when interface and method overloading or quilt heavy duty.The scope interpretative rule defines the usable range of class, and scope is the expansion to the Applet class under the default situations.See following program code:
public?class?Example_218?extends?Applet{
private?void?methodA(){
}
public?void?methodB(){
}
}
Again for example, fault title: the inner classes system information exposes.This class mistake occurs in when having the inner classes definition.See following program code:
public?class?innerClsDef{
private?String?data;
class?MyInnerClass{
public?void?print(){
System.out.println(data);
}
}
Analyze: the Java bytecode does not have the notion for inner classes.Compiler converts inner classes to the general category that can visit all codes in same bag.Like this, even be declared into privately ownedly, inner classes has also obtained the access right in territory to the encapsulation class.The assailant can use inner classes to visit the outer category of its correspondence.
Again for example, fault title: the Garbage Collector access rights are unusual; Garbage Collector should be protected, is not public.
Two, at the C/C++ language, concrete safety bug defect mode comprises following classification:
Category-A, not verified input.Comprising following several subtypes:
A1, buffer zone overflow: if when the programmer wants the data of storing in buffer zone can data quantity stored than buffer zone institute also big, Buffer Overflow mistake will take place.These extra data will be stored in the adjacent internal storage location, and this will damage system and be stored in the data here originally, be accidental though BufferOverflow causes system mistake.But it is a modal problem in the software security problem.When utilizing Buffer Overflow to attack, these extra data may comprise some malicious codes, and it may destroy user file, rewrite data or steal user's privacy.Why can utilize buffer zone to overflow and attack, be because the program language structure of a lot of C/C++ can not be carried out range check automatically, and many programmers do not give enough attention to this problem yet.It mainly comprises following content:
A1.1, fault title: input function causes overflowing.Some input function in the C/C++ language, in extraneous reading of content, unqualified length of reading in data.When the data length that reads in surpasses the internal memory restriction that distributes, will cause the Installed System Memory data destroyed, problems such as program crashing or execution malicious code.This class function mainly contains:
Numbering |
Function name or operational character |
Function performance |
Threaten |
? 1 |
cin |
From stream, read character string |
The cin function is reading of data from data stream directly, has ignored the data length detection fully |
? 2 |
gets(char[]) |
From stream, get a character string |
Same cin is less than length detection that the data of reading in are advanced |
3 |
getenv(char*envvar); |
From environment, get character string |
Same cin is less than length detection that the data of reading in are advanced |
4 |
LoadString(HINSTANCE?instance,UINT?uID, LPTSTR?lpBuffer,int?nBufferMax) |
Reading of data from a character source, and be assigned in the buffer zone |
Same cin is less than length detection that the data of reading in are advanced |
? 5 |
read(int?handle,void*buf,int?nbyte); |
From file, read the character of nbyte length |
Though on nbyte the length data length of reading in is controlled, nbyte can surpass the length of string |
6 |
fgets(char*string,int?n,FILE*stream); |
From stream, read a character string |
Same read |
7 |
scanf(char*format[,argument,...]) |
Carry out the format input |
Same cin does not detect for the length of the data of reading in |
8 |
gettext(int?left,int?top,int?right,intbottom, void*destin) |
Text copy on the text mode screen is arrived the memory block |
Same cin |
9 |
fread(char*,intnum?1,int?num2,FILE*fp) |
The file read operation |
Same read |
For example, see following program code:
char?buf[BUFSIZE];
cin>>buf;
Analyze: cin does not detect with the length of reading in data the length of buf, when the length of reading in data surpasses the BUFSIZE of buf, will cause memory overflow.The method that solves is to use and has detection function or the built-in function that reads in length restriction is replaced these functions.
A1.2, fault title: input variable causes buffer zone to overflow.If data pass into from the outside, and also do not detect before using, so, this is a mistake. such variable mainly contains: argv[], optarg, env[].Simultaneously, if a variable imports in a publicly-owned function, perhaps global variable (not knowing that statement wherein) is used by publicly-owned function, and checking the variable legitimacy not.
A1.3, fault title: string operation causes buffering to be crossed the border.In the C/C++ language, some string operation function is to operate by source data size formulation buffer zone border rather than according to the buffer size of Target Assignment.Like this, when the size of source data surpasses big or small that target data distributes, will cause buffer zone to overflow.This class function has:
Numbering |
Function name or operational character |
Function performance |
Threaten |
1 |
Strcpy (char*str1, char * str2) |
The string copy |
Buffer zone takes place to be overflowed when the length of str2 surpasses str1, |
2 |
Strncpy (char*destin, char*source, int maxlen) |
The string copy |
As maxlen during greater than the length of destin, buffer zone overflow error takes place |
3 |
Strcat (char*destin, char * source) |
Character string splicing function |
To the character string that will splice, do not detect the size of buffer zone |
4 |
Sprintf (char*string, char * farmat[, argument ...]) |
Send format to output in the character string |
Format output character string function sprintf does not check the size of buffer zone |
5 |
Vsprintf (char*string, char*format, va_list param) |
Send format to output in the string |
The same sprintf of size does not check buffer zone |
6 |
Snprintf (char*restrict buf, size_tn, const char* restrict format ...); |
From subject string, copy n-1 character at most in target strings, and then add one 0 in the back.If, will can not overflow so the size of target strings is n. |
The character string size surpasses n, will cause overflowing |
int?main()
{
char?a[10];
char?b[100];
strcpy(a,b);
}
Analyze: sizeof (b) sizeof (a), so internal memory overflow error takes place when copying the content of b the buffer zone of a to.
A1.4, fault title: the internal memory that the internal memory operation function causes overflows.In C Plus Plus, a part of function can directly be operated region of memory, when the size of operated internal memory does not have when monitored, internal memory may take place overflow.Function as shown in the table:
Numbering |
Function name or operational character |
Function performance |
Threaten |
1 |
memset(void*dest,int?c,size_t count) |
The internal memory assignment function |
When c surpasses the memory size of dest distribution, overflow |
2 |
wmemset(wchar_t*dest,wchar_t c,size_tcount); |
The internal memory assignment function |
When c surpasses the memory size of dest distribution, overflow |
3 |
memcpy(void*dest,const?void *src,size_tcount); |
The memory copying function |
When Memory Allocation space, source greater than purpose Memory Allocation space, overflow |
4 |
wmemcpy(wchar_t*dest, const?wchar_t*src,size_tcount) |
The memory copying function |
When Memory Allocation space, source greater than purpose Memory Allocation space, overflow |
For example: memcpy is used for doing memory copying, and you can take it to copy the object of any data type, can specify the data length of copy, as: char a[100], b[50]; Memcpy (b, a, sizeof (b)); Attention: if, can cause the memory address of b to overflow with sizeof (a).
A1.5, fault title: incorrect end-of-string character position.Incorrect end of string symbol position will make the improper end of character string, if the position length of this end-of-string character surpasses the buffer length that character string is distributed, overflows.See following program code:
void?receive(intsocket){
char?buf[MAX];
int?nbytes=recv(socket,buf,sizeof(buf),0);
buf[nbytes]=′\0′;
Analyze: the length of nbyte is greater than max owing on nbyte, be provided with ' 0 ' will make the length of buf surpass the max length of having distributed.The problem that causes buffer zone to overflow.
A1.6, fault title: the comparison condition when symbolic number is negative value.When reading in the numerical value of a signed number certificate from the external world, because might surpassing the maximum positive of signed number certificate, the data of reading in represent scope, causing the actual value of this number is a negative value.See following program code:
void?TypeConvert(){
char?input[MAX];
char?output[MAX];
fillBuffer(input);
in?tlen=getInputLength();
if(len<=MAX){
memcpy(output,input,len);
}
...
}
Analyze: when len was a negative value, the Rule of judgment of len<=MAX was set up, and causes memcpy function generation buffer zone overflow error.
A1.7, fault title: integer overflows.The expression of integer is limited in scope, and when the data of reading in from the external world are given integer the system by assignment when, if surpass the span of integer, causes integer to overflow.The variable that overflows may cause total system to go wrong in use.See following program code:
char*processNext(char*strm){
char?buf[512];
short?len=*(short*)strm;
strm+=sizeof(len);
if(len<=512){
memcpy(buf,strm,len);
process(buf);
return?strm+len;
}else{
return-1;
}
}
The analysis of causes: when strm is a negative, overflow, cause system crash.
A1.8, fault title: Array Bound, i.e. Array Bound visit.See following program code:
char?Read(){
char?buf[5];
return0+buf[0]
+buf[1]
+buf[2]
+buf[3]
+buf[4]
+buf[5];
}
Analyze: buf[5] cross the border.
A2, Light Directory Access Protocol (LDAP, Lightweight Directory Access Protocol) are attacked.Described LDAP is a kind of directory services access agreement based on Client, and LDAP also is a kind of special database.When the LDAP content is changed by malice, be equivalent to data message and be modified, may give inappropriate authority to the user name that the assailant uses, cause leakage of information; May make system for content be changed by malice; May obtain incorrect data, finally may cause the collapse of system.
A2.1, fault title: the change of LDAP Query Information malice.When the user data that is not verified is used as establishment LDAP filtrator, will cause assailant's malicious modification LDAP information.See following program code:
fgets(manager,sizeof(manager),socket);
snprintf(filter,sizeof(filter,"(manager=%s)",manager);
if((rc=ldap_search_ext_s(1d,FIND_DN,LDAP_SCOPE_BASE,
filter,NULL,0,NULL,NULL,LDAP_NO_LIMIT,
LDAP_NO_LIMIT,&result))==LDAP_SUCCESS){
..}
Analyze: when by manage keyword lookup information, and when lookup result made amendment, because manager is maliciously tampered, so the result who obtains is non-conceivable result.What lead to errors searches and data modification.
A2.2, fault title: LDAP handle.When the LDAP query statement as inquiry contains the malicious data of user's input, will obtain wrong return results.See following program code:
rc=ldap_simple_bind_s(1d,NULL,NULL);
if(rc!=LDAP_SUCCESS){
}
fgets(dn,sizeof(dn),socket);
if((rc=ldap_search_ext_s(1d,dn,LDAP_SCOPE_BASE,
filter,&result))!=LDAP_SUCCESS){
...
}
Analyze: dn has been delivered to the query statement of LDAP as variable.
A3, SQL attack.
For example, fault title: SQL injects.Be similar to LDAP, when not verified user's input is used for the query statement of SQL, will cause obtaining wrong Query Result.See following program code:
ctx.getAuthUserName(&userName);{
CString?query="SELECT*FROM?items?WHERE?owner=″′
+userName+″′AND?itemname=″′
+request.Lookup("item")+""′;
dbms.ExecuteSQL(query);
Analyze: userName is by the change of malice.
A4, not verified input are used for file.
For example, fault title: variable is used as filename.If data just are used as filename without validity check and use, so it is classified as Defect.
FILE*configf=NULL;
char*config=getenv("CONFIG_FILE");
if(config!=NULL){
configf=fopen(config,"r");
In this example, think, not through checking that effectively just be not used as a filename and be applied among the function f open (), the hacker can be easy to read shielded file like this because of Defect is data from function getenv ().
A5, not verified input are used for the system level function
A5.1, fault title: system is provided with malicious modification.When the information of reading in when the external world is used to the function of system level, will cause system to be provided with by malicious modification.These functions generally mostly are linux and use function down, and similarly function mainly contains:
Title |
Function |
Title |
Function |
getdtablesize |
The maximum number of files that process can be opened |
getpid |
Obtain process identification number |
getpgid |
Obtain and specify the process group identification number |
getppid |
Obtain the parent process identification number |
setpgid |
Be provided with and specify the process group mark number |
getpriority |
Obtain dispatching priority |
getpgrp |
Obtain current process group id number |
setpriority |
Dispatching priority is set |
setpgrp |
Current process group mark number is set |
|
|
For example: sethostid (argv[1]).Because sethostid relates to the function of system level, when using argv[1] when doing parameter, may make that system information is maliciously tampered.
A5.2, fault title: system resource malicious modification.When the information of reading in when the external world is used to the function of system level, will cause system resource by malicious modification.See following program code:
char*rPort=getenv("rPort");
serv_addr.sin_port=htons(atoi(rPort));
if(connect(sockfd,&serv_addr,sizeof(serv_addr))<0)
error("ERROR?connecting");
Analyze:, make that a port is opened by malice in the system because of system resource is modified.
A5.3, fault title: incorrect built-in function loads.When the built-in function that loads is not formulated absolute path, other built-in function of the same name of one of loading that may victim malice.This class function has:
Numbering |
The function call name |
Numbering |
The function call name |
1 |
LoadLibrary |
15 |
ReplaceFile |
2 |
LoadLibraryEx |
16 |
SearchPath |
3 |
AfxLoadLibrary |
17 |
SetFileSecurity |
4 |
CopyFile |
18 |
DecryptFile |
5 |
CopyFileEx |
19 |
DuplicateEncryptionInfoFile |
6 |
CreateDirectory |
20 |
EncryptFile |
7 |
CreateDirectoryEx |
21 |
EncryptionDisable |
8 |
CreateFile |
22 |
FileEncryptionStatus |
9 |
DeleteFile |
23 |
OpenEncryptedFileRaw |
10 |
MoveFile |
24 |
QueryRecoveryAgentsOnEncryptedFile |
11 |
MoveFileEx |
25 |
QueryUsersOnEncryptedFile |
12 |
MoveFileWithProgress |
26 |
RemoveUsersFromEncryptedFile |
13 |
OpenFile |
27 |
GetExpandedName |
14 |
RemoveDirectory |
28 |
LZOpenFile |
If use: LoadLibrary (" liberty.dll "); Then can there be specified path because of liberty.dll.The assailant can load the liberty.dll of a malice.
A6, other.
A6.1, fault title: denial of service.When not verified user's input is used for the thread control function, will cause thread deadlock, Dos attacks.See following program code:
unsigned?int?usrSleep?Time=uatoi(usrInput);
sleep(usrSleepTime);
Analyze: allow the user import the time of a thread sleep, if usrSleepTime is excessive, thread will rest on sleep state, denial of service all the time.
A6.2, fault title: inveigle security risk.Used some system calls, as gethostbyaddr, gethostbyname, sethostname can bring security risk.Because these class methods depend on the data of remote server, might be false information.See following program code:
#include<netdb.h>
extern?int?h_errno;
struct?hostent*myGethostbyname(const?char*name)
{
return?gethostbyname(name);
}
Analyze: name is by the information of user's input, when name is system manager or other key person's user names, will leak out system information.Therefore, need to check the code under the various situations, comprise incredible user's input.
A6.3, fault title: unserviceable SHELL order.Utility command line character string was as parameter when system carried out the SHELL explicit order, and a user can inject this character string and carry out arbitrary code.
B, abuse API pattern.Mainly comprise following content:
B1, fault title: inappropriate chroot () system call.Inappropriate chroot () system call meeting makes the assailant escape the constraint of chroot.See following program code:
chroot("/var/ftproot");
...
fgets(filename,sizeof(filename),network);
localfile=fopen(filename,"r");
while((len=fread(buf,1,sizeof(buf),localfile))!=EOF){
fwrite(buf,1,sizeof(buf),network);
}
fclose(localfile);
Analyze: the GET order of the FTP that this code can be used for carrying out.Ftp server calls chroot () and visits file to attempt to stop outside/var/ftproot when its initialization routine.("/") changes current working directory, so the assailant can demand file " ../../../../../etc/password ", and obtains the portion copy of the cryptogram of this system but because server is not by calling chdir.
B2, fault title: the internal memory of not removing heap discharges.Use realloc (), fork (), vfork () to adjust buffer size and store sensitive information and may cause sensitive information to be exposed to the assailant, because it is not eliminated out internal memory.Solution: in program, discern critical data and check its operating position.After using these functions, destroy the data in the extra buffer immediately.See following program code:
cleartext_buffer=get_secret();
...
cleartext_buffer=realloc(cleartext_buffer,1024);
...
scrub_memory(cleartext_buffer,1024);
Analyze: code is attempted sensitive data is removed from internal memory, but realloc () is used, and this function is commonly used to increase the size of storage allocation piece.This operation often needs content replication to the new and bigger memory block with old memory block.The existence that memory block originally is still complete, so the copy of data still remains in the internal memory of originally distributing to cleartext_buffer.
B3, fault title: unsafe DNS inquiry.This class mistake occurs in domain name or the IP address of too believing the dns lookup function.Because the assailant can change dns server, so in not too DNS inquiry of secure context.See following program code:
struct?hostent*hp;
struct?in_addr?myaddr;
char*tHost="trustme.trusty.com";
myaddr.s_addr=inet_addr(ip_addr_string);
hp=gethostbyaddr((char*)&myaddr,
sizeof(struct?in_addr),AF_INET);
if(hp&&!strncmp(hp->h_name,tHost,sizeof(tHost))){
trusted=true;
}else{
trusted=false;
}
Analyze: this code wants to inquire about to determine by DNS whether an inbound request comes from the trust main frame, if but the assailant can infect DNS buffer memory (also claiming the DNS Cache Poisoning), and they just can gain credit so.
B4, fault title: socket binding issue.Can not guarantee not have socket to be bound on the address specific among the INADDR_ANY at same port, the bag in the network service may stolen or deception.In most systems, the socket option of SO_REUSEADDR is set, calling bind () method all allows any processing to use INADDR_ANY to be tied to the port that a processing has before been bound, this just allows the user being tied on the special address of a server on the unprivileged port, and the udp bag or the tcp that steal it connect.See following program code:
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdio.h>
#include<arpa/inet.h>
void?bind_socket(void){
int?server_sockfd;
int?server_len;
struct?sockaddr_in?server_address;
unlink("server_socket");
server_sockfd=socket(AF_INET,SOCK_STREAM,0);
server_address.sin_family=AF_INET;
server_address.sin_port=21;
server_address.sin_addr.s_addr=htonl(INADDR_ANY);
server_len=sizeof(struct?sockaddr_in);
bind(server_sockfd,(struct?sockaddr*)&s1,server_len);
}
Solution: the address of the socket address limitation of server to known part.
B5, fault title: the fragility of named pipes.Call the function of handling resource and its return results is not judged, the rreturn value of ignoring the resources allocation function can cause the reusing of existing shared resource, and can give the operating right of user Geng Gao and brings risk to system.Such fault usually occurs in following two kinds of situations:
First kind, called CreateNamedPipe during use, do not check whether returned INVALID_HANDLE_VALUE; Do not call GetLastError yet and check whether returned ERROR_ACCESS_DENIED.Second kind, called CreateMutex during use, do not check whether returned NULL; Do not call GetLastError yet and check whether returned ERROR_ALREADY_EXISTS.
C, peace zone properties defect mode; Mainly comprise following several types:
C1, fault title: insecure process creation.The exposure that local authority enlarges, the execution of calling meeting permission malicious code of some system creation processes comprises following system call:
Numbering |
The system call name |
Numbering |
The system call name |
Numbering |
The system call name |
Numbering |
The system call name |
1 |
CreateProcess |
17 |
_spawnle |
33 |
_tspawnle |
49 |
_wexecvpe |
2 |
CrcateProcessAsUser |
18 |
_spawnlpe |
34 |
_tspawnlp |
50 |
_wspawnle |
3 |
CreateProcessWithLogon |
19 |
_spawnlp |
35 |
_tspawnlpe |
51 |
_wspawnlp |
4 |
ShellExecute |
20 |
_spawnv |
36 |
_tspawnv |
52 |
_wspawnlpe |
5 |
ShellExecuteEx |
21 |
_spawnve |
37 |
_tspawnve |
53 |
_wspawnv |
6 |
WinExec |
22 |
_spawnvp |
38 |
_tspawnvpe |
54 |
_wspawnve |
7 |
system |
23 |
_spawnvpe |
39 |
_tspawnvp |
55 |
_wspawnvp |
8 |
_execlp |
24 |
_texecle |
40 |
_wexecl |
56 |
_wspawnvpe |
9 |
_execl |
25 |
_texeclp |
41 |
_wexecle |
|
|
10 |
_execlpe |
26 |
_texecl |
42 |
_wsystem |
|
|
11 |
_execle |
27 |
_texecve |
43 |
_wexeclpe |
|
|
12 |
_execvp |
28 |
_texeclpe |
44 |
_wexeclp |
|
|
13 |
_execv |
29 |
_texecv |
45 |
_wexecv |
|
|
14 |
_execve |
30 |
_texecvp |
46 |
_wexecve |
|
|
15 |
_execvpe |
31 |
_texecvpe |
47 |
_wexecvp |
|
|
16 |
_spawnl |
32 |
_tspawnl |
48 |
_wspawnl |
|
|
For example, see following program code:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
int
main(intargc,char*argv[]){
int?fd;
if((fd=open(argv[1],0))==-1){
error("can′t?open%s",argv[1]);
return-1;
}
if(argc==2){/*execute?command*/
if(execlp("/bin/sh/","sh","-á",argv[1],(char*)0)){
/*some?code*/
}else{
error("can′t?execute%s",argv[1]);}
?}
}
Solution: use fork, execve, pipes to finish the execution that control is visited.
C2, fault title: unserviceable grand.Can obtain too much access rights by " ALL_ACCESS ", cause unsuitable loosening to allow to visit resource, or with variable as following function parameters:
Numbering |
Function name |
Numbering |
Function name |
1 |
RegCreateKeyEx |
5 |
CreateDesktopEx |
2 |
SHRegCreateUSKey |
6 |
CreateWindowStation |
3 |
CreateFile |
7 |
CreateService |
4 |
CreateDesktop |
|
|
For example, see following program code:
//SV.BRM.CONST
LONG?foo(H?KEY?hkey,LPCTSTR?lpSubKey,DWORD
ulOptions,PHKEY?phkResult){
return?RegOpenKeyEx(hkey,lpSubKey,ulOptions,
KEY_ALL_ACCESS,phkResult);
}
Solution: use the minimum authority that needs.
C3, fault title: unserviceable registration.Use HKEY_LOCAL_MACHINE as parameter registration, can run counter to minimum authority principle, the person has supvr's authority to cause the low rights.Perhaps use variable as these function parameters, all may cause the generation of safety failure.
C4, fault title: insecure password.Unserviceable password during easy crack, can be reported this type of mistake.
C5, fault title: clear-text passwords.This class mistake appears in the plaintext that password is stored in the configuration file of application program or other data space, and the storage password is in the safety of the inside entail dangers to system expressly.See following program code:
...
RegQueryValueEx(hkey,TEXT(.SQLPWD.),NULL,
NULL,(LPBYTE)pwd,&size);
rc=SQLConnect(*hdbc,server,SQL_NTS,uid,
SQL_NTS,pwd,SQL_NTS);
...
Analyze: this section code reads the password accesses database from registration table.It can well move, but anyone, if he can visit the registration table of storage password, he just can read password value.If a dishonest employees access these information, he just might invasive system.Solution: password should be imported dynamically.If can not do like this, then should be in irreversible summary with password storage, md5 for example.If method need be obtained password from plain text, then will add overstocked password storage in configuration file.
C6, fault title: hard coded password.This class mistake occurs in works as hard coded, when perhaps the part of hard coded is as password.The hard coded password may jeopardize the safety of system, and this harm is not easy to be remedied.
C7, fault title: unsafe random number.Random behavior that unserviceable random function produced or data can not reach due effect: such as, hacker may guess you program next step will how to carry out or will use what data.The least reliable random function is srand () and rand (), and also have much very insecure function not use, as, rand48 (), random (), srandom (), s etstate (), initstate () and srand48 (), and other all * rand48 () functions.See following program code:
char*CreateReceiptURL(){
int?num;
time_tt1;
char*URL=(char*)malloc(MAX_URL);
if(URL){
(void)time(&t1);
srand48((long)t1);/*use?time?to?set?seed*/
sprintf(URL,"%s%d%s",
"http://test.com/",lrand48(),".html");
}
return?URL;
}
Analyze: this section code is with this function of srand48 (), produces the sign of " unique " in the page of acceptance.Because this function is a statistics pseudorandom number generator,, the character that it produces guesses so being easy to victim.
C8, fault title: unsafe privilege-escalation.The exposure of privilege-escalation can cause dangerous function.Some functions need special authority to carry out, and in some cases, these functions can only be carried out by specific user or group.Modal needs are that the user should be local keeper.Other functions need user's account to have special authority.The visit that most of program needs authority or special account to obtain the system resource that could visit the power user.See following program code:
#include<unistd.h>
#include<sys/types.h>
int?CheckPoorEncryption(void){
uid_tmyid=getuid();
/*..some?code..*/
setuid(0);
/*..code?that?needs?to?be?run?at?high
privilege..*/
return0;
}
Analyze: when carrying out the operation of a higher authority, need to use setuid to promote authority, this allows a domestic consumer to have the root authority.The security breaches that may cause common in setuid have: unstated or the hint hypothesis; Overflowing of numeral or buffering; Change or deleted file; Quote subprocess or the like.
C9, fault title: explicit raising user right.Therefore the correct execution of some functions needs the user to have certain authority, should be careful when higher-rights is set.In program, if reduce certain user's authority, guarantee to change earlier its group identification, change user ID again.Because if change user ID earlier, program is provided with group identification with regard to the authority that no longer includes advanced level user.
C10, fault title: ignore the rreturn value of checking function.The rreturn value of some system functions has shown this time operates success or not, so must check its rreturn value when calling these functions, otherwise will weaken the function of these system functions.Such as, may make to use to obtain to bring risk to system than the higher priority of reality.
D, race condition pattern: mainly comprise following content:
D1, fault title: time check and time are used the race condition (TOCTOU) that produces.The reason that the race condition of this class mistake produces is: the window that has security breaches between time detecting and time utilization of a given resource this means that the state of inspection may no longer be true under the state that uses.
Certain operations function for file name can cause " TOCTOU ", and these functions mainly contain:
Numbering |
Title |
Function |
Numbering |
Title |
Function |
1 |
acct |
|
12 |
chgrp |
|
2 |
access |
|
13 |
creat |
|
3 |
chmod |
|
14 |
open |
|
4 |
lchown |
|
15 |
pathconf |
|
5 |
chown |
|
16 |
opendir |
|
6 |
fopen |
|
17 |
lstat |
|
7 |
fdopen |
|
18 |
stat |
|
8 |
freopen |
|
19 |
rename |
|
9 |
fchmod |
|
20 |
link |
|
10 |
fchown |
|
21 |
lchown |
|
11 |
chdir |
|
22 |
|
|
For example, see following program code:
do{
if(iterator->dir==NULL){
iterator->dir=opendir(iterator->bucket_name);
if(iterator->dir==NULL){
switch(errno){
case?ENOENT:{
break;
}
case?0:{
struct?stat?dirstat;
...
if(stat(iterator->bucket_name,&dirstat)==0){
...
break;
}
Analyze: what the programmer designed is to adopt opendir () and stat () to operate in same file simultaneously, but the hacker may remove this document at a terrific speed, thus cause these two operations can not follow procedure person the acting on like that on the same file of design.Solution: avoid using above-mentioned, adopt file handle or file description with the system function of file name as parameter: symbol, in case because system gives file handle and description: symbol assignment, just easy change unlike the filename of character interlinkage of file.
D2, fault title: signal Processing is improper.Set up the same signal processor for a plurality of different signals, will cause race condition if different signals arrives in a short time simultaneously.
D3, fault title: state synchronized fault.State synchronized is meant one group of defective, wherein relates to the contradictory state in carrying out a process, and it can cause some undefined behaviors.
Competition between D4, fault title: access () and the remove ().
What following Example was showed is the race condition that causes between access () and the remove (), and clearly these two operate in the same function, and usefulness is same complete trails.
void?remove_if_possible(char*filename){
if(access(filename,0))
remove(filename);
}
Competition between D5, fault title: opendir () and the access ().Programmer design be to adopt opendir () and stat () to operate in same file simultaneously, but the hacker may remove this document at a terrific speed, thereby acting on like that on the same file of causing that these two operations can not follow procedure person design.See following program code:
do{
if(iterator->dir==NULL){
iterator->dir=opendir(iterator->bucket_name);
if(iterator->dir==NULL){
switch(errno){
case?ENOENT:{
break;
}
case?0:{
struct?stat?dirstat;
...
if(stat(iterator->bucket_name,&dirstat)==0){
...
break;
}
F, inferior quality code pattern; Mainly comprise following type:
F1, fault title: predictable temporary file name.Some temporary file name is a danger close, because may allow the hacker guess their name in advance like this, thereby causes the hacker can visit exclusive data.Hacker or make a spurious document of the same name allows program read, and perhaps the hacker be by can reading these files, thereby sees the relevant information of program.See following program code:
static?bool
do_edit(const?char*filename_arg,EBuf?buf)
{
char fnametmp[MAXPGPATH];
FILE *stream=NULL;
const?char*fname;
bool error=false;
int fd;
if(filename_arg)
fname=filename_arg;
else
{
GetTempFileName(".","psql",0,fnametmp);←defect
fname=(const?char*)fnametmp;
fd=open(fname,O_WRONLY|O_CREAT|O_EXCL,0600);
if(fd!=-1)
stream=fdopen(fd,"w");
Analyze: the 3rd parameter of GetTempFileName () must be a random number, otherwise the temporary file name that generates is exactly predictable.In the example below, the 3rd parameter is 0, so this IP is defect.
F2, fault title: expose absolute path.The file operation function uses absolute path can reveal significant data.See following program code:
int?main(int?argc,char*argv[])
{
int?fh;
fh=creat("/usr/bin/ls",_S_IREAD|_S_IWRITE);
if(fh==-1)
return-1;
else
{
write(fh,argv[1],sizeof(argv[1]))
close(fh);
return?0;
}
}
Solution: check the filename operation.
F3, fault title: the storehouse address of variable returns.Function has returned the address of storehouse variable, and this will cause beyond thought program behavior, such as program crashing.See following program code:
char*?getName(){
char?name[STR_MAX];
fill?InName(name);
return?name;
}
The analysis of causes: because local variable is to be distributed on the storehouse, when a program was returned the pointer of a sensing local variable, what it returned was the address of storehouse.Function call subsequently is to reuse this identical stack address, thereby the value of the pointer that covers makes it no longer correspond to identical variable.In many cases, it can cause program crashing.
F4, fault title: repeat to discharge.This mistake occurs in the internal memory that has discharged and is discharged once more.In some cases, this mistake may cause buffer zone to overflow.
F5, fault title: discharge resource and use.Use the resource that has discharged can make program crashing.See following program code:
char*ptr=(char*)malloc(SIZE);
...
if(err){
abrt=1;
free(ptr);
}
...
if(abrt)_{
logError("operation?aborted?before?commit",ptr);
}
Analyze: pointer variable ptr is released in this example, and the function logError () of back is still using it.
F6, fault title: variable no initializtion.Code has used the variable of no initializtion, will cause a uncertain result.
F7, fault title: symbolic number and unsigned number conversion.Function declaration is returned a unsigned number, but in fact returned one value of symbol is arranged.See following program code:
unsigned?int?readdata(){
int?amount=0;
...
if(result==ERROR)
amount=-1;
...
return?amount;
}
Analyze: the conversion between signed number and the unsigned number, can cause various mistakes, still from the angle of safety, modal is to overflow with integer to overflow relevant with buffer zone.
G, encapsulate improper pattern; Mainly comprise following type:
G1, fault title: system resource is leaked.System data or Debugging message are gone out by unconscious leakage, can make the assailant understand system information.Increased the possibility that system is attacked.See following program code:
if(!fileInput.Open(PATH,CFile::modeRead,&ex)){
ex.ReportError();
}
else{
fileInput.Close();
}
Analyze: the configuration different according to system, error message may be output to control desk, and the log file will be exposed to malicious attacker.If contain the relevant content of system in these error messages, the assailant will obtain by the relevant information of attacking system.
G2, fault title: do not have catching exception.If do not catch unusual that some dangerous functions dish out, will cause program crashing.See following program code:
void?function?(char*szDate)
{
PVOID?p=_alloca(lstrlen(szData));
//use?p
}
Analyze: if the assailant provides a szData also longer than memory size, _ alloca can cause one unusual and cause application program to stop, and then cause Dos.The correct method of handling this error situation is that calling of right _ alloca is packaged in the exception handler, and replacement internal memory stack region when wrong occurring.Its improve one's methods into:
void?function(char*szData)
{
_try
{
PVOID p=_alloca (lstrlen (szData)); // use p
}_except((EXCEPTION_STACK_OVERFLOW==GetExceptionCode())?
EXCEPTION_EXECUTE_HANDLER:EXCEPTION_CONTINUE_tSEARCH)
{
_resetstkoflw();
}
}
Adopt the test macro (DTS based on safety bug defect mode of the present invention, Defect TestingSystem), can carry out effective defect test and regular testing to the program that adopts the C/C++/Java language compilation, have the high and high characteristics of automaticity of measuring accuracy.
At first, this system definition based on the key technical indexes of the method for testing of software defect, and provide the defect mode state machine description document, this document has adopted the xml technical description defect mode state machine that will detect.
Secondly, the treatment scheme of system is: read software under testing, software source program to be measured is carried out lexical analysis, grammatical analysis, semantic analysis and function calling relationship analysis, generate abstract syntax tree, control flow graph, symbol table and the function call figure of software under testing, calculate the interval of variable in program by interval arithmetic then, the defect mode analysis engine is provided at last, the programmed control flow graph is traveled through, defect mode is unified test by this engine.Once more, this system provides friendly DTS user interface, and provides the defect mode form that the defect distribution situation is analyzed.Therefore the use test DTS of system of the present invention carries out the safety bug defect detection to C/C++ (VC)/Java written program.
Be to use the DTS system that the present invention is based on the safety defect pattern below, the result that 10 open source softwares that adopt Java languages to write are tested.(annotate: following software all derives from the code of increasing income, and wherein: the digital form of xx/xx is represented result that defective is confirmed, meaning promptly: confirm number/indefinite number/sum)
Dbase (version) |
File number/file line number |
Irrational abnormality processing |
It is improper to encapsulate |
Not verified input |
Abuse API pattern |
Security feature |
Down total |
Saxonb(1.0.2) |
990/269891 |
4/0/4 |
13/1/14 |
0/0/0 |
3/0/0 |
0/0/0 |
20/1/21 |
Contineo(3.0.4) |
224/54767 |
6/0/6 |
28/3/31 |
1/2/3 |
0/0/0 |
0/1/1 |
35/6/41 |
Mycore |
411/100599 |
16/0/16 |
17/7/24 |
20/10/30 |
0/0/0 |
1/0/1 |
54/17/71 |
j2ssh(0.2.9) |
442/89423 |
6/4/10 |
33/5/38 |
0/0/0 |
4/0/4 |
1/0/1 |
44/9/53 |
XuiPro(3.2) |
799/155290 |
6/1/7 |
31/31/62 |
0/0 |
1/0/1 |
0/0/0 |
38/3/41 |
Xui?32(3.2) |
552/113153 |
1/1/2 |
23/0/23 |
|
1/0/1 |
|
25/1/26 |
Azureus(3.0.5.2) |
2726/572721 |
27/6/33 |
12/3/15 |
|
2/0/2 |
30/6/36 |
71/15/76 |
Phex(3.2.6.106) |
790/166106 |
14/0/14 |
31/9/40 |
0/0/0 |
0/0/0 |
4/0/4 |
49/9/58 |
SSHTools-SSHDaemo n(Win32-0.0.9) |
308/39070 |
5/0/5 |
24/1/25 |
0/0/0 |
4/0/4 |
0/0/0 |
33/1/34 |
Drftpd(2.0.5) |
316/55587 |
18/3/21 |
10/2/12 |
0/0/0 |
5/0/5 |
0/0/0 |
33/5/38 |
Be to use DTS system below, the result that 10 open source softwares that adopt C Plus Pluss to write are tested based on the safety defect pattern.(annotate: following software all derives from the code of increasing income, and wherein: the digital form of xx/xx is represented result that defective is confirmed, meaning promptly: confirm number/indefinite number/sum)
Dbase (version) |
File number/file line number |
Not checking input |
The inferior quality code |
The risk operation |
Abuse API |
Down total |
winscp(416) |
164/12594 |
0/7/21 |
7/0/27 |
0/0/0 |
0/0/0 |
7/7/48 |
odbtp(1.1.4) |
23/5016 |
0/1/6 |
1/0/2 |
0/0/0 |
0/0/2 |
1/1/10 |
amsn(0.97.2) |
75/12776 |
0/16/16 |
0/0/0 |
0/0/0 |
0/0/0 |
0/16/16 |
italc(1.0.9) |
148/13052 |
0/2/2 |
1/0/1 |
12/0/12 |
0/0/0 |
13/2/15 |
pueblo |
370/79399 |
0/22/22 |
19/1/20 |
6/0/6 |
0/0/0 |
25/23/48 |
eMule |
199/10047 |
0/1/1 |
0/0/0 |
0/0/0 |
0/0/0 |
0/1/1 |
fileZilla(3.1.2) |
181/28013 |
0/10/46 |
21/4/68 |
0/0/0 |
0/0/0 |
21/14/116 |
firtex(1.0.3) |
301/38839 |
0/0/12 |
1/0/19 |
2/0/2 |
0/0/0 |
3/0/33 |
Freeweb(0.1.3.2) |
75/5578 |
0/1/38 |
4/0/6 |
0/0/0 |
0/0/0 |
4/1/44 |
myIE(301) |
70/13578 |
3/0/4 |
0/0/5 |
17/3/20 |
0/0/0 |
20/3/29 |
Be to use DTS2.0 test macro below, the result that the open source software of 10 C language is tested based on the safety defect pattern.(annotate: following software all derives from the code of increasing income, and wherein: the digital form of xx/xx is represented result that defective is confirmed, meaning promptly: confirm number/indefinite number/sum)
Dbase (version) |
File number/file line number |
Not checking input |
The inferior quality code |
The risk operation |
The security feature defective |
The race condition pattern |
Down total |
menuetos |
575/35725 |
0/10/21 |
2/1/5 |
2/2/6 |
0/0/0 |
0/0/0 |
4/13/32 |
acl_project |
147/25523 |
0/0/11 |
0/0/0 |
0/0/0 |
0/0/0 |
0/0/0 |
0/0/11 |
openh323 |
32/36190 |
0/0/0 |
2/0/2 |
4/0/4 |
0/0/0 |
0/0/0 |
6/0/6 |
robodoc |
84/21637 |
0/6/6 |
1/0/1 |
2/0/2 |
0/0/0 |
0/0/0 |
3/6/9 |
ettercap |
105/184766 |
2/13/15 |
4/0/4 |
0/0/0 |
0/0/0 |
0/0/0 |
6/13/19 |
kadcwin |
303/45849 |
1/1/4 |
0/0/6 |
23/0/23 |
0/0/0 |
0/0/0 |
24/1/33 |
amsn |
49/8862 |
1/7/11 |
0/0/0 |
0/0/0 |
0/0/0 |
0/0/0 |
1/7/11 |
fpgac |
25/8176 |
0/8/8 |
0/0/6 |
0/0/0 |
0/0/0 |
0/0/0 |
0/8/14 |
pg2 |
111/79479 |
0/1/1 |
7/0/7 |
2/1/3 |
0/0/0 |
0/0/0 |
9/2/11 |
ucd-snmp |
153/100619 |
1/40/41 |
2/1/3 |
8/0/8 |
0/0/0 |
0/1/1 |
12/41/53 |
In sum, as can be seen, when using the DTS system that the present invention is based on the security breaches pattern to test, its rate of false alarm is less from above three test result statistical forms, and test accuracy is higher.
The above is preferred embodiment of the present invention only, is not to be used to limit protection scope of the present invention.