PHP - Sql Injection Vulnerability
i just want to ask this simple question
let say i have this basic query $place=$_GET['place']; mysql_query("SELECT * FROM table WHERE place='$place'"); this is a nice target for sql injection.. but what if i replace the whole special characters that could be added $replacethis=array("-","`"); $withthis=array("",""); $place=str_replace($replacethis,$withthis,$_GET['place']); mysql_query("SELECT * FROM table WHERE place='$place'"); Are they still able to do the basic sql injection by trying to get the error by adding special character although i didn't use mysql_real_escape_string() ?? then what if i protect the file by changing the setting of the permission to either 644 or 755? thanks in advance Similar TutorialsDoes this code have mySQL Injection vulnerability?
$query = "DELETE FROM `$table` WHERE `$column` IN('".implode("','",$array)."')";using php5, would this make the code more safe... foreach($array as $key=>$a){ $array[$key] = mysql_real_escape_string($a);} $query = "DELETE FROM `$table` WHERE `$column` IN('".implode("','",$array)."')";or is there another way to make the code safe? I opened a thread yesterday about an XSS vulnerability when the user is logged in. I'll summarize is in a short quote: Quote http://host/editText.php?fieldname=slogan&content=slogan<img src=x onerror=alert("XSS")> This vulnerability only works if the user is logged in. I want to secure it anyway to give the security companies contacting me about this a break. xyph solved my problem with this: Code: [Select] foreach( $_REQUEST as $key => $val ) $_REQUEST[$key] = htmlentities($val); He warned me it was a risky but I didn't take him that seriously. Well guess he was right. The foreach loop he gave me does protect me from the XSS attack, but it also disables the users to use any kind of code in the pages. Next time xyph warns me its risky, I'll know he means it. Now to my problem, how do I use this foreach loop without disabling the user of using simple html tags? Here's the file (editText.php) where the foreach loop was used: Code: [Select] <?php session_start(); // THE LOOP WAS USED HERE BUT I REMOVED IT DUE TO THE USERS PROBLEM. function getSlug( $page ) { $page = strip_tags( $page ); preg_match_all( "/([a-z0-9A-Z-_]+)/", $page, $matches ); $matches = array_map( "ucfirst", $matches[0] ); $slug = implode( "-", $matches ); return $slug; } $fieldname = $_REQUEST['fieldname']; $encrypt_pass = @file_get_contents("files/password"); if ($_COOKIE['wondercms']!=$encrypt_pass) { echo "You must login before using this function!"; exit; } $content = rtrim(stripslashes($_REQUEST['content'])); // if to only allow specified tags if($fieldname=="title") $content = strip_tags($content); else $content = strip_tags($content,"<audio><source><embed><iframe><p><h1><h2><h3><h4><h5><h6><a><img><u><i><em><strong><b><strike><center><pre>"); $content = trim($content); $content = nl2br($content); if(!$content) $content = "Please be sure to enter some content before saving. Just type anything in here."; $content = preg_replace ("/%u(....)/e", "conv('\\1')", $content); if($fieldname>0 && $fieldname<4) $fname = "attachment$fieldname"; else $fname = $fieldname; $file = @fopen("files/$fname.txt", "w"); if(!$file) { echo "<h2 style='color:red'>*** ERROR *** unable to open content_$fieldname</h2><h3>But don't panic!</h3>". "Please set the correct read/write permissions to the files folder.<br/> Find the /files/ folder and CHMOD it to 751.<br /><br /> If this still gives you problems, open up the /files/ folder, select all files and CHMOD them to 640.<br /><br /> If this doesn't work, contact me <a href='http://krneky.com/en/contact'>right here</a>."; exit; } fwrite($file, $content); fclose($file); echo $content; // convert udf-8 hexadecimal to decimal function conv($hex) { $dec = hexdec($hex); return "&#$dec;"; } ?> Does anyone already fix the bug. I found something interesting in the error_log file this morning
x.x.x.x - - [25/Sep/2014:01:12:34 -0500] "GET /cgi-bin/defaul_p.cgi HTTP/1.0" 404 312 "-" "() { :;}; /bin/ping -c 5 "209.126.230.74"
I have a problem which I've been trying to fix for a while now with htmlentities. I've written my own small cms which is available for the public, and recently I recieved a report that it's vulnerable to an XSS attack: http://host/editText.php?fieldname=slogan&content=slogan<img src=x onerror=alert("XSS")> This vulnerability only works if the user is logged in. I want to secure it anyway to give the security companies contacting me about this a break. I've been rolling around the internet trying to find a simple answer how to prevent this XSS attack with HTMLENTITIES. I've even tried writing my own solutions with the htmlentities and it doesn't seem to solve the problem/stop the attack. I'm thinking something like htmlEntities($content); //but again, this won't do the job. Here's the editText.php Code: [Select] <?php session_start(); function getSlug( $page ) { $page = strip_tags( $page ); preg_match_all( "/([a-z0-9A-Z-_]+)/", $page, $matches ); $matches = array_map( "ucfirst", $matches[0] ); $slug = implode( "-", $matches ); return $slug; } $fieldname = $_REQUEST['fieldname']; $encrypt_pass = @file_get_contents("files/password"); if ($_COOKIE['wondercms']!=$encrypt_pass) { echo "You must login before using this function!"; exit; } $content = rtrim(stripslashes($_REQUEST['content'])); // if to only allow specified tags if($fieldname=="title") $content = strip_tags($content); else $content = strip_tags($content,"<audio><source><embed><iframe><p><h1><h2><h3><h4><h5><h6><a><img><u><i><em><strong><b><strike><center><pre>"); $content = trim($content); $content = nl2br($content); if(!$content) $content = "Please be sure to enter some content before saving. Just type anything in here."; $content = preg_replace ("/%u(....)/e", "conv('\\1')", $content); if($fieldname>0 && $fieldname<4) $fname = "attachment$fieldname"; else $fname = $fieldname; $file = @fopen("files/$fname.txt", "w"); if(!$file) { echo "<h2 style='color:red'>*** ERROR *** unable to open content_$fieldname</h2><h3>But don't panic!</h3>". "Please set the correct read/write permissions to the files folder.<br/> Find the /files/ folder and CHMOD it to 751.<br /><br /> If this still gives you problems, open up the /files/ folder, select all files and CHMOD them to 640.<br /><br /> If this doesn't work, contact me <a href='http://krneky.com/en/contact'>right here</a>."; exit; } fwrite($file, $content); fclose($file); echo $content; // convert udf-8 hexadecimal to decimal function conv($hex) { $dec = hexdec($hex); return "&#$dec;"; } ?> There are only 3 files altogether, if someone needs index I'll post that too. Hello my mcafee secure gave me a MySQL Database Error Disclosure Vulnerability error found in this code i installed here is the code in question maybe someone can help me find a fix for it thanks pfrom=From pto=To refine=Refine+your+results categories_id=334 search_in_description=1 subsearch=0 max_pages=x%27%3B%22%2C%29%60 THE SINGLE BEST WAY TO FIX THIS VULNERABILITY IS TO IDENTIFY THE ACCEPTABLE INPUT FOR EACH FORM PARAMETER AND REJECT INPUT THAT DOES NOT MEET THAT CRITERIA. The following is an acceptable solution however it is not optimal. Implement content parsing on data input fields including URL parameters. Remove the following characters from any user or dynamic database input: (examples in VBScript) ' (escape the single quote) input = replace( input, "'", "''" ) " (double quote) input = replace( input, """", "" ) ) (close parenthesis) input = replace( input, ")", "" ) ( (open parenthesis) input = replace( input, "(", "" ) ; (semi-colon) input = replace( input, ";", "" ) - (dash) input = replace( input, "-", "" ) | (pipe) input = replace( input, "|", "" ) On text input it is recommended to append quotes around the user supplied input. Please contact ScanAlert Support if you need further instructions. Code: [Select] <?php require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_ADVANCED_SEARCH); ?> <script language="javascript" src="includes/general.js"></script> <script language="javascript" src="includes/jquery1.2.6.js"></script> <script language="javascript"> <!-- function check_form() { var error_message = "<?php echo JS_ERROR; ?>"; var error_found = false; var error_field; var keywords = document.adv_filter.refine.value; var pfrom = document.adv_filter.pfrom.value; var pto = document.adv_filter.pto.value; var pfrom_float; var pto_float; if (((keywords == '') || (keywords.length < 1)) && ((pfrom == '') || (pfrom.length < 1)) && ((pto == '') || (pto.length < 1))) { error_message = error_message + "* <?php echo ERROR_AT_LEAST_ONE_INPUT; ?>\n"; error_field = document.advanced_search.keywords; error_found = true; } if (pfrom.length > 0) { pfrom_float = parseFloat(pfrom); if (isNaN(pfrom_float)) { error_message = error_message + "* <?php echo ERROR_PRICE_FROM_MUST_BE_NUM; ?>\n"; error_field = document.advanced_search.pfrom; error_found = true; } } else { pfrom_float = 0; } if (pto.length > 0) { pto_float = parseFloat(pto); if (isNaN(pto_float)) { error_message = error_message + "* <?php echo ERROR_PRICE_TO_MUST_BE_NUM; ?>\n"; error_field = document.advanced_search.pto; error_found = true; } } else { pto_float = 0; } if ((pfrom.length > 0) && (pto.length > 0)) { if ((!isNaN(pfrom_float)) && (!isNaN(pto_float)) && (pto_float < pfrom_float)) { error_message = error_message + "* <?php echo ERROR_PRICE_TO_LESS_THAN_PRICE_FROM; ?>\n"; error_field = document.advanced_search.pto; error_found = true; } } if (error_found == true) { alert(error_message); error_field.focus(); return false; } else { return true; } } function popupWindow(url) { window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=450,height=280,screenX=150,screenY=150,top=150,left=150') } //Search Box controls $(document).ready( function() { searchBox(); } ); function searchBox() { $("#refine").focus( function() { if(this.value=='<?php echo REFINE_RESULTS; ?>') { this.value=''; } } ); $("#subsearch").click( function() { if($("#refine").val()=='<?php echo REFINE_RESULTS; ?>') { $("#refine").val(''); } } ); $("#refine").blur( function() { if(this.value=='') { this.value='<?php echo REFINE_RESULTS; ?>'; }; } ); $("#pfrom").focus( function() { if(this.value=='<?=PRICE_FROM?>') { this.value=''; } } ); $("#subsearch").click( function() { if($("#pfrom").val()=='<?=PRICE_FROM?>') { $("#pfrom").val(''); } } ); $("#pfrom").blur( function() { if(this.value=='') { this.value='<?=PRICE_FROM?>'; }; } ); $("#pto").focus( function() { if(this.value=='<?=PRICE_TO?>') { this.value=''; } } ); $("#subsearch").click( function() { if($("#pto").val()=='<?=PRICE_TO?>') { $("#pto").val(''); } } ); $("#pto").blur( function() { if(this.value=='') { this.value='<?=PRICE_TO?>'; }; } ); } //--> </script> <?php $hold_max_pages = MAX_DISPLAY_SEARCH_RESULTS; if ($HTTP_POST_VARS['max_pages']) { $hold_max_pages = $HTTP_POST_VARS['max_pages']; } else { $hold_max_pages = MAX_DISPLAY_SEARCH_RESULTS; } $error = false; if ( (isset($HTTP_POST_VARS['refine']) && empty($HTTP_POST_VARS['refine'])) && (isset($HTTP_POST_VARS['pfrom']) && !is_numeric($HTTP_POST_VARS['pfrom'])) && (isset($HTTP_POST_VARS['pto']) && !is_numeric($HTTP_POST_VARS['pto'])) ) { $error = true; $messageStack->add_session('search', ERROR_AT_LEAST_ONE_INPUT); } else { $pfrom = ''; $pto = ''; $keywords = ''; if (isset($HTTP_POST_VARS['pfrom']) && $HTTP_POST_VARS['pfrom'] !== PRICE_FROM) { $pfrom = $HTTP_POST_VARS['pfrom']; } if (isset($HTTP_POST_VARS['pto']) && $HTTP_POST_VARS['pto'] !== PRICE_TO) { $pto = $HTTP_POST_VARS['pto']; } if (isset($HTTP_POST_VARS['refine']) && $HTTP_POST_VARS['refine'] !== REFINE_RESULTS) { $keywords = $HTTP_POST_VARS['refine']; } $price_check_error = false; if (tep_not_null($pfrom)) { if (!settype($pfrom, 'double')) { $error = true; $price_check_error = true; $messageStack->add_session('search', ERROR_PRICE_FROM_MUST_BE_NUM); } } if (tep_not_null($pto)) { if (!settype($pto, 'double')) { $error = true; $price_check_error = true; $messageStack->add_session('search', ERROR_PRICE_TO_MUST_BE_NUM); } } if (($price_check_error == false) && is_float($pfrom) && is_float($pto)) { if ($pfrom >= $pto) { $error = true; $messageStack->add_session('search', ERROR_PRICE_TO_LESS_THAN_PRICE_FROM); } } if (tep_not_null($keywords)) { if (!tep_parse_search_string($keywords, $search_keywords)) { $error = true; $messageStack->add_session('search', ERROR_INVALID_KEYWORDS); } } } if (empty($pfrom) && empty($pto) && empty($keywords)) { $error = true; $messageStack->add_session('search', ERROR_AT_LEAST_ONE_INPUT); } if ((isset($HTTP_POST_VARS['refine']) && (!empty($HTTP_POST_VARS['refine']) || ($HTTP_POST_VARS['refine'] !== REFINE_RESULTS))) || (isset($HTTP_POST_VARS['pfrom']) && is_numeric($HTTP_POST_VARS['pfrom'])) || (isset($HTTP_POST_VARS['pto']) && is_numeric($HTTP_POST_VARS['pto']))) { // create column list $define_list = array('PRODUCT_LIST_MODEL' => PRODUCT_LIST_MODEL, 'PRODUCT_LIST_NAME' => PRODUCT_LIST_NAME, 'PRODUCT_LIST_MANUFACTURER' => PRODUCT_LIST_MANUFACTURER, 'PRODUCT_LIST_PRICE' => PRODUCT_LIST_PRICE, 'PRODUCT_LIST_QUANTITY' => PRODUCT_LIST_QUANTITY, 'PRODUCT_LIST_WEIGHT' => PRODUCT_LIST_WEIGHT, 'PRODUCT_LIST_IMAGE' => PRODUCT_LIST_IMAGE, 'PRODUCT_LIST_BUY_NOW' => PRODUCT_LIST_BUY_NOW); asort($define_list); $column_list = array(); reset($define_list); while (list($key, $value) = each($define_list)) { if ($value > 0) $column_list[] = $key; } $select_column_list = ''; for ($i=0, $n=sizeof($column_list); $i<$n; $i++) { switch ($column_list[$i]) { case 'PRODUCT_LIST_MODEL': $select_column_list .= 'p.products_model, '; break; case 'PRODUCT_LIST_MANUFACTURER': $select_column_list .= 'm.manufacturers_name, '; break; case 'PRODUCT_LIST_QUANTITY': $select_column_list .= 'p.products_quantity, '; break; case 'PRODUCT_LIST_IMAGE': $select_column_list .= 'p.products_image, '; break; case 'PRODUCT_LIST_WEIGHT': $select_column_list .= 'p.products_weight, '; break; } } $select_str = "select distinct " . $select_column_list . " m.manufacturers_id, p.products_id, pd.products_name, p.products_price, p.products_tax_class_id, IF(s.status, s.specials_new_products_price, NULL) as specials_new_products_price, IF(s.status, s.specials_new_products_price, p.products_price) as final_price "; if ( (DISPLAY_PRICE_WITH_TAX == 'true') && (tep_not_null($pfrom) || tep_not_null($pto)) ) { $select_str .= ", SUM(tr.tax_rate) as tax_rate "; } $from_str = "from ((" . TABLE_PRODUCTS . " p) left join " . TABLE_MANUFACTURERS . " m using(manufacturers_id), " . TABLE_PRODUCTS_DESCRIPTION . " pd) left join " . TABLE_SPECIALS . " s on p.products_id = s.products_id, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c"; if ( (DISPLAY_PRICE_WITH_TAX == 'true') && (tep_not_null($pfrom) || tep_not_null($pto)) ) { if (!tep_session_is_registered('customer_country_id')) { $customer_country_id = STORE_COUNTRY; $customer_zone_id = STORE_ZONE; } $from_str .= " left join " . TABLE_TAX_RATES . " tr on p.products_tax_class_id = tr.tax_class_id left join " . TABLE_ZONES_TO_GEO_ZONES . " gz on tr.tax_zone_id = gz.geo_zone_id and (gz.zone_country_id is null or gz.zone_country_id = '0' or gz.zone_country_id = '" . (int)$customer_country_id . "') and (gz.zone_id is null or gz.zone_id = '0' or gz.zone_id = '" . (int)$customer_zone_id . "')"; } $where_str = " where p.products_status = '1' and p.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id "; if (isset($HTTP_POST_VARS['categories_id']) && tep_not_null($HTTP_POST_VARS['categories_id'])) { if (isset($HTTP_POST_VARS['inc_subcat']) && ($HTTP_POST_VARS['inc_subcat'] == '1')) { $subcategories_array = array(); tep_get_subcategories($subcategories_array, $HTTP_POST_VARS['categories_id']); $where_str .= " and p2c.products_id = p.products_id and p2c.products_id = pd.products_id and (p2c.categories_id = '" . (int)$HTTP_POST_VARS['categories_id'] . "'"; for ($i=0, $n=sizeof($subcategories_array); $i<$n; $i++ ) { $where_str .= " or p2c.categories_id = '" . (int)$subcategories_array[$i] . "'"; } $where_str .= ")"; } else { $where_str .= " and p2c.products_id = p.products_id and p2c.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and p2c.categories_id = '" . (int)$HTTP_POST_VARS['categories_id'] . "'"; } } if (isset($HTTP_POST_VARS['manufacturers_id']) && tep_not_null($HTTP_POST_VARS['manufacturers_id'])) { $where_str .= " and m.manufacturers_id = '" . (int)$HTTP_POST_VARS['manufacturers_id'] . "'"; } if (isset($search_keywords) && (sizeof($search_keywords) > 0)) { $where_str .= " and ("; for ($i=0, $n=sizeof($search_keywords); $i<$n; $i++ ) { switch ($search_keywords[$i]) { case '(': case ')': case 'and': case 'or': $where_str .= " " . $search_keywords[$i] . " "; break; default: $keyword = tep_db_prepare_input($search_keywords[$i]); $where_str .= "(pd.products_name like '%" . tep_db_input($keyword) . "%' or p.products_model like '%" . tep_db_input($keyword) . "%' or m.manufacturers_name like '%" . tep_db_input($keyword) . "%'"; if (isset($HTTP_POST_VARS['search_in_description']) && ($HTTP_POST_VARS['search_in_description'] == '1')) $where_str .= " or pd.products_description like '%" . tep_db_input($keyword) . "%'"; $where_str .= ')'; break; } } $where_str .= " )"; } if (tep_not_null($pfrom)) { if ($currencies->is_set($currency)) { $rate = $currencies->get_value($currency); $pfrom = $pfrom / $rate; } } if (tep_not_null($pto)) { if (isset($rate)) { $pto = $pto / $rate; } } if (DISPLAY_PRICE_WITH_TAX == 'true') { if ($pfrom > 0) $where_str .= " and (IF(s.status, s.specials_new_products_price, p.products_price) * if(gz.geo_zone_id is null, 1, 1 + (tr.tax_rate / 100) ) >= " . (double)$pfrom . ")"; if ($pto > 0) $where_str .= " and (IF(s.status, s.specials_new_products_price, p.products_price) * if(gz.geo_zone_id is null, 1, 1 + (tr.tax_rate / 100) ) <= " . (double)$pto . ")"; } else { if ($pfrom > 0) $where_str .= " and (IF(s.status, s.specials_new_products_price, p.products_price) >= " . (double)$pfrom . ")"; if ($pto > 0) $where_str .= " and (IF(s.status, s.specials_new_products_price, p.products_price) <= " . (double)$pto . ")"; } if ( (DISPLAY_PRICE_WITH_TAX == 'true') && (tep_not_null($pfrom) || tep_not_null($pto)) ) { $where_str .= " group by p.products_id, tr.tax_priority"; } if ( (!isset($HTTP_POST_VARS['sort'])) || (!ereg('[1-8][ad]', $HTTP_POST_VARS['sort'])) || (substr($HTTP_POST_VARS['sort'], 0, 1) > sizeof($column_list)) ) { for ($i=0, $n=sizeof($column_list); $i<$n; $i++) { if ($column_list[$i] == 'PRODUCT_LIST_NAME') { $HTTP_POST_VARS['sort'] = $i+1 . 'a'; $order_str = ' order by pd.products_name'; break; } } } else { $sort_col = substr($HTTP_POST_VARS['sort'], 0 , 1); $sort_order = substr($HTTP_POST_VARS['sort'], 1); $order_str = ' order by '; switch ($column_list[$sort_col-1]) { case 'PRODUCT_LIST_MODEL': $order_str .= "p.products_model " . ($sort_order == 'd' ? "desc" : "") . ", pd.products_name"; break; case 'PRODUCT_LIST_NAME': $order_str .= "pd.products_name " . ($sort_order == 'd' ? "desc" : ""); break; case 'PRODUCT_LIST_MANUFACTURER': $order_str .= "m.manufacturers_name " . ($sort_order == 'd' ? "desc" : "") . ", pd.products_name"; break; case 'PRODUCT_LIST_QUANTITY': $order_str .= "p.products_quantity " . ($sort_order == 'd' ? "desc" : "") . ", pd.products_name"; break; case 'PRODUCT_LIST_IMAGE': $order_str .= "pd.products_name"; break; case 'PRODUCT_LIST_WEIGHT': $order_str .= "p.products_weight " . ($sort_order == 'd' ? "desc" : "") . ", pd.products_name"; break; case 'PRODUCT_LIST_PRICE': $order_str .= "final_price " . ($sort_order == 'd' ? "desc" : "") . ", pd.products_name"; break; } } $listing_sql = $select_str . $from_str . $where_str . $order_str; } $listing_split = new splitPageResults($listing_sql, $hold_max_pages, 'p.products_id'); if (($listing_split->number_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '1') || (PREV_NEXT_BAR_LOCATION == '3'))) { ?> <div class="infoBoxContents" style="padding:0.5em; text-align:center;"> <form name="filter" action="<?php echo tep_href_link(basename($PHP_SELF),tep_get_all_get_params(array('pfrom', 'pto', 'refine', 'page', 'info', 'x', 'y', 'manufacturers_id'))); ?>" method="post"> <label for="pfrom" class="fieldKey"><?=PRICE_RANGE?></label> <input id="pfrom" name="pfrom" value="<?=PRICE_FROM?>" class="fieldValue" style="width:5em" /> - <input id="pto" name="pto" value="<?=PRICE_TO?>" class="fieldValue" style="width:5em" /> <input id="refine" type='text' name='refine' value="<?=REFINE_RESULTS?>" style='width:42%;' class="fieldValue" /> <?php echo tep_draw_hidden_field('categories_id', (int)$current_category_id) . tep_draw_hidden_field('search_in_description', '1') . tep_image_submit('button_search.gif', IMAGE_BUTTON_SEARCH, "id='subsearch' name='subsearch' style='margin:0 5px;'"); ?> <div style="display:inline-block; width:49%; margin: 0.5em 0; text-align:center;"> <?php // optional Product List Filter if (PRODUCT_LIST_FILTER > 0) { $filterlist_sql = "select distinct m.manufacturers_id as id, m.manufacturers_name as name from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c, " . TABLE_MANUFACTURERS . " m where p.products_status = '1' and p.manufacturers_id = m.manufacturers_id and p.products_id = p2c.products_id and p2c.categories_id = '" . (int)$current_category_id . "' order by m.manufacturers_name"; $filterlist_query = tep_db_query($filterlist_sql); if (tep_db_num_rows($filterlist_query) > 1) { echo tep_draw_hidden_field('cPath', $cPath); $options = array(array('id' => '', 'text' => TEXT_ALL_MANUFACTURERS)); echo tep_draw_hidden_field('sort', $HTTP_POST_VARS['sort']); while ($filterlist = tep_db_fetch_array($filterlist_query)) { $options[] = array('id' => $filterlist['id'], 'text' => $filterlist['name']); } echo tep_draw_pull_down_menu('manufacturers_id', $options, (isset($HTTP_POST_VARS['manufacturers_id']) ? $HTTP_POST_VARS['manufacturers_id'] : ''), 'onchange="this.form.submit()"'); } } ?> </div><div style="display:inline-block; width:49%; margin: 0.5em 0; text-align:center;"> <?php $all = $listing_split->number_of_rows; $page_options = array(array('id' => $hold_max_pages, 'text' => sprintf(SHOWING_RESULTS, $hold_max_pages))); $page_options[] = array('id' => $all, 'text' => sprintf(SHOW_RESULTS, 'All') . " ($all)"); $page_options[] = array('id' => 5, 'text' => sprintf(SHOW_RESULTS, 5)); $page_options[] = array('id' => 15, 'text' => sprintf(SHOW_RESULTS, 15)); $page_options[] = array('id' => 25, 'text' => sprintf(SHOW_RESULTS, 25)); $page_options[] = array('id' => 50, 'text' => sprintf(SHOW_RESULTS, 50)); echo tep_hide_session_id(); echo tep_draw_pull_down_menu('max_pages', $page_options, '', 'onchange="this.form.submit()"'); ?> </div> </form> <div> <?php // Sort columns by ??? You may need to rearrange the numbers in order of your columns in product listing echo SORT_BY . tep_create_sort_heading($HTTP_GET_VARS['sort'], 1, TABLE_HEADING_MODEL) . ' | ' . tep_create_sort_heading($HTTP_GET_VARS['sort'], 4, TABLE_HEADING_PRODUCTS) . ' | ' . tep_create_sort_heading($HTTP_GET_VARS['sort'], 2, TABLE_HEADING_MANUFACTURER) . ' | ' . tep_create_sort_heading($HTTP_GET_VARS['sort'], 5, TABLE_HEADING_PRICE); ?> </div> </div> <div class="smallText" style="display:inline-block; width:49%;"><?php echo $listing_split->display_count(TEXT_DISPLAY_NUMBER_OF_PRODUCTS); ?></div> <div class="smallText" style="display:inline-block; width:49%; text-align:right;"><?php echo TEXT_RESULT_PAGE . ' ' . $listing_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></div> <?php } ?> I'm confused, can this result in css/sql injection? Code: [Select] if(isset($_GET['action'])){ if($_GET['action'] == 'details'){ $cupID = $_GET['cupID']; $ergebnis = safe_query("SELECT gameaccID, name, start, ende, typ, game, `desc`, status, checkin, maxclan, gewinn1, gewinn2, gewinn3 FROM ".PREFIX."cups WHERE ID = '".$cupID."'"); $ds=mysql_fetch_array($ergebnis); ... Some german fellow was explaining, translate to English briefly: "$ CupID is not escaped. NEN here I could just "; DROP TABLE` cups `Paste and your table is no longer available eez. Or I could inject javascript, your current session read out, accept it and act as an admin ... " I am trying to understand what he means by this... is this query vulnerable to an injection and why/how? I am having a wamp issue so I can't try these out right now. According to the book I'm learning php with, I can easily avoid injection attacks this way:
$a= stripslashes($a);
$a= mysql_real_escape_string($a);
What concerns me is the repetition of the variable, $a. Does it matter? Intuitively, it should.
$a changes. By the time $a hits mysql_real_escape_string it is slash-free. So it is a totally different "value" but still contained in the original variable which may have had slashes...just has me concerned a bit.
I know PDOs are the best way. I'm not there yet, unfortunately.
Edited by baltar, 23 May 2014 - 10:36 AM. Hi, I'm sure many of you heard of "pastebin", if not the short of it, is that you can submit your code (+100 languages), and you can display it to your friends via a link with syntax highlighting available. So, One way to store the code is surely in txt files, but I would really prefer to have it stored in a mysql database. My only concern is people trying to run a sql injection, so how do i get around all this? I don't want the user's content to be changed, but I don't want SQL injections either.. is this even possible at all? Any tips appreciated, also if you could think of another alternative than txt files and mysql. I'm trying to use dependency injection to pass a database connection to an object but I'm not sure why it's not working. I have my "dbClass" below that connects to a MySQL database. Code: [Select] class dbClass { public $db; function __construct() { $this->db = mysql_connect("localhost","username","password") or die ('Could not connect: ' . mysql_error()); return $this->db; } } Then I have my "baseClass". This is the class that I want to feed to connection too. Code: [Select] class baseClass { public $mysql_conn; function __construct($db) { $this->mysql_conn = $db; $rs = mysql_select_db("webdev_db", $this->mysql_conn) or die ('Could not connect: ' . mysql_error()); } } And this is my index.php file. The error I'm getting is "supplied argument is not a valid MySQL-Link resource". However I tripled checked and my db connection details are definately correct. Code: [Select] $db = new dbClass(); $baseclass = new baseClass($db); Thanks for any help. Will this prevent a SQL injection? I am guessing the answer is no because it is too simple. // retrieve form data ========================================== $ama = $_POST['ama']; // Check for alphanumeric characters ===================================== $string = "$ama"; $new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string); // echo $new_string; // Send query =========================================================== $query = "SELECT * FROM members WHERE ama='$new_string'"; if (!mysql_query($query)){ die('Error :' .mysql_error()); } I want to know which part of my script has the hole..as i can find lots of php script and even folder can be injected into my public_html how they do that, and which part need to be checked? is that the upload part <enctype> or what?? thanks in advance Based on the comments on my previous question, took some tutorials on how to avoid injections on query. Does the code below prevents against it in any way.? Secondly, can you recommend a good article that writes well in how to secure input data by users. Please be kind with your comments.😉😉. Thankks in advance.
The code works fine. <?php include 'db.php'; error_reporting(E_ALL | E_WARNING | E_NOTICE); ini_set('display_errors', TRUE);  if(isset($_POST['submit']))  {     $username = $_POST['username']; $password =  ($_POST['password']); $sql = "SELECT * FROM customer WHERE username = ?"; $stmt = $connection->prepare($sql); $stmt->bind_param('s', $username); $stmt->execute(); $result = $stmt->get_result(); $count =  $result->num_rows;   if($count == 1)              { while ($row = $result->fetch_assoc())  {   if ($row['status'] == 'blocked')  {  echo'your account is suspended'   session_destroy();   exit();  }  else if($row['status'] == 'active') { if($username !== $row['username'])  { echo '<script>swal.fire("ERROR!!", " Username is not correct. Check Again", "error");</script>'; } if($password !== $row['password']) {  echo'<script>swal.fire("ERROR!!!", "Your Password is Incorrect. Check Again.", "error");</script>';     } if($username == $row['username'] && $password == $row['password']) { header('Location:cpanel/'); else { } }//if count }//while loop }//submit ?>  Hello, I have a video game site - mostly vBulletin which is fine but there are a few extra bits to the site that I have done myself. I'm pretty new to PHP so my code isn't great. Anyway, I wanted to test my code for SQL Injection but I looked on Google and most of the tools seemed to come from hacker sites etc which I'm not downloading. I eventually found an addon for Firefox called SQL Inject Me and ran that. It said everything was alright but when I checked my MySQL tables they were full of junk code it had inserted. One of my pages doesn't even have any visible fields. It's just a page with a voting submit button and some hidden fields so how does it inject the code into the tables? The insert page code is: Code: [Select] $db = mysql_connect("localhost", "username", "password"); mysql_select_db("thedatabase",$db); $ipaddress = mysql_real_escape_string($_POST['ipaddress']); $theid = mysql_real_escape_string($_POST['theid']); $gamert = mysql_real_escape_string($_POST['gamert']); $serveron = mysql_real_escape_string($_POST['serveron']); $check= mysql_query("select * from voting2 where ipaddress='$ipaddress'"); $ipname = mysql_fetch_assoc($check); if($ipname['ipaddress'] == $ipaddress) { echo 'It appears you have already voted. Click <a href="vote.php">here</a> to return to the votes.'; } else { mysql_query ("INSERT INTO voting2 (theid,ipaddress,gamert,serveron2) VALUES ('$theid','$ipaddress','$gamert','$serveron')"); echo 'Your vote has been added. Click <a href="vote.php">here</a> to view the updated totals.'; } How can I make it safer against SQL injection? Thanks (I'm putting this in PHP since it's not a question specific to MySQL or other DB stuff.)
I have a page that uses the GET id to find a product. GET variables are sanitized, and the SQL string is escaped even though it's expecting a number only. So the code seems safe to me. I'm getting some error_log results that appear to be hack attempts:
SELECT Hi, I am using parameterized queries on my code, here's the relevant part Code: [Select] $params=$_POST['ITGtable']; $tsql2 = "SELECT COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=?"; /* Execute the statement with the specified parameter value. Display the returned data if no errors occur. */ $stmt2 = sqlsrv_query( $conn, $tsql2, $params); if( $stmt2 === false ) { echo "Statement 2 could not be executed.\n"; die( print_r(sqlsrv_errors(), true)); } else { $qty = sqlsrv_fetch_array( $stmt2); } Do I really have to sanitize $_POST['ITGtable'] for apostrophe, semicolon, etc, to avoid SQL injection problems? Or just with above code I should be safer (I did not say safe) against SQL injection? And if the answer is "No", what could be the sanitize code of function? I am using sqlsrv and MS-SQL database engine; most of the functions we have for sanitize inputs on MySQL are not available for MS-SQL. Thanks in advance, Trying to make my code more secure. This is what I currently have, which is not secure by any means: Code: [Select] $query1 = "SELECT COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$table'"; // Run PRO query $qresult1 = sqlsrv_query($dbPRO, $query1); if ($qresult1 === false) { exitWithSQLError('Retrieving schema failed.'); } This is how I changed it, Code: [Select] $query1 = "SELECT COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=?"; $params = array(1, $table); // Run PRO query $qresult1 = sqlsrv_query($dbPRO, $query1, $params); if ($qresult1 === false) { exitWithSQLError('Retrieving schema failed.'); } but I'm getting this error: Code: [Select] SQL-Status: 22018 Code: 245 Message: [Microsoft][SQL Server Native Client 10.0][SQL Server]Conversion failed when converting the nvarchar value 'sysrscols' to data type int Please notice I am using sqlsrv_query function because my database engine is MS-SQL 2008. That's why I'm a bit confused. Most documentation online is pointed to MySQL. exitWithSQLError is a customized function of mine, so please ignore. Any help or hints is appreciated, Thanks, $_POST['user_name'] = "CLUEL3SS"; $_POST['user_pass'] = "test123"; $_POST['confirm_pass'] = "test123"; $_POST['user_email'] = "user@email.com"; $_POST['confirm_pass'] = 'user@email.com'; function testFunc($inputVars){ foreach($inputVars as $key=>$value){ $escapeData[$key] = mysql_real_escape_string($value); } return $escapeData; } var_dump(testFunc($_POST)); I'm trying to make a user system for my site and I want to make sure its secure enough to void off injection attackers. Any useful advice and and suggestions would be greatly appreciated! Thanks! been wondering about this for a while do I need to put the escape on each WHERE? or do i really only need to put it on the $_POST i can probably understand why i need it on $_GET also after WHERE. So wondering about the session id. Code: [Select] <?php mysql_query("UPDATE systems SET homes= $homes + '".mysql_real_escape_string($_POST['homes'])."' WHERE address = '".mysql_real_escape_string($_GET['planet'])."' AND id = '".($_SESSION['user_id'])."'"); ?> Hey Guys, Hope you are all having a great day I was hoping somebody could help me with preventing my blog from being attacked by SQL Injection. I made a simple blog in using PHP and MySQL but I keep getting spam comments (even though I use re-captcha) and some files were overwritten on my web server. For all my input I use mysql_real_escape_string but I still get the problem. I found a video on youtube that showed how to enter stuff on the address bar like "order by 2--" and "union all select...." after passing a variable etc, and all of the things in the video could be replicated on my site I am guessing that is my problem, but the video did not tell me how to resolve the issue and I am sick of having to delete hundreds of spam comments per day and check my web server for uploaded files. How can I stop people adding these commands to the address bar and getting data from my database? I really need your help Thanx, Jen |