At the code level, that is, if you consider code security at the application level (that is, you do not consider vulnerabilities in the underlying language itself), the script security issue is the issue of functions and variables. At the code level, that is, if you consider code security at the application level (that is, you do not consider vulnerabilities in the underlying language itself), the script security issue is the issue of functions and variables.
I. Preface
At the code level, that is, if you consider code security at the application level (that is, you do not consider vulnerabilities in the underlying language itself), the script security issue is the issue of functions and variables. Variables directly or indirectly receive insecure user input. due to the characteristics of php, in php, it is easier to find the chaos of such variables (many php programs are used to define, initialize, and receive variables, and $ id variables can be directly used in the program, initialization is completely completed by php settings. if you do not pay attention to it, it may lead to variable confusion and attack ).
When a variable receives insecure input, it is not properly filtered and used in different places, which may cause different dangers. If you directly access the database and display it to the user, it will lead to cross-site scripting attacks. if you use it in SQL statements, it may lead to SQL injection attacks, these attacks are irrelevant to specific scripting languages and may exist in various scripting languages. Due to the flexibility of php variables, if these harmful variables are used in some logical statements, this will cause key code skipping, such as failed authentication and skipping variable initialization, resulting in program logic confusion and other vulnerabilities. If this variable is used in dangerous functions such as include, the file inclusion vulnerability may occur, and the file write vulnerability may occur in the fopen function, the SQL injection vulnerability occurs in the mysql_query function. eval and preg_replace may cause code execution, the environment that may cause errors in the htmlspecia function and absolute path leakage variables determines its potential harm.
After thinking about the problem, how can we check this vulnerability at the code level? Of course, familiarity with the php language is the most basic. It should also be to grasp the functions and variables. if there is a variable in a dangerous function, please determine the source of the variable and whether it is correctly initialized, whether the user can inject sensitive characters after initialization, and whether these sensitive characters are completely cleared before entering the function. The difficulty in code review may be the determination of the variable source, which requires familiarity with php features and the code you have reviewed, however, not all sources of variables are clearly visible. some initialization code may not run as expected, some variables may also come from places you don't want them to come, and some variables may come from database or system configuration files, however, it is very likely that the database and configuration file have been modified before, or these variables are not operated securely in the future. these variables are also untrustworthy. Next we will consider the security of script code based on the ideas of variables and functions.
Where does the binary variable come from?
1 displayed input
Where the variables come from, that is, where the threats come from. what kind of website is the most secure if we only consider the web? Obviously, websites that only provide static Html pages are the safest, because such websites do not interact with viewers, it is like robbing a bank that is hard to crack, it is difficult to implement, but it is different for a large forum or script program. when you log on, you need to pass the username and password variables to the server, even the Ip address you log on to and the browser are all objects captured by the program. capture the interaction process with the server, such as posting a post, and you will find that data transmission between the browser and the server is performed, what you may see includes submitted forms, address bar parameters, and so on. what you cannot see includes cookies. the Http header is where data is submitted, that is, the variable. These locations are also the most primitive portals for servers to process data. So how does the php program accept variables? All submitted variables are saved in some arrays by php, including
$ _ GET
$ _ POST
$ _ COOKIE
$ _ FILES
$ _ SERVER
For initial convenience and flexibility, this option is available in php settings.
Register_globals
When this option is on, all the variables shown above will become a member of $ GLOBALS, which can be used directly without being obtained in the script.
Variables_order
. Many programs consider that register_globals is off, so the following code is used during program initialization:
@ Extract (daddslashes ($ _ POST ));
@ Extract (daddslashes ($ _ GET ));
These codes play the role of register_globals. they release POST and GET content as global variables, but the risks may be even greater.
2. implicit input
The above are the most primitive data that has not been converted by the program. The variables used in many parts of the program come from here, but it does not mean that no variables are transmitted elsewhere, the following is a data transmission mode:
User-transmitted data ==========> database ========> program code processing ======> program code
This mode means that user input may first enter the database, and then the program obtains the input from the database and sends it to some dangerous function execution, programmers generally think that the variables obtained from the database are safe, but this is not the case. as long as some sensitive characters are finally sent to the program code, no matter where he stays, it is dangerous. Similar to the situations stored in a database, some programs put user input into files, such as cache files, and then obtain them from them when necessary, if you believe in the variables from these places too much, this will still lead to problems.
3. variable overwrite
In many cases, the variables received by the program may come from the places where they should not come, such as the Dz code:
$ Magic_quotes_gpc = get_magic_quotes_gpc ();
@ Extract (daddslashes ($ _ POST ));
@ Extract (daddslashes ($ _ GET ));
If (! $ Magic_quotes_gpc ){
$ _ FILES = daddslashes ($ _ FILES );
}
After that, do you still think $ _ FILES is the original $ _ FILES? If we create a _ FILES form or simply add php to the url? _ FILES [] = ddddd. then, $ _ FILES is completely overwritten, and the $ _ FILES referenced in your code is not the original one, this problem has occurred in earlier versions of Dz. This should be a problem of variable overwrite. let's enlarge the initialized file:
The code is as follows:
$ Magic_quotes_gpc = get_magic_quotes_gpc ();
@ Extract (daddslashes ($ _ POST ));
@ Extract (daddslashes ($ _ GET ));
If (! $ Magic_quotes_gpc ){
$ _ FILES = daddslashes ($ _ FILES );
}
$ Charset = $ dbcharset = '';
$ Plugins = $ hooks = array ();
Require_once DISCUZ_ROOT. './config. inc. php ';
Require_once DISCUZ_ROOT. './include/db _'. $ database. '. class. php ';
If ($ attackevasive ){
Require_once DISCUZ_ROOT. './include/security. inc. php ';
}
This seems to be okay, but if certain conditions are met, problems may still occur. if register_globals is on, let's enter the global variables not just $ _ GET and $ _ POST! $ _ COOKIE, $ _ FILES, and $ _ SERVER all generate variables in the global array. through the above statement, we submit a php? _ SERVER [PHP_SELF] can overwrite the _ SERVER array, so the $ _ SERVER array in the entire program cannot be believed. I have also seen the code written like this:
The code is as follows:
Require_once ROOT_PATH. 'Inc/database_config.php ';
Require_once
ROOT_PATH. 'Inc/dv_spacemain.php ';
If (PHP_VERSION <'4. 1.0 '){
$ _ GET = & $ HTTP_GET_VARS;
$ _ POST = & $ HTTP_POST_VARS;
$ _ COOKIE = & $ HTTP_COOKIE_VARS;
$ _ SERVER = & $ HTTP_SERVER_VARS;
$ _ ENV = & $ HTTP_ENV_VARS;
$ _ FILES = & $ HTTP_POST_FILES;
$ _ SESSION = & $ HTTP_SESSION_VARS;
}
$ Magic_quotes_gpc = get_magic_quotes_gpc ();
$ Register_globals = @ ini_get ('register _ globals ');
If (! $ Register_globals |! $ Magic_quotes_gpc ){
@ Extract (I _addslashes ($ _ POST ));
@ Extract (I _addslashes ($ _ GET ));
@ Extract (I _addslashes ($ _ COOKIE ));
If (! $ Magic_quotes_gpc ){
$ _ FILES = I _addslashes ($ _ FILES );
}
}
It is also in the system initialization, but the release of the variable is in
Require_once ROOT_PATH. 'Inc/general_funcs.php ';
Require_once ROOT_PATH. 'Inc/dv_spacemain.php ';
After these key variables are initialized, can we submit one? $ Host = xxx. xxx overwrites the database address variable in the system's own database initialization file, and then you can
4. variable infection
It is easy to understand that when a variable is insecure, the related operations such as assignment are insecure, such:
$ Id = $ _ GET [id];
..
$ Articleid = $ id;
The actual process may not be so obvious, but the results are the same. as long as a variable brings sensitive characters into a place that shouldn't be included, it will generate a threat, not just a variable, unsafe functions make all the code using this function insecure.
2. insecure
The variable is finally to be processed by code, and the code is ultimately executed by some system functions and statements. incorrect variables appear in dangerous functions. Congratulations!
1. SQL Injection Vulnerability: According to our understanding, there are insecure variables in SQL functions. There are many statements executed in php in the system, the following code is available in the Dz initialization file:
If ($ sid ){
If ($ discuz_uid ){
$ Query = $ db-> query ("SELECT s. sid, s. styleid, s. groupid = '6' AS ipbanned, s. pageviews AS spageviews, s. lastolupdate, s. seccode, m. uid AS discuz_uid,
M. username AS discuz_user, m. password AS discuz_pw, m. secques AS discuz_secques, m. adminid, m. groupid, m. groupexpiry,
M. extgroupids, m. email, m. timeoffset, m. tpp, m. ppp, m. posts, m. digestposts, m. oltime, m. pageviews, m. credits, m. extcredits1, m. extcredits2, m. extcredits3,
M. extcredits4, m. extcredits5, m. extcredits6, m. extcredits7, m. extcredits8, m. timeformat, m. dateformat, m. pmsound,
M. sigstatus, m. invisible, m. lastvisit, m. lastactivity, m. lastpost, m. newpm, m. accessmasks, m. xspacestatus, m. editormode, m. customshow
FROM {$ tablepre} sessions s, {$ tablepre} members m
WHERE m. uid = s. uid AND s. sid = '$ sid' AND CONCAT_WS ('. ', s. ip1, s. ip2, s. ip3, s. ip4) = '$ onlineip' AND m. uid = '$ discuz_uid'
AND m. password = '$ discuz_pw' AND m. secques = '$ discuz_secques '");
} Else {
$ Query = $ db-> query ("SELECT sid, uid AS sessionuid, groupid, groupid = '6' AS ipbanned, pageviews AS spageviews, styleid, lastolupdate, seccode
FROM {$ tablepre} sessions WHERE sid = '$ sid' AND CONCAT_WS ('.', ip1, ip2, ip3, ip4) = '$ onlineip '");
Find the us circle symbol in the $ db-> query function. ha, there are several, that is, there may be vulnerabilities. Note that it is possible, because the security of the current code has been improved, it is not easy to find a variable that nobody cares about. Generally, the variables will be correctly tested, however, when tracking the $ onlineip variable, we can find that this variable is basically unmanageable, because it is extracted from the Http header. Generally, people do not pay much attention to this, but the problem occurs :)
It should be noted that a function has a vulnerability. no matter what the statement is, we can control the variable as long as it appears in update, insert, or select, and changing the volume can break through some restrictions of the program (what restrictions will be discussed later) to control the execution of this SQL statement, then our vulnerability is true. whether it can be used depends on the specific environment.
2 Xss cross-site scripting vulnerability: This vulnerability is rooted in the client's Html injection vulnerability. if the user submits variables that contain <> or can be interpreted as Html characters, then output data from the database to the browser of the browser, the Xss injection vulnerability may exist. <> Characters can cause cross-site scripting attacks to be well understood, but note that you do not need to submit them <> This problem occurs, which is misunderstood by many people. Assume that our input, such as a url, is eventually placed in an Html tag. There are many such cases, because the user's profile picture must be in the following format:
Echo ""
We have controlled the img attributes and implemented cross-site scripting attacks.
3. file inclusion vulnerability: This is mainly because there are no restrictions on the parameters of functions such as include and require in the file. as a result, you can specify the files to be included as follows:
Require_once ROOT_PATH. "cache/style/$ cssname. php ";
If we can control $ cssname, we can control the content to be included. the existence of the vulnerability depends on whether this variable can be controlled. if it can be controlled, it can be used again .. /jump, then: As for the dangers, that is, arbitrary code execution and directory traversal.
4. webshell write vulnerability: This is widely seen in some text databases. some programs use text files as databases, so they inevitably need to use functions such as fopen, fread, and fwrite. let's take a look at the help of opening fopen functions:
Resource fopen (string filename, string mode [, bool use_include_path [, resource zcontext])
From this help, we can know that if the first parameter of the fopen function can be controlled, some files that should not be opened may be opened. Other file functions are like examples. I would like to reiterate again, the environment of the variable determines its value :)
5. code execution vulnerability: Functions that can generate such vulnerabilities must have such functions. common functions include the eval function and the preg_replace function. if the eval contains statements that can be controlled, problems may occur, the second parameter in the preg_replace function may cause arbitrary code execution problems!
6. absolute path leakage: This is mainly caused by php errors. mysql Query errors occur when a non-existent file is used. submitting a non-conforming parameter to some functions will cause this problem, in general, programs use @ to suppress function errors, but there are still some methods to crack the path! Some people say that a path cannot represent anything. In fact, a path can know the operating system, the path, and the configuration of the virtual host. ,
7 logical chaos
If a variable is used in logic statements such as if, it may cause logical confusion and skip the execution of some statements.
Problems with other functions
3. filtering and raster filtering
Many people have noticed these security issues. php also includes its own security mechanism, that is, when GPC = On, it adds escape to 'and "and, many programs also add these escape characters. This mechanism may not be available in other scripting languages, but it is a good idea. When escaped, it can ensure that all user input is a string, no matter where the variable enters, including SQL queries, cross-site scripts, etc, however, a very important premise is that the program you write must treat all input as strings. Obviously, if there are two statements:
$ Query = $ db-> query ("select * from user where uid = $ id ");
$ Query = $ db-> query ("select * from user where uid = '$ ID '");
Which one is safer? The first statement assumes that $ id is a numeric variable, and the second assumes that the input is a character variable, so ''is used to reference it. If php? Id = 1 and 1 = 2 for the first statement, the result is:
Select * from user where uid = 1 and 1 = 2 // and 1 = 2 becomes an expression
Select * from user where uid = '1 and 1 = 2' // and 1 = 2 or a part of the string
I hope this will give you some tips, but not just SQL injection! If it is a cross-site scripting vulnerability, we can also use the above ideas, no matter what the user inputs, filtering well <>, and then just treat the user input as a string, however, it should be noted that an escape character \ 'may still be meaningful in html. you need to remove the escape character in html and use the htmlspecialchars () function, of course, we also need to work with the program security code to give two examples:
Echo "";
Echo "";
Which one has no defect?
The above example implies that if a variable can only be used as a string, it should not be given a specific meaning, and it cannot do anything. You may have thought that, for the vulnerabilities mentioned above, if you are forced to require user control variables, you only need to filter out special characters and then use the input as a string, then you can eliminate these vulnerabilities at the code level. For example, for the fopen function, we only need to filter it out .. /and .. \, and then escape the "," and empty characters entered by the user, for webshell writing, you can escape the script flag characters by creating a database, if a php file is generated, you can restrict user input to ''or" ". everything is only a character, which is similar to the defense of XSS! Some sensitive characters may be generated by the program itself, as shown in the following code:
$ Deldb = explode ("|", $ imgdb ['Icon ']);
It gives $ imgdb ['Icon '] a sacred meaning, so we must first clean the | in $ imgdb ['Icon'] during processing!
4. Other problems
What I mentioned above is just some ideas about how to detect and fix vulnerabilities. I started to analyze variable processing from functions, but in more cases, program security depends on the clear thinking of programmers, but security is not just like this, such as the encoding of GBK and Big5, as well as uploading. The Php script is like this, and other scripts are like this.