PHP strings that start with $

Status
Not open for further replies.

scHarvey

Ars Legatus Legionis
10,386
Trying to do some string comparisons from user_ids that a client uses to create a login system, however the client's user ids are random strings many of which start with a $ so when I do something like

Code:
$user_id = '$myid';

It sets $user_id to an empty string. I know there's a way to prevent this string from thinking it's a variable, but I can't for the life of me remember what it is. Someone mentioned escaping the $, but as this comes to me from the outside by the time I have it it's already in a string variable and I'm 90% sure that if I try to do a strpos on '$myid' it's going to just look inside an empty string.

What's the simple solution here other than yelling at people that start user ids with a $?
 

scHarvey

Ars Legatus Legionis
10,386
the id comes in either from a querystring, from a web service call, or possibly from an array that I've built for "special users". The only place where I can see actually being able to escape the $ is in the special users, but since I'm comparing that value to the user id that's been passed in by the query string (from a system outside of my control) I will still end up comparing an empty string to my '\$myid' value.



edit;
Maybe I'm overthinking this and it is just the special users that I need to account for. I'll do some more testing and see what happens.
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
JonTD":1mn2d4zu said:
Can you use addcslashes?
FWIW, using addslashes and its derivatives is kind of poor practice in PHP. Generally speaking, if you need to do that, you need to refactor your code. (It's possible to use it safely, but it's not binary-safe and can introduce even more subtle bugs than other encoding functions when used unwisely.)
 

JonTD

Ars Legatus Legionis
14,317
Blacken00100":hnqbjw1b said:
JonTD":hnqbjw1b said:
Can you use addcslashes?
FWIW, using addslashes and its derivatives is kind of poor practice in PHP. Generally speaking, if you need to do that, you need to refactor your code. (It's possible to use it safely, but it's not binary-safe and can introduce even more subtle bugs than other encoding functions when used unwisely.)
It was all I could even think to try because I didn't understand why the OP was even having an issue if the $ was coming to him in the string already.
 

scHarvey

Ars Legatus Legionis
10,386
Just wanted to follow up.

Something weird was definitely going on when the client's system passed me a string variable that started with a $ in the querystring.

I tried multiple versions of my code on my own servers and everything seemed to be working as you guys described, however it was still acting weird on the client's server. Rather than debug their server to figure out what was going on I had them pad all usernames that they sent me with a pipe on either side, so "?userid=$monkey" becomes "?userid=|$monkey|".

I was then able to use substr to grab the real userid in to a php variable and everything worked as expected.

Appreciate the help. I thought I remembered that single quotes prevented variables from resolving to their values, but as the server was acting so weird I started to doubt my hazy memory.
 

inpher

Well-known member
3,697
Delirious":sbzfxdzs said:
Ok from what you've said, particularly in your last post... Why on earth are you passing strings that start with a $ when you know that's what PHP uses to identify variables? surely user_id should be a unique number or username in which case it should be ?user_id=monkey. The PHP code then should be $user_id=$_GET['user_id'];
Don't forget input sanitation!
 

Delirious

Wise, Aged Ars Veteran
172
inpher":2rvmw1pc said:
Delirious":2rvmw1pc said:
Ok from what you've said, particularly in your last post... Why on earth are you passing strings that start with a $ when you know that's what PHP uses to identify variables? surely user_id should be a unique number or username in which case it should be ?user_id=monkey. The PHP code then should be $user_id=$_GET['user_id'];
Don't forget input sanitation!

Ok, I'm relatively new at this so explain; "input sanitation"?
 

inpher

Well-known member
3,697
Delirious":2xwf3gfw said:
Ok, I'm relatively new at this so explain; "input sanitation"?
It is internet security 101: You sanitize any and all data that you get from the user end. You do this for reasons of 1. security and 2. stability.

First reason: Security.
If you do not remove bad data from the input you prevent the user from changing, reading or deleting your database content. SQL injections are common (perhaps the most common) security breaches today. It works by sending your script data that would change your query into something new.

Let us say your PHP script is called with this URL:
Code:
http://www.example.com/form.php?user=12&form_id=account_details&action=update&email=mail@example.com

Your code would probably look something like this (shortened for brevity):

Code:
<?php
// Get form data
$action = $_POST['action'];
$email = $_POST['email'];
$user = $_POST['user'];
$form = $_POST['form_id'];

if ($form == "update") {
    // Build SQL update query
    $query = "UPDATE users SET user_email=$email WHERE user_id=$user";
}
// Then run the query, no code written because >99% of all security problems are already present in the code above
?>

I count three types (some occurring more than once) of security problems in the code above.
  • The code does not check that the $user is an integer by removing anything that is not in the range of [0-9] and that the remaining integer is the same as the logged in user has.
  • The code does not remove or escape unwanted data from any of the inputs. If I wanted to do something nefarious I could send something along the lines of
    Code:
    http://www.example.com/form.php?user=*&form_id=account_details&action=update&email=mail@example.com
    and have everyones account set to my e-mail address. Succeeding with this I am now a 1337 haX0r and can brag about it on 4chan. ;)
  • The code does not parametize or prepare the SQL query.
  • Other good things to use is LIMIT 1 as often as possible which might sometimes mitigate some damage. This is a pretty good beginners article, and I am sure someone on this forum will discover at least one security consideration that I have forgotten to mention above.
PHP has many halfbaked solutions like mysql_real_escape_string or similar functions. I blame the PHP developers for not providing a solid single function and I blame every goddamned tutorial on the net that disregards security in the name of laziness. I always recommend developers to use PDO, not only is it more secure, it is also provides rudimentary database abstraction and some other nice feature you may appreciate when you get into more advanced development.

Second reason: Stability.
If I happen to include a cite or some html code or odd glyph in the input I could potentially cause problems for your form (returning errors and such unfriendly for the user behaviour). For example the someone with the name O'Connor will have trouble submitting their name in some forms. If you escape/encode the user input O'Connor, Jönsson, 陈 (Chén) will be as happy as you are because you wrote good code.
 

ronelson

Ars Legatus Legionis
21,399
Subscriptor
It is internet security 101: You sanitize any and all data that you get from the user end. You do this for reasons of 1. security and 2. stability.
It really is Input Validation 101. Even for programs that are not accessible from the internet or have no security implications.
Code:
Please enter a number from 1 to 10
> e
Stupid users :)
 

norton_I

Ars Tribunus Angusticlavius
6,174
Subscriptor++
Input validation is great, and you should always strive to detect invalid input at the earliest possible point in order to allow the user to correct it.

However, sanitization is not the right solution to most security issues, especially SQL injection. You should be using parameterized queries instead. It is too easy to miss sanitizing a string. Furthermore, sanitization by escaping is vulnerable to environments where the string will go through multiple levels of unescaping. Sanitizating by filtering or rejecting invalid characters is bad because it leads to idiotic rules like "no punctuation in passwords". The real issue here is that you shouldn't treat data like code.
 

ronelson

Ars Legatus Legionis
21,399
Subscriptor
However, sanitization is not the right solution to most security issues, especially SQL injection.
It is still part of it. If you are expecting an email address, you need at least one character, an '@' sign, one or more characters, a '.', and one or more characters. Sure, you can just use parameterized queries to ensure that the contents of $email do not screw up the DB, but you should also validate it to ensure that it has a good chance of retrieving data or populating/updating a row (SELECT * FROM USERS WHERE email = '(123)456-7890' better not return any results!). Likewise, if you had characters in $phone_num, you would have a problem. They should be used together. I know that is kind of what you said, just emphasizing that validation is the 101 level class.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
ronelson":lx90g14f said:
However, sanitization is not the right solution to most security issues, especially SQL injection.
It is still part of it. If you are expecting an email address, you need at least one character, an '@' sign, one or more characters, a '.', and one or more characters. Sure, you can just use parameterized queries to ensure that the contents of $email do not screw up the DB, but you should also validate it to ensure that it has a good chance of retrieving data or populating/updating a row (SELECT * FROM USERS WHERE email = '(123)456-7890' better not return any results!). Likewise, if you had characters in $phone_num, you would have a problem. They should be used together. I know that is kind of what you said, just emphasizing that validation is the 101 level class.

Validating your data and 'sanitizing your inputs' are 2 completely different things. Lumping them together is just another haphazard treatment of the core problem: Lazy practices that lead to more holes, not less.

You validate data based on the business rules that are applicable to it. Is the data type correct for the field? Is the phone number in the right format with the correct number of digits, etc. Those are your business rules.

Sanitizing your inputs revolve around data that your system cannot handle. Single quotes, double quotes, Unicode character sequences that you can't predict that break your escape sequences, etc. Sanitizing your inputs is a fools game you cannot win. As you stuff another finger into another fissure that's developing there will be more, and more until sooner or later you miss one. It only takes one to bring everything down. I know people doing this for a living. Every 3 months or so a new method of encoding illegal values gets brought to their attention when they fail an audit that tests for them, and off they go to the races, again...

How many input fields (GET or POST) are there on all your pages combined? This total is the minimum number of variables you have to filter properly to sanitize your inputs.
How many queries in your entire application? This is how many queries you have to convert to parameterized values. Any bets which one is less work? Any bets which one is less error prone? Any bets which one won't involve you munging the raw data so you're actually shoving crap into your database because you're doing it wrong? Yeah, that's right: Use Parameterized queries.

All output data should go through functions which will escape characters for html compatibility (so you can't get javascript/html injections into a page), -OR- treat them appropriate for the intent. ie: create a mailto field with an appropriately filtered field. There are a limited number of ways to output data and RAW isn't one of them. (And, if you find that one corner case where RAW -is- correct, fine. Do it. But it shouldn't be a default).

I'm fucking sick of seeing IT / Programmers getting dragged through the mud for this shit: It's Fixable TODAY, and FOREVER. And instead we keep doing it wrong and then we justify it.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
you need at least one character, an '@' sign, one or more characters, a '.', and one or more characters.

I know you were just losely typing as an example but before anyone thinks to just go and blindly do this sort of thing have a read up on the complexities. and at least absorb the line:

you have to know exactly what you're trying to match, and what not; and there's often a trade-off between what's exact, and what's practical.
 

norton_I

Ars Tribunus Angusticlavius
6,174
Subscriptor++
ronelson":l8esclto said:
However, sanitization is not the right solution to most security issues, especially SQL injection.
It is still part of it. If you are expecting an email address, you need at least one character, an '@' sign, one or more characters, a '.', and one or more characters. Sure, you can just use parameterized queries to ensure that the contents of $email do not screw up the DB, but you should also validate it to ensure that it has a good chance of retrieving data or populating/updating a row (SELECT * FROM USERS WHERE email = '(123)456-7890' better not return any results!). Likewise, if you had characters in $phone_num, you would have a problem. They should be used together. I know that is kind of what you said, just emphasizing that validation is the 101 level class.

The point is validation should done to conform to the application business rules, not to plug security holes from incorrect design.

While we are on the subject of validation, I should also point out that I see far more bugs due to over-zealous validation that inadequate validation, especially with respect to phone numbers and addresses -- although plenty of people have more trouble with names and email addresses. Too many developers think that they are experts in everything, If you are unsure, it is better to err on the side of permissiveness. If you are sure, you should ask yourself if that certainty is justified.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
over-zealous validation
I wish to really hurt, quite painfully[1], the people responsible for each and every occasion when, on entering my proposed password tell me 'you may only use the characters XXX'[2].

1. a chinese burn perhaps, or a dead arm...
2. IF this includes removing upper or lower case letters it's a good kicking round the bike sheds let me tell you.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
ShuggyCoUk":2g48p8qf said:
over-zealous validation
I wish to really hurt, quite painfully[1], the people responsible for each and every occasion when, on entering my proposed password tell me 'you may only use the characters XXX'[2].

1. a chinese burn perhaps, or a dead arm...
2. IF this includes removing upper or lower case letters it's a good kicking round the bike sheds let me tell you.

I get really annoyed when "+" isn't allowed in email addresses. If it weren't for it being improperly filtered out it would be a fantastic way to identify where spam mail originates from. you+arstechnica@gmail.com

Alas, so many sites filter it out it's almost useless.
 

Ardax

Ars Legatus Legionis
19,795
Subscriptor
[url=http:/civis/viewtopic.php?p=21552102#p21552102:3cakhfhq said:
ronelson[/url]":3cakhfhq]
Likewise, if you had characters in $phone_num, you would have a problem.
Why's that? If my phone number is most memorable for being 123-I-AM-HOTT, then dammit I want to be able to put that in every single fucking phone number field I can. :)
 

scHarvey

Ars Legatus Legionis
10,386
Wow, I had no idea this thread was still around.

Delirious":ddgrwei7 said:
Ok from what you've said, particularly in your last post... Why on earth are you passing strings that start with a $ when you know that's what PHP uses to identify variables? surely user_id should be a unique number or username in which case it should be ?user_id=monkey. The PHP code then should be $user_id=$_GET['user_id'];

These user ids that start with a $ were from the client in question, not something I had any control over. They set up the web service that passed the ID to me, so there wasn't a lot I could do about it.

It's all working now, so I've completely blocked it out as something that never really happened.
 

Delirious

Wise, Aged Ars Veteran
172
inpher":2ushprti said:
Delirious":2ushprti said:
Ok, I'm relatively new at this so explain; "input sanitation"?
It is internet security 101: You sanitize any and all data that you get from the user end. You do this for reasons of 1. security and 2. stability.

First reason: Security.
If you do not remove bad data from the input you prevent the user from changing, reading or deleting your database content. SQL injections are common (perhaps the most common) security breaches today. It works by sending your script data that would change your query into something new.

Let us say your PHP script is called with this URL:
Code:
http://www.example.com/form.php?user=12&form_id=account_details&action=update&email=mail@example.com

Your code would probably look something like this (shortened for brevity):

Code:
<?php
// Get form data
$action = $_POST['action'];
$email = $_POST['email'];
$user = $_POST['user'];
$form = $_POST['form_id'];

if ($form == "update") {
    // Build SQL update query
    $query = "UPDATE users SET user_email=$email WHERE user_id=$user";
}
// Then run the query, no code written because >99% of all security problems are already present in the code above
?>

I count three types (some occurring more than once) of security problems in the code above.
  • The code does not check that the $user is an integer by removing anything that is not in the range of [0-9] and that the remaining integer is the same as the logged in user has.
  • The code does not remove or escape unwanted data from any of the inputs. If I wanted to do something nefarious I could send something along the lines of
    Code:
    http://www.example.com/form.php?user=*&form_id=account_details&action=update&email=mail@example.com
    and have everyones account set to my e-mail address. Succeeding with this I am now a 1337 haX0r and can brag about it on 4chan. ;)
  • The code does not parametize or prepare the SQL query.
  • Other good things to use is LIMIT 1 as often as possible which might sometimes mitigate some damage. This is a pretty good beginners article, and I am sure someone on this forum will discover at least one security consideration that I have forgotten to mention above.
PHP has many halfbaked solutions like mysql_real_escape_string or similar functions. I blame the PHP developers for not providing a solid single function and I blame every goddamned tutorial on the net that disregards security in the name of laziness. I always recommend developers to use PDO, not only is it more secure, it is also provides rudimentary database abstraction and some other nice feature you may appreciate when you get into more advanced development.

Second reason: Stability.
If I happen to include a cite or some html code or odd glyph in the input I could potentially cause problems for your form (returning errors and such unfriendly for the user behaviour). For example the someone with the name O'Connor will have trouble submitting their name in some forms. If you escape/encode the user input O'Connor, Jönsson, 陈 (Chén) will be as happy as you are because you wrote good code.


Fair does, so it's validation? Just never heard it called "Sanitation" before >.> Then again, I feel stupid now because it should've been obvious >.<

@scHarvey: Glad you got it working, out of curiousity, what was the solution?
 

Ciso

Wise, Aged Ars Veteran
152
ronelson":2cbc077m said:
It is internet security 101: You sanitize any and all data that you get from the user end. You do this for reasons of 1. security and 2. stability.
It really is Input Validation 101. Even for programs that are not accessible from the internet or have no security implications.
Code:
Please enter a number from 1 to 10
> e
Stupid users :)

Technically that user input is correct. :)
 

scHarvey

Ars Legatus Legionis
10,386
Delirious":2e0lpvlb said:
@scHarvey: Glad you got it working, out of curiousity, what was the solution?


If I remember correctly we moved where the call to the web service was so that it was all within one function so that the shit data wasn't being passed around from page to page and then as soon as we authenticated the user with that foreign user_id we switched over to my systems internal user tracking and pretended like the $ never happened.
 

Delirious

Wise, Aged Ars Veteran
172
scHarvey":3djb6mxn said:
Delirious":3djb6mxn said:
@scHarvey: Glad you got it working, out of curiousity, what was the solution?


If I remember correctly we moved where the call to the web service was so that it was all within one function so that the shit data wasn't being passed around from page to page and then as soon as we authenticated the user with that foreign user_id we switched over to my systems internal user tracking and pretended like the $ never happened.


Sweet, I still say a nuke from orbit is the only way to be sure though...
 
Status
Not open for further replies.