1. Code injection
1.1 Command Injection
Refers to a portion of the command injection application execution command string or strings from untrusted sources, these programs no untrusted authentication, filtering, lead to a malicious attack command execution.
Code in question:
$dir = $_POST['dir']
exec("cmd.exe /c dir" + $dir);
Rehabilitation program:
(1) procedures for user input data from non-trusted purify, remove unsafe characters.
(2) defining the type of input, to create a secure string list, the user can input data to limit the list. Repair examples:
//方式1 if (!preg_match('/^[\w\.:\-]+$/', $dir) ){ // Handle error } $cmd = filter_var($cmd, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => getCommandFilterReg()))); ... $msg = escapeshellarg($msg); //方式2 function cmd_arg($cmd, $filter='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.') { $filter_chars = str_split($filter); $filter_chars = array_combine($filter_chars, $filter_chars); $cmd_chars = str_split($cmd); $ret = ''; foreach ($cmd_chars as $v) { $ret .= isset($filter_chars[$v]) ? $filter_chars[$v] : ''; } return $ret; } $cmd = cmd_arg($cmd);
1.2 js dynamic code injection
(1) The front end uses mainly eval function to parse the server response
evalResponse: function() { try { return eval((this.transport.responseText )); } catch (e) { this.dispatchException(e); }
Rehabilitation program:. A Do not use the eval function, use a custom function to replace
function _dhtmlxEvalData( code ) { var script; if ( code ) { var data_key = '_process_json_data_'+parseInt( rand(0,1000000000000)); code = 'window["'+data_key+'"]=('+code+');' // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); return window[data_key]; } return null; } return _dhtmlxEvalData(this.transport.responseText );
(2) document.write (html) written in html document.location = url and the filtering process is not url
var html = '<span>'+rows[i]+'</span>'; document.write(html) .... document.location = url
Repair scheme: a document.write be avoided. Reference address
b whitelist.
//document.write() 换成如下写法 _var sNew = document.createElement("script"); sNew.async = true; sNew.src = "https://example.com/script.min.js"; var s0 = document.getElementsByTagName('script')[0]; s0.parentNode.insertBefore(sNew, s0); //document.location = url的处理 function safe_url (url, whiteChars) { whiteChars = ''+(whiteChars||'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.-_~+#,%&=*;:@[]'); var ret = ''; for(var i=0; i<url.length; i++) { ret += whiteChars[whiteChars.indexOf(url[i])] || ''; were old = K; { Do } ret = ret.replace(/javascript:/gi,''); }while(ret != old); return ret; } document.location = safe_url(url);
(3) the received global variables and functions to meet setTimeout
Code in question:
this.timer = setTimeout(this.onTimerEvent.bind(this), this.decay * this.frequency * 1000); ... (u = setTimeout(function() { x.abort("timeout") }, c.timeout));
Repair scheme: use anonymous functions, wrapped setTimeout function
(function(){ this.timer = setTimeout(this.onTimerEvent.bind(this), this.decay * this.frequency * 1000); })(); ... (u = (function() { var u = setTimeout(function() { x.abort("timeout") }, c.timeout); return u; })() );
1.3 JSON injection
Code in question:
$data = file_get_contents("php://input"); $data = json_decode($data, true);
Repair scheme: filtering function using filter_var repair example:
$data = file_get_contents("php://input"); $data = filter_var($data, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES); $data = json_decode($data, true);
1.4 SQL injection
The reason SQL injection occurs:
1, data from a data source into the untrusted program.
2, the data used to dynamically construct a SQL query.
Code in question:
$sql = "SELECT value FROM config WHERE ip=".$ip." AND owner=".$_SESSION["user"]; $stm->execute(); $stm->fetchAll(PDO::FETCH_ASSOC);
Rehabilitation program:
a, ensure not constructed by concatenating sql statement;
B, then use some method for performing sql statement precompiled;
C, and finally bound in the manner set parameter values required conditions sql statement.
Repair examples:
$sql = "SELECT value FROM config WHERE ip=? AND owner=?"; $stm = $db->prepare($sql); $stm->execute(array($ip, $_SESSION["user"])); $rows = $stm->fetchAll(PDO::FETCH_ASSOC);
2. insecure random number
Standard pseudo-random value generator can not resist various cryptographic attacks. Pseudo-random number generator (PRNG) approximates random algorithm, a statistical PRNG, the PRNG is portable and repeatable, the attacker can easily guess the strings it generates. In high security requirements of the environment, a function capable of generating random data as the predicted value of the source, will generate an error Insecure Randomness.
2.1 php example
Code using the rand () and the mt_rand () function, related to learn
mt_srand(time()); $token = mt_rand(); ... $randnum = rand(1,10000); $str = md5($token.$randnum.time()); ...
Rehabilitation program: 1.php7 adds better random number random_int () is used instead of php5 of mt_rand ()
2. re-use openssl_random_pseudo_bytes custom function random function, pay attention to the operating environment needs to support this function
Repair examples:
f
unction dynamicNumber($min,$max) { $range = $max - $min + 1; if ($range == 0) return $min; $length = (int) (log($range,2)/8) + 1; $max = pow(2, 8 * $length); $num = $max + 1; while ($num > $max) { $num = hexdec(bin2hex(openssl_random_pseudo_bytes($length,$s))); } return ($num % $range) + $min; } function getDynamicInt($min = 0, $max = null) { if ($max === null) { $max = getrandmax(); } return dynamicNumber($min,$max); } function getDynamicMtInt($min = 0, $max = null) { if ($max === null) { $max = mt_getrandmax(); } return dynamicNumber($min,$max); } $token = getDynamicMtInt(); ... $randnum = getDynamicInt(1,10000);
2.2 js examples
Code used Math.random ()
... var rnd = Math.random, (),; ...
Repair scheme: not used Math.random (), the principle of the reference self-repair function defined random examples:
var rand = (function(){ var seed = (new Date()).getTime() function r(){ seed = (seed*9301+49297)%233280 return seed/(233280.0) } return function(number){ return Math.ceil(r()*number) } })() console.log(rand(5)); function randnum() { var seed = (new Date()).getTime(); seed = (seed*9301+49297)%233280; return seed/(233280.0); }
3. The hard-coded password
The program is hard-coded passwords process, reduces system security on the one hand, on the other hand is not easy to program maintenance.
if (password == null) { password = "123456"; }
fortify may be false, such as some variable with keywords: password, passwd, pass, password_xxx, xxx_passwd etc.
Repair mode: Program the desired password should be encrypted configuration file to obtain the password value. For variable false positives, only modify the variable name.
4. Other
1. Empty password problem
In fact, only variable is set to empty, but to fortify error
passwd = $ ""; // solution with function into an empty $ passwd = strval (null);
2. Variable coverage
Extract ($ params) // instead extract ($ params, EXTR_SKIP);
3.base64_pri_decrypt () method performs public-key encryption RSA OAEP without stuffing mode, encryption mechanism so fragile.
openssl_public_encrypt($input, $output, $key, OPENSSL_NO_PADDING); =》 openssl_private_decrypt($password_base64_decode, $password_decode, $pi_key,OPENSSL_PKCS1_OAEP_PADDING);//私钥解密
4.js dynamic packet code injection setTimeout
this.timer = setTimeout(this.onTimerEvent.bind(this), this.decay * this.frequency * 1000);
Anonymous function to wrap
(function(){ this.timer = setTimeout(this.onTimerEvent.bind(this), this.decay * this.frequency * 1000); })();
Example 2:
(u = setTimeout(function() { x.abort("timeout") }, c.timeout)); 改为
(u = (function() { var u = setTimeout(function() { x.abort("timeout") }, c.timeout); return u; })() );
5.Cookie Security: Overly Broad Path path 不传“/”
6..xss,css Dom
safe_url: function (url, whiteChars) {
whiteChars = ''+(whiteChars||'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.-_~+#,%&=*;:@[]');
var ret = ''; for(var i=0; i<url.length; i++) { ret += whiteChars[whiteChars.indexOf(url[i])] || ''; } do { var old = ret; ret = ret.replace(/javascript:/gi,''); }while(ret != old); return ret; },
7.jsonencode output the filter_var_array ()
function stripHtml(value) { // remove html tags and space chars return value.replace(/<.[^<>]*?>/g, " ").replace(/ | /gi, " ") // remove punctuation .replace(/[.(),;:!?%#$'\"_+=\/\-“”’]*/g, ""); }