CN101482847B - Detection method based on safety bug defect mode - Google Patents

Detection method based on safety bug defect mode Download PDF

Info

Publication number
CN101482847B
CN101482847B CN2009100030824A CN200910003082A CN101482847B CN 101482847 B CN101482847 B CN 101482847B CN 2009100030824 A CN2009100030824 A CN 2009100030824A CN 200910003082 A CN200910003082 A CN 200910003082A CN 101482847 B CN101482847 B CN 101482847B
Authority
CN
China
Prior art keywords
control flow
security breaches
function
tested program
file
Prior art date
Legal status (The legal status is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the status listed.)
Expired - Fee Related
Application number
CN2009100030824A
Other languages
Chinese (zh)
Other versions
CN101482847A (en
Inventor
宫云战
刘传昌
陈俊亮
杨朝红
肖庆
金大海
李飞宇
Current Assignee (The listed assignees may be inaccurate. Google has not performed a legal analysis and makes no representation or warranty as to the accuracy of the list.)
Beijing University of Posts and Telecommunications
Original Assignee
Beijing University of Posts and Telecommunications
Priority date (The priority date is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the date listed.)
Filing date
Publication date
Application filed by Beijing University of Posts and Telecommunications filed Critical Beijing University of Posts and Telecommunications
Priority to CN2009100030824A priority Critical patent/CN101482847B/en
Publication of CN101482847A publication Critical patent/CN101482847A/en
Application granted granted Critical
Publication of CN101482847B publication Critical patent/CN101482847B/en
Expired - Fee Related legal-status Critical Current
Anticipated expiration legal-status Critical

Links

Images

Landscapes

  • Storage Device Security (AREA)

Abstract

The present invention discloses a detection method based on security vulnerability mode, wherein the detection method comprises the following steps: reading the source code document of tested program for preprocessing, analyzing the safety vulnerability state machine description document corresponding to security vulnerability mode; executing lexical analysis and syntax analysis to the tested program code for constructing an abstract syntax tree of tested program; constructing a control flow chart according to the abstract syntax tree for generating symbol table; then calculating and updating the range set of variable value, analyzing the function calling relationship to the tested program according to symbol table and generating a function calling relationship graph, and then establishing a ud/du chain; traversing the control flow chart through establishing a security vulnerability mode state machine and calling the ud/du chain, calculating the state transition of security vulnerability state machine of each node on the control flow chart, if the security vulnerability machine enters a defect state, reporting the corresponding checking node, and outputting a security vulnerability testing report after testing. The method of the invention has the advantages of high automatization degree and high testing accuracy.

Description

A kind of detection method based on safety bug defect mode
Technical field
The present invention relates to the computer software testing technology, relate in particular to a kind of detection method based on computer security leak defect mode.
Background technology
Software defect normally produces in the software product performance history, has influenced the problem that maybe may influence the software product quality.According to the definition of software defect and the performance history of software product, software defect can be divided into classifications such as document defective, code defective, test defect and process defect usually.Here, described document defective refers to the defective found in the static check process to document, generally can examine by testing requirement analysis, document and pinpoint the problems; Described code defective is meant carries out going in peer review, audit or the code check process defective found to code; Described test defect is meant that (measurand generally is meant code, the system that can move to the measurand of being found by the test execution activity, the problem that does not comprise the static test discovery) defective, test activity type mainly comprise close beta, connect test, System Integration Test, user acceptance testing (UAT); Described process defect (being called the Non-Compliance problem again) is meant by movable defective and the problem of finding about process such as process audit, process analysis procedure analysis, management review, quality evaluation, quality audit.Described document defective, test defect and process defect can be realized preventing or avoiding mostly by method for normalizing, and the code defective is the most common, also the most difficult prevention.
Current, some defective or mistake in the soft project can only be found by the detection of manual type; And some mistake can detect it by compiler as grammar mistake and to discern, and picture expression formula mistake then both can have been passed through the manual testing, also can finish detection by automatic test.Because the mode efficient of manual detection is lower, range of application is narrower at present; If adopt automated manner that software defect is detected, then at first need various software defects are carried out rational pattern classification, but up to the present, existing software testing technology is still more coarse to the classification of software defect or software error, need be at software defect and classification of defects, do further research towards the aspects such as method of testing of certain class defective.
Because the complicacy of software and the complicacy of software defect, since software testing technology is born, although there are a lot of scientists aspect software defect mode, to do a large amount of research work, produce little effect, this has influenced the development and progress of software testing technology to a great extent.Entered since this century, along with society is increasing to the demand of software testing technology, the quality of software more and more comes into one's own, and the theory of testing of software is also developed fast.Judge whether ripe a kind of software test theory important symbol be whether tested object has reasonable defect mode definition, promptly require fault under this pattern should be realistic, in the actual software engineering, exist in a large number, the number of defects of defect mode can tolerate, and the fault under this pattern can be determined by test.
Software security flaw is a kind of of computer software defective, modal security breaches typically refer to the system software security breaches under the operating system environments such as form (windows), Linux, also comprise extensive application software, as the security breaches in office series office software, IE browser, Realplayer player, Mediaplayer player, network download tool and the instant communication software popular softwares such as (as MSN, QQ); In addition, also comprise the free software of open source code and the safety bug defect that has the software in the intelligent terminal of operating system.The existence of security breaches in the soft project, may attack this software and computer system is provided convenience for other people, in case security breaches implement to be attacked after by the network hacker utilization, then this system just may be controlled and then cause in the system confidential information to be stolen or consequence such as systemic breakdown by the attacker, causes heavy losses thus.
The problem of used computerese self owing to develop software, more or less all there are security breaches to a certain degree in different computereses.And fast-developing in network technology and the internet is popularized day by day today, computer system no longer is an information island one by one, most computing machine all needs to come into contacts with the external world, and suffers network attack probably in the process of computing machine and extraneous network communication.Therefore, study the detection technique at the software security flaw defective of the multiple computerese of a kind of compatibility, the security that improves the computer system and computer network is unusual urgent task.
Summary of the invention
In view of this, fundamental purpose of the present invention is to provide a kind of detection method based on safety bug defect mode, by to comprising that the security breaches that machine words such as C/C++/Java call the turn existence detect, reduce the rate of failing to report and the rate of false alarm of software test, improve accuracy of test, thereby promote the quality of software product.
For achieving the above object, technical scheme of the present invention is achieved in that
A kind of detection method based on safety bug defect mode, this method comprises:
A, read the security breaches detected state machine description document of tested program source code file and software security flaw pattern correspondence, described tested program is carried out pre-service and resolved security breaches detected state machine description document, and tested program carried out lexical analysis and grammatical analysis, generate the abstract syntax tree of tested program;
B, according to the abstract syntax tree of being constructed, generate the control flow graph of reflection tested program control structure and according to the abstract syntax tree of being constructed, and create the symbol table of tested program;
C, 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; Wherein, the process of the described ud/du of foundation chain is stored in the ud chain, is kept in the du chain by preserving all possible use tabulation of current definition for the use relation that will define by the use to the assignment of variable and variable, and described ud/du chain is used for confession security breaches detected state machine and calls;
D, 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; Wherein, described ud/du chain according to described foundation carries out the process of software vulnerability test for according to function calling relationship figure the control flow graph being traveled through to program code, and according in the security breaches detected 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 Hole Detection state machine on the calculation control flow graph, if security breaches detected state machine enters the software defect state, the checkpoint IP of then report correspondence.
Wherein, described tested program source code file is Java language or C/C++ language.
Described software security flaw mode type comprises:
Not verified input pattern is used to describe the input that some do not have checking, directly the security breaches of calling as function parameters;
Abuse application programming interfaces API pattern is used to describe the leak that those are trusted the side of being called mistakenly and caused by caller;
The security feature defect mode is used to describe for information about the security breaches of the related authentication of safety, access mechanism, confidentiality guarantee, cryptographic algorithm, rights management aspect;
The race condition pattern is used for describing the security breaches that the Distributed Calculation process resource sharing aspect relevant with time and state exists;
Irrational abnormality processing pattern is used to describe the safety bug defect relevant with error handling processing;
The inferior quality code pattern is used to describe the not good enough security breaches that can't expect that cause of software quality;
Encapsulate improper pattern, the security breaches when being used for the related system variable of described function, system resource and user profile and operating.
Steps A described to described tested program carry out pretreated process for to carry out macro substitution to tested program before testing, file comprises and conditional compilation.
The described parsing security breaches of steps A detected state machine description document resolves in the subsequent treatment internal storage data structure that security breaches pattern analysis engine can be discerned for utilizing analysis program with described security breaches detected state machine description document.
The described process of lexical analysis that tested program is carried out of steps A is for being converted to tested program the mark stream that can carry out grammatical analysis.
The process of the control flow graph of the described generation reflection of step B tested program control structure is: obtain by adopting visitor's pattern traversal abstract syntax tree, its method is on the basis of traversal abstract syntax tree, generates the visitor by a control flow graph and realizes; The way that described visitor adopts recurrence to descend generates the control flow graph, 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.
Described 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.
Detection method based on safety bug defect mode provided by the present invention has the following advantages:
The present invention is by carrying out the summary of system to the software security flaw defective that exists in Java language and the C/C++ language, and described security breaches are reasonably classified and be defined as some class security breaches patterns, promptly not verified input, abuse API pattern, security feature defect mode, race condition pattern, irrational abnormality processing pattern, inferior quality code pattern and encapsulate improper pattern; When using the automatic software testing tool, as application number is that the described test macro based on software defect mode of CN200810114261.0 is when testing the program source code of software under testing, use pairing defect mode state machine of security breaches pattern and foundation in the inventive method to be used for the ud/du chain that the described defect mode state machine of confession calls, assignment and use that can the fast query variable, improved the automaticity of test, classification in conjunction with described rational security breaches pattern, can in test, reduce the rate of failing to report and the rate of false alarm of software test, improve the accuracy of software test.
Description of drawings
Fig. 1 is the method for testing schematic flow sheet that the present invention is based on safety bug defect mode.
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:
Figure G2009100030824D00061
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:
Figure G2009100030824D00071
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?profie=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?getUserProfile(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_ONLY);
ResultSet?results=statement.exeeuteQuery(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?data?from?HTTP?request?in?servlet
String?lastName=req.getParameter(″lastName″);
int?userId=Integer.parseInt(req.getParameter(″userId″));
//Using?prepared?statements,even?if?last?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?something?with?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?objectl,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:
File?file=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?1=new?ReentrantLock();
l.lock();
try{
dosomething();
}catch(java.lang.Exception?e){
throw?new?RuntimeException(″xxx″);
}
l.unlock();
}
Improve one's methods:
l.lock();
try{
}finally{
l.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)throws
ServletException,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 Overfl ow 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,int?bottom, void*destin) Text copy on the text mode screen is arrived the memory block Same cin
9 fread(char*,int?num1,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 When the length of str2 surpasses str1, buffer zone takes place overflow
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 Same sprintf does not check the size of buffer zone
6 Snprintf (char*restrict buf, size_t n, 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_t?count); The internal memory assignment function When c surpasses the memory size of dest distribution, overflow
3 memcpy(void*dest,const?void *src,size_t?count); 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_t?count) 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(int?socket){
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);
int?len=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:
charRead(){
char?buf[5];
return?0+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(ld,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(ld,NULL,NULL);
if(rc!=LDAP_SUCCESS){
}
fgets(dn,sizeof(dn),socket);
if((rc=ldap_search_ext_s(ld,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?usrSleepTime=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/fiproot″);
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.But because server does not change current working directory by calling chdir ("/"), so the assailant can demand file " ../../../../../etc/password ", and obtains the portion copy of the cryptogram of this system.
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 CreateProcessAsUser 18 _spawnlpe 34 _tspawnlp 50 _wspawnle
3 CreatePr0cessWithLogon 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(int?argc,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(HKEY?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_ttl;
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_t?myid=getuid();
/*..some?code..*/
setuid(0);
/*..code?that?needs?to?be?run?at?high
privilege..*/
return?0;
}
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 r emove ().
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: o pendir () and the access ().Programmer design be to adopt opendir () and st at () 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];
fillInName(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*szData)
{
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_SEARCH)
{
_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(3.01) 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.

Claims (8)

1. the detection method based on safety bug defect mode is characterized in that, this method comprises:
A, read the security breaches detected state machine description document of tested program source code file and software security flaw pattern correspondence, described tested program is carried out pre-service and resolved security breaches detected state machine description document, and tested program carried out lexical analysis and grammatical analysis, generate the abstract syntax tree of tested program;
B, according to the abstract syntax tree of being constructed, generate the control flow graph of reflection tested program control structure and according to the abstract syntax tree of being constructed, and create the symbol table of tested program;
C, 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; Wherein, the process of the described ud/du of foundation chain is stored in the ud chain, is kept in the du chain by preserving all possible use tabulation of current definition for the use relation that will define by the use to the assignment of variable and variable, and described ud/du chain is used for confession security breaches detected state machine and calls;
D, 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; Wherein, described ud/du chain according to described foundation carries out the process of software vulnerability test for according to function calling relationship figure the control flow graph being traveled through to program code, and according in the security breaches detected 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 Hole Detection state machine on the calculation control flow graph, if security breaches detected state machine enters the software defect state, the checkpoint IP of then report correspondence.
2. detection method according to claim 1 is characterized in that, described tested program source code file is Java language or C/C++ language.
3. detection method according to claim 1 is characterized in that, described software security flaw mode type comprises:
Not verified input pattern is used to describe the input that some do not have checking, directly the security breaches of calling as function parameters;
Abuse application programming interfaces API pattern is used to describe the leak that those are trusted the side of being called mistakenly and caused by caller;
The security feature defect mode is used to describe for information about the security breaches of the related authentication of safety, access mechanism, confidentiality guarantee, cryptographic algorithm, rights management aspect;
The race condition pattern is used for describing the security breaches that the Distributed Calculation process resource sharing aspect relevant with time and state exists;
Irrational abnormality processing pattern is used to describe the safety bug defect relevant with error handling processing;
The inferior quality code pattern is used to describe the not good enough security breaches that can't expect that cause of software quality;
Encapsulate improper pattern, the security breaches when being used for the related system variable of described function, system resource and user profile and operating.
4. method according to claim 1 is characterized in that, steps A described to described tested program carry out pretreated process for to carry out macro substitution to tested program before testing, file comprises and conditional compilation.
5. method according to claim 1, it is characterized in that, the described parsing security breaches of steps A detected state machine description document, for utilizing analysis program that described security breaches detected state machine description document is resolved in the subsequent treatment internal storage data structure that security breaches pattern analysis engine can be discerned.
6. method according to claim 1 is characterized in that, the described process of lexical analysis that tested program is carried out of steps A is for being converted to tested program the mark stream that can carry out grammatical analysis.
7. method according to claim 1, it is characterized in that, the process of the control flow graph of the described generation reflection of step B tested program control structure is: obtain by adopting visitor's pattern traversal abstract syntax tree, its method is on the basis of traversal abstract syntax tree, generates the visitor by a control flow graph and realizes; The way that described visitor adopts recurrence to descend generates the control flow graph, 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.
8. method according to claim 1 is characterized in that, described 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.
CN2009100030824A 2009-01-19 2009-01-19 Detection method based on safety bug defect mode Expired - Fee Related CN101482847B (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
CN2009100030824A CN101482847B (en) 2009-01-19 2009-01-19 Detection method based on safety bug defect mode

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
CN2009100030824A CN101482847B (en) 2009-01-19 2009-01-19 Detection method based on safety bug defect mode

Publications (2)

Publication Number Publication Date
CN101482847A CN101482847A (en) 2009-07-15
CN101482847B true CN101482847B (en) 2011-06-29

Family

ID=40879966

Family Applications (1)

Application Number Title Priority Date Filing Date
CN2009100030824A Expired - Fee Related CN101482847B (en) 2009-01-19 2009-01-19 Detection method based on safety bug defect mode

Country Status (1)

Country Link
CN (1) CN101482847B (en)

Families Citing this family (68)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN101706749B (en) * 2009-11-18 2011-12-21 电子科技大学 Comprehensive processing method based on software safety defect detection
CN101937388B (en) * 2009-12-17 2013-03-13 High-extensibility and high-maintainability source code defect detection method and device
CN101866302B (en) * 2010-06-12 2013-08-21 中兴通讯股份有限公司 Device and method for testing applicability of application mode
CN101908006B (en) * 2010-07-30 2011-12-14 北京理工大学 GCC abstract syntax tree-based buffer overflow vulnerability detection method
CN101937499B (en) * 2010-09-19 2013-03-06 深圳创维-Rgb电子有限公司 Method and device for detecting hidden loophole and Linux operating system
CN101937396B (en) * 2010-09-30 2012-07-11 中国科学院软件研究所 Detecting method of unsafe variable use in software program
CN101964036B (en) * 2010-10-29 2013-01-16 深圳市安盾椒图科技有限公司 Leak detection method and device
CN102279800A (en) * 2011-08-31 2011-12-14 中国信息安全测评中心 Source code static defect analyzer and method for processing path-sensitive symbol definition
CN102521079B (en) * 2011-12-02 2014-06-04 华中科技大学 Fault-tolerant method of software stack buffer overflow
CN102567183B (en) * 2011-12-08 2014-10-22 清华大学 Tainted variable tracking method
CN102750220B (en) * 2011-12-31 2015-06-17 中国信息安全测评中心 Method and device for analyzing safety defects of software source code
CN102708055B (en) * 2012-05-14 2014-08-06 中国联合网络通信集团有限公司 Method and device for testing credibility of software
CN103455759B (en) * 2012-06-05 2017-03-15 深圳市腾讯计算机系统有限公司 A kind of page Hole Detection device and detection method
CN102693396B (en) * 2012-06-11 2014-09-17 中南大学 Flash bug detection method based on virtual execution mode
CN103577758B (en) * 2012-07-31 2017-05-31 西门子公司 The code verification method and device of program
CN102945203B (en) * 2012-10-26 2016-04-13 深圳出入境检验检疫局信息中心 A kind of code security method of testing for mobile Internet application
US9426177B2 (en) 2013-07-15 2016-08-23 Tencent Technology (Shenzhen) Company Limited Method and apparatus for detecting security vulnerability for animation source file
CN104298921B (en) * 2013-07-15 2019-01-29 深圳市腾讯计算机系统有限公司 Animation source file security breaches inspection method and device
CN104657162A (en) * 2013-11-21 2015-05-27 腾讯科技(深圳)有限公司 Service environment modification method and device
CN103729244B (en) * 2013-12-17 2017-04-26 华为技术有限公司 Collection method and collection device
CN104021084A (en) * 2014-06-19 2014-09-03 国家电网公司 Method and device for detecting defects of Java source codes
US9690552B2 (en) * 2014-12-27 2017-06-27 Intel Corporation Technologies for low-level composable high performance computing libraries
CN104573503B (en) * 2015-02-11 2018-04-27 中国农业银行股份有限公司 The detection method and device that a kind of internal storage access overflows
CN106295346B (en) * 2015-05-20 2022-08-30 深圳市腾讯计算机系统有限公司 Application vulnerability detection method and device and computing equipment
CN104899147B (en) * 2015-06-19 2017-11-28 北京理工大学 A kind of code Static Analysis Method towards safety inspection
CN105022958B (en) * 2015-07-11 2018-01-12 复旦大学 Vulnerability of application program determination method based on code library secure protocol in a kind of Android application
CN105159828B (en) * 2015-08-25 2018-02-02 中国人民解放军信息工程大学 The context sensitivity detection method of source code level
US9749357B2 (en) * 2015-09-05 2017-08-29 Nudata Security Inc. Systems and methods for matching and scoring sameness
WO2017068889A1 (en) * 2015-10-19 2017-04-27 日本電信電話株式会社 Analysis device, analysis method, and analysis program
CN106227668B (en) * 2016-07-29 2017-11-17 腾讯科技(深圳)有限公司 Data processing method and device
CN106294156B (en) * 2016-08-11 2018-12-07 北京邮电大学 A kind of static code fault detection analysis method and device
CN106407104B (en) * 2016-08-24 2018-12-04 北京奇虎测腾安全技术有限公司 It is a kind of for detecting the method and system for discharging relevant defect to memory headroom
CN106371997B (en) * 2016-09-07 2020-01-10 网易(杭州)网络有限公司 Code checking method and device
CN106357664B (en) * 2016-09-30 2020-07-21 北京奇虎科技有限公司 Vulnerability detection method and device
CN106503563B (en) * 2016-10-17 2019-03-08 成都知道创宇信息技术有限公司 Batch leak detection method based on general framework
CN106572117B (en) * 2016-11-11 2019-10-18 北京安普诺信息技术有限公司 A kind of detection method and device of WebShell file
CN107943481B (en) * 2017-05-23 2021-01-26 清华大学 C language program code specification construction method based on multiple models
CN109214188B (en) * 2017-06-30 2022-05-27 阿里巴巴集团控股有限公司 Vulnerability analysis method and device and data processing method and device
CN107516040A (en) * 2017-07-25 2017-12-26 中国人民解放军63928部队 A kind of Vulnerability Characteristics analysis and acquisition methods based on data controlling stream graph
CN107506299B (en) * 2017-08-09 2021-04-02 平安科技(深圳)有限公司 Code analysis method and terminal equipment
CN109558332B (en) * 2017-09-26 2022-10-25 北京金山安全软件有限公司 Object recovery method and device, electronic equipment and storage medium
CN107886000B (en) * 2017-11-13 2019-11-22 华中科技大学 A kind of software vulnerability detection method, response at different level method and software bug detection system
CN108446121A (en) * 2018-02-28 2018-08-24 华东师范大学 A kind of automatic verification method of structured text program
CN109408034B (en) * 2018-03-17 2022-02-15 东南大学 Control flow graph construction method for object-oriented program
CN109002712B (en) * 2018-06-22 2020-11-03 北京大学 Pollution data analysis method and system based on value dependency graph and electronic equipment
CN109165161A (en) * 2018-08-30 2019-01-08 北京轩宇信息技术有限公司 A kind of analysis method for local variable data contention in C51 LISP program LISP
CN109325353A (en) * 2018-11-01 2019-02-12 南京邮电大学 A kind of cluster leak analysis method for home router
CN109828923B (en) * 2019-01-22 2022-02-01 西安微电子技术研究所 Non-atomic instruction sequence prototype verification method based on application program structure
CN110059006B (en) * 2019-03-29 2020-07-07 北京创鑫旅程网络技术有限公司 Code auditing method and device
CN110162474B (en) * 2019-05-10 2020-09-15 北京理工大学 Intelligent contract reentry vulnerability detection method based on abstract syntax tree
CN110442330B (en) * 2019-07-05 2023-07-21 五八有限公司 List component conversion method and device, electronic equipment and storage medium
CN110545264B (en) * 2019-08-16 2021-09-03 苏州浪潮智能科技有限公司 Method and device for automatically detecting LDAP authentication injection vulnerability
CN110471662B (en) * 2019-08-21 2023-04-25 北京百度网讯科技有限公司 Program conversion method, device and equipment
CN110674495B (en) * 2019-09-03 2021-07-09 Xc5 香港有限公司 Detection method, device and equipment for group border crossing access
CN110955898A (en) * 2019-12-12 2020-04-03 杭州安恒信息技术股份有限公司 Vulnerability auditing method and system of station building system and related device
CN111240719B (en) * 2020-01-23 2021-08-20 复旦大学 Defect-driven third-party library version upgrade recommendation method
CN111291373B (en) * 2020-02-03 2022-06-14 思客云(北京)软件技术有限公司 Method, apparatus and computer-readable storage medium for analyzing data pollution propagation
CN111625446B (en) * 2020-04-30 2023-05-23 库卡机器人制造(上海)有限公司 Software testing method and device, computer readable medium and electronic equipment
CN112256271B (en) * 2020-10-19 2022-11-29 中国科学院信息工程研究所 Block chain intelligent contract safety detection system based on static analysis
CN112422515B (en) * 2020-10-27 2023-03-21 锐捷网络股份有限公司 Protocol vulnerability testing method and device and storage medium
CN112347486A (en) * 2020-11-30 2021-02-09 山东浪潮商用系统有限公司 Code vulnerability examination method and device for realizing privacy protection and readable medium
CN112291275B (en) * 2020-12-25 2021-03-26 远江盛邦(北京)网络安全科技股份有限公司 Command interaction implementation method for CVE vulnerability penetration utilization
CN112965851A (en) * 2021-03-30 2021-06-15 建信金融科技有限责任公司 Memory overflow processing method and device, electronic equipment and storage medium
CN112968914B (en) * 2021-05-18 2021-10-15 北京仁科互动网络技术有限公司 System, method, device and medium for requesting data to be imported into vulnerability scanner in real time
CN112989363B (en) * 2021-05-19 2021-09-28 北京邮电大学 Vulnerability positioning method and device, electronic equipment and storage medium
CN113190374A (en) * 2021-06-30 2021-07-30 四川新网银行股份有限公司 Application fault transfer system and method based on mysql MGR
CN113568607B (en) * 2021-08-09 2023-11-07 软子数字软件(广州)有限公司 Digital program implementation method and system
CN115913655B (en) * 2022-10-28 2024-05-14 华中科技大学 Shell command injection detection method based on flow analysis and semantic analysis

Citations (1)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN101286132A (en) * 2008-06-02 2008-10-15 北京邮电大学 Test method and system based on software defect mode

Patent Citations (1)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN101286132A (en) * 2008-06-02 2008-10-15 北京邮电大学 Test method and system based on software defect mode

Non-Patent Citations (4)

* Cited by examiner, † Cited by third party
Title
孙茜.基于静态检测的程序安全漏洞测试.北京化工大学学报.2007,349-12. *
杨朝红.基于缺陷模式的软件测试中的区间运算应用.计算机辅助设计与图形学学报.2008,20(12),1630-1635. *
杨朝红.基于软件缺陷模型的测试系统.北京邮电大学学报.2008,31(5),1-4. *
王德胜.论软件缺陷.计算机应用研究.2008,25(12),3531-3533. *

Also Published As

Publication number Publication date
CN101482847A (en) 2009-07-15

Similar Documents

Publication Publication Date Title
CN101482847B (en) Detection method based on safety bug defect mode
Livshits et al. Towards fully automatic placement of security sanitizers and declassifiers
Doupe et al. deDacota: toward preventing server-side XSS via automatic code and data separation
Koishybayev et al. Mininode: Reducing the attack surface of node. js applications
Liang et al. Sound and precise malware analysis for Android via pushdown reachability and entry-point saturation
Mercaldo et al. Download malware? no, thanks: how formal methods can block update attacks
Møller et al. Automated detection of client-state manipulation vulnerabilities
Tevis et al. Methods for the prevention, detection and removal of software security vulnerabilities
Zhang et al. Condysta: Context-aware dynamic supplement to static taint analysis
Gajrani et al. Vulvet: Vetting of vulnerabilities in android apps to thwart exploitation
Lin et al. Reuse-oriented camouflaging trojan: Vulnerability detection and attack construction
Zhang et al. Detecting and understanding JavaScript global identifier conflicts on the web
Cavalli et al. Design of a secure shield for internet and web-based services using software reflection
Ohm et al. You Can Run But You Can't Hide: Runtime Protection Against Malicious Package Updates For Node. js
Nirumand et al. A model‐based framework for inter‐app Vulnerability analysis of Android applications
Aloraini et al. Evaluating state-of-the-art free and open source static analysis tools against buffer errors in android apps
Yoshihama et al. Dynamic information flow control architecture for web applications
Cho et al. Runtime input validation for Java web applications using static bytecode instrumentation
Lu et al. Detecting missing-permission-check vulnerabilities in distributed cloud systems
Jula et al. Communix: A framework for collaborative deadlock immunity
Goichon et al. Static vulnerability detection in Java service-oriented components
Graa et al. Formal characterization of illegal control flow in android system
Chen et al. STELLA: sparse taint analysis for enclave leakage detection
Cui et al. Container‐Based Privacy Preserving Scheme for Android Applications
Randevik et al. Secarchunit extending archunit to support validation of security architectural constraints

Legal Events

Date Code Title Description
C06 Publication
PB01 Publication
C10 Entry into substantive examination
SE01 Entry into force of request for substantive examination
C53 Correction of patent for invention or patent application
CB03 Change of inventor or designer information

Inventor after: Gong Yunzhan

Inventor after: Liu Chuanchang

Inventor after: Chen Junliang

Inventor after: Yang Chaohong

Inventor after: Xiao Qing

Inventor after: Jin Dahai

Inventor after: Li Feiyu

Inventor before: Gong Yunzhan

Inventor before: Chen Junliang

Inventor before: Yang Chaohong

Inventor before: Xiao Qing

Inventor before: Jin Dahai

Inventor before: Li Feiyu

COR Change of bibliographic data

Free format text: CORRECT: INVENTOR; FROM: GONG YUNZHAN CHEN JUNLIANG YANG ZHAOHONG XIAO QING JIN DAHAI LI FEIYU TO: GONG YUNZHAN LIU ZHUANCHANG CHEN JUNLIANG YANG ZHAOHONG XIAO QING JIN DAHAI LI FEIYU

C14 Grant of patent or utility model
GR01 Patent grant
CF01 Termination of patent right due to non-payment of annual fee

Granted publication date: 20110629

Termination date: 20200119

CF01 Termination of patent right due to non-payment of annual fee