This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I've got a problem. As soon as I enter this little f****r --> ' <-- in my textarea which are sent to a database via AJAX, it stops working. So if I for example enter:
I am a little gnome and I'm glad to meet you. Hug me!
The database will only receive:
I am a little gnome and I
So.. Can I limit all textareas on the page to like A-Z + ÅÄÖ + . , + other regularly used characters which don't ruin my stuff? I am using onchange for the AJAX request, and another eventlistener for keyup to make it work on Safari, if that's of any importance to anyone!
SQL-injection vulnerability, got it. I'm scared, and have stuff to do. Thanks for all answers thus far.
Note
I can see you're starting out, and it's great! You've always gotta find a bug to learn new stuff, and you're learning about SQL Injections now. If I could suggest something, you'd be best to start at PHP The Right Way, it'll help you a truckload.
You're PHP script (that inserts this data into a database) is not sanitized correctly.
We can't do much without seeing your associated code. But I take it you're using mysql_*/mysqli_* functions? We'll the former one is deprecated and removed as of PHP7!
You should start learning either of the following two prepared statement types:
PDO
Mysqli Prepared Statements
From what I assume, you want to escape the string:
$data = mysql_real_escape_string($_POST['data']);
Although, there are still ways around the above escape; your database can still be hacked via SQL Injection, which is not what you want.
As noted by Armadan, to back up my statement above, mysql_real_escape_string() is still by-passable in certain cases, read these:
SQL injection that gets around mysql_real_escape_string()
Bypassing mysql_escape_string while SQL injection attacks
Taking the code you've supplied, you'd use prepare() and execute():
if(isset($_GET['comment1'])) {
if($mysqli = connect_db()) {
$insertcomment1 = $_GET['comment1'];
$stmt = $mysqli->prepare("UPDATE result SET c1=?");
if ( false===$stmt ) {
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$stmt->bind_param('s', $insertcomment1);
// execute
if(!$stmt->execute()){
die('execute() failed: ' . htmlspecialchars($mysqli->error));
}
// handle the rest here.
}
}
You'd be doing something like the above. You're best to read up on the following in relation to prepared statements using MySQLi:
prepare()
bind_param()
execute()
Related
I have an idea for a game where people can type in some simple instructions for their character like player.goLeft() or player.attackInFront() and for that I have people type their code into a text box and then I parse it into eval(). This works well but it also allows people to change their own character object by typing things like player.health = Infinity; or something similar. I have a list of functions I want to allow people to use, but I am unsure how to restrict it to only use them.
I understand that the whole point of not letting people use eval is to avoid accidental cross-site scripting but I am unsure on how else to do this. If you have a suggestion please leave a comment about that.
I asked some people around on what to do and most suggested somehow changing scope(which is something I was not able to figure out) or to add some odd parameter to each function in my code that would be required to be a specific string to execute any function, but that seems hacky and since I am making the game in browser with p5js it would be easy to just inspect element and see what the password is.
basically every character has variable called "instruction" which is just a string of javascript. Then every frame of the game I execute it by doing eval(playerList[i].instruction);
tl;dr, how can I only allow specific function to be executed and not allow any others?
EDIT: I forgot to mention that I also am planning to provide player with information so that people can made code that would adapt to the situation. For example there will be parameter called vision that has vision.front and vision.left etc. These variables would just say if there is an enemy, wall, flower, etc around them in a grid. Some people suggested that I just replace some functions with key words but then it compromises the idea of using if statements and making it act differently.
EDIT 2: Sorry for lack of code in this post, but because of the way I am making it, half of the logic is written on server side and half of it works on client side. It will be a little large and to be completely honest I am not sure how readable my code is, still so far I am getting great help and I am very thankful for it. Thank you to everybody who is answering
Do NOT use eval() to execute arbitrary user input as code! There's no way to allow your code to run a function but prevent eval() from doing the same.
Instead, what you should do is make a map of commands the player can use, mapping them to functions. That way, you run the function based on the map lookup, but if it's not in the map, it can't be run. You can even allow arguments by splitting the string at spaces and spreading the array over the function parameters. Something like this:
const instructions = {
goLeft: player.goLeft.bind(player),
goRight: player.goRight.bind(player),
attackInFront: player.attackInFront.bind(player)
};
function processInstruction(instruction_string) {
const pieces = instruction_string.split(' ');
const command = pieces[0];
const args = pieces.slice(1);
if (instructions[command]) {
instructions[command](...args);
} else {
// Notify the user their command is not recognized.
}
};
With that, the player can enter things like goLeft 5 6 and it will call player.goLeft(5,6), but if they try to enter otherFunction 20 40 it will just say it's unrecognized, since otherFunction isn't in the map.
This issue sounds similar to the SQL Injection problem. I suggest you use a similar solution. Create an abstraction layer between the users input and your execution, similar to using parameters with stored procedures.
Let the users type keywords such as 'ATTACK FRONT', then pass that input to a function which parses the string, looks for keywords, then passes back 'player.attackInFront()' to be evaluated.
With this approach you simplify the syntax for the users, and limit the possible actions to those you allow.
I hope this isn't too vague. Good luck!
From your edit, it sounds like you're looking for an object-oriented approach to players. I'm not sure of your existing implementation needs, but it would look like this.
function Player() {
this.vision = {
left: '',
// and so on
}
}
Player.prototype.updateVisibilities = function() {
// to modify the values of this.visibility for each player
}
Player.prototype.moveLeft = function() {
}
Don't give the user an arbitrary interface (such as an input textfield that uses eval) to modify their attributes. Make a UI layer to control this logic. Things like buttons, inputs which explicitly run functions/methods that operate on the player. It shouldn't be up to the player as to what attributes they should have.
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
Having a bad day. This one has stumped me all morning. All the solutions I've found have stopped one step short of where I need to go.
I have a legacy PHP/JS app that I'm working on. Rather than trying to explain it, I'll just show what I need to do.
<?php
$phpDate_1 = new Date($someDate);
$phpDate_2 = new Date($someOtherDate);
//...There are a bunch of these
$phpDate_n = new Date($endOfTime);
<script language="javascript">
function myFunction() {
var line = aUserSelection; //an int from user which tells me what date to use
//Next line is the problem. I'm trying to pull the month from the appropriate PHP date into the JS variable.
var theMonth = "<?php echo $phpDate_" + line + "->getMonth();?>";
}
</script>
?>
I must have tried 20-30 combinations of single and double quotes, escapes, dots, pluses, and so on, but I keep getting errors over the "line" part. Unexpected character, encapsed strings, etc.
Hoping someone can point me in the right direction because my brain is fried at this point. Answers in pure JS and PHP only please because that's how the app is built. Thanks.
You need to close your php (?>) before outputting the javascript to fix the syntax error that you got.
However, with that said, you are trying to incorporate the javascript line variable into the variable name for $phpDate, to generate something like $phpDate_1.
If you don't want to go with an AJAX solution, your best bet would be to output each line's date into a javascript array. This is strongly discouraged, but if this is a legacy application that you cannot make many changes to, this might be your only option.
I'm working on the profile section of my users.
They can define several things including their description ("About me") in a textarea, with a max of 400 characters.
In this description, I want to let my users use Font Awesome and Bootstrap icons. I also let them use JS tags (but not PHP ones). I guess this is pretty dangerous, therefore I wanted to know :
Is letting people use JS tags dangerous ? I know I must block functions like $.ajax but maybe there are somethings else.
Does a function which blocks string containing JS or PHP code exist in JS or jQuery ?
Is letting people use HTML tags and attributes dangerous for my site ?
Thank you !
As long as you escape all the tags before saving the form, I think it's all good.
You can do this with the following function:
function escapeTags(value){
return $('<div/>').text(value).html();
}
For eg. the following <script>alert("hello world")</script> will become <script>alert("hello world")</script>.
Also, you can do this with javascript only:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
Source: https://css-tricks.com/snippets/javascript/htmlentities-for-javascript/
...if you take a look at comments you'll se that there's also a function that reverse my escapeTags function
// Encode/decode htmlentities
function krEncodeEntities(s){
return $j("<div/>").text(s).html();
}
function krDencodeEntities(s){
return $j("<div/>").html(s).text();
}
Yes, it's in fact very dangerous, and should only be allowed on a very limited set of "tags" or function calls.
Several systems like bbcode exist to address specifically these issues. i suggest implementing one of those.
They're easier to validate, and it is fairly easy to add new features to them.
It should be less work than validating actual js and php code and figuring out whether or not it is trying to do something malicious.
I'm using PHP to pull posts from Wordpress (WP_Query()) to generate Fullcalendar event strings. All's working swell except character entities (specifically apostrophes), which are in the post's Title field (as apostrophes), are displaying on the webpage as "’". I thought maybe there's some double decoding going on somewhere, so I tried running the variable through html_entity_decode(), as well as htmlspecialchars_decode(), with no luck. Thanks for any help!
<?php
$the_film = ': '.strtoupper(get_the_title($filmID));
...
echo '{"id":"'.get_the_ID().'","title":"'.$the_city.$the_film.'","start":"'.$start.'","color":"'.$color.'","textColor":"'.$textColor.'","url":"'.$filmlink.'","moderator":"'.$moderator.'","guest":"'.$guest.'"},';
?>
Thanks for the nudge, Henrique. Your confidence in me proved worthy. I messed around with things a bit more and because I was using .text() rather than .html() in rendering my FC events, the character entities weren't being decoded.
So I've made this search that does what its supposed to do front-end wise. However, when submitting I'd like the query to ignore commas.
Right now I'm using commas to make a comma separated search. The whole thing is, when I submit; the comma's are included and thus messes up my search values.
Is there any way to ignore comma's upon submit?
Example: Searching [Example][Test] will actually return Example,Test.
I've made a fiddle here
Any suggestions and help is greatly appreciated.
var firster = true;
//capture form submit
$('form.nice').submit(function(e){
if(firster){
// if its the first submit prevent default
e.preventDefault();
// update input value to have no commas
var val = $('input').val();
val = val.replace(/,/g, ' ');
$('input').val(val);
// let submit go through and submit
firster = false;
$(this).submit();
}
});
DEMO
Looking at your profile, I'm guessing you're using python as a server-side language. The issue you're trying to solve is best dealt with server-side: never rely on front-end code to escape or format data that is being used in a query... check Bobby Tables for more info
Anyhow, in python, you could try this:
ajaxString.replace(",","\", \"")
Thiis will replace all commas witIh " OR ", so a string like some, keywords is translated into some", "keywords, just add some_field IN (" and the closing ") to form a valid query.
Alternatively, you can split the keywords, and deal with them separately (which could come in handy when sorting the results depending on how relevant the results might be.
searchTerms = ajaxString.split(",")
>>>['some','keywords']
That should help you on your way, I hope.
Lastly, I'd suggest just not bothering with developing your own search function at all. Just add a google search to your site, they're the experts. There is just no way you, by yourself, can do better. Or even if you could, just imagine how long it'd take you!
Yes, sometimes a company will create their own search-engine, but only if they have a good reason to do so, and have the resources such an endevour requires. Programming is often all about being "cleverly lazy": Don't reinvent the wheel.