Parse id in URL in encrypted form to prevent sql injection - parsing

snatching my hair to fix this problem but I can't.
I am parsing id in url to pull data on next page according to that id. So rather than parsing id=123 I encrypted it something like process.php?token=TG4n6iv_aoO7sU3AngFY4WLSppLvueEoh-MnYE6k7NA, and decrypted it on process.php page by collecting it with $_GET, before using it in sql query. This is not proper URL, I need url like process.php?token=9878799889 and I need to decrypt this 9878799889 on process.php which would give me my original user id.
So here I can not use md5 or base64_encode which give me ugly string.
What would be best thing to do here?
id is unique so generated long digits should be unique as well and not easy to guess.
Right now I am using encrypt logarithm with salt. Actually want to parse like www.sitename.com/process/token/9878799889..this can be achieve with .htaccess so not worried about it..
Any help will be much appreciated..

What you could do is add an association table in your databse, which would contains a UUID as primary key (a randomly generated number) and your true ID reference (and other information you may want to store there, like a "valid until" date or other things...)
You'd have to generate the entry in that table as you parse the UUID
let's say INSERT INTO uuid_table (uuid, real_id) VALUES (9878799889, 123);
now when you process the url process.php?token=9878799889
you would only have to SELECT real_id FROM uuid_table WHERE uuid=9878799889;
it would retern the read id 123
You should also DELETE FROM uuid_table WHERE uuid=9878799889 when you're done.
Note that it would also work with md5 or base_64, but indeed it makes the url uglier.

Related

How can I secure this form post from manipulation

I have a very unique situation. I am building an application where a user uploads a QR code to my site, and when decoded, it has a matching ID already stored in the DB (as in I already have a record of the qr code before the user uploads it)
When they upload it, I decode it, which is a base64 string like so 6BbW0pxO0YENxn38HMUbcQ==
Like I said, That code corresponds to some information, and after they upload the QR image, I redirect them to one more page, which shows them the qr code, the corresponding information stored in the DB, and they are also prompted with a submit button. When pressed, I take note that they have confirmed, and I do some other things.
To elaborate
As a user I go to www.url.com/code/upload and upload an image. I am then redirected to /code/new with the page displaying the data stored in the DB from the correspond decoding of the image.
How can I make the submit button on /code/new reliable? Here are the solutions I can think of, and their vulnerabilities
Propagate /code/new with the correspond data stored in the DB, lets say #username and #movie into a form, with a submit button and POST the data to the server
This is dangerous because I don't think anything stops someone from editing the DOM and changing #username and #movie to something else
Pass the unique base64 identifier in the parameters such like, /code/new?id=STRING
Then when you submit, the string gets passed to the handling controller action, but i feel that this is not safe because then users can attempt to guess the strings and make concurrent post requests.
Essentially, I have a user upload a qr code, and after submission, I need to verify to verify that they were the one that uploaded the image. I lose all state, and information after they upload the image.
A proposed solution:
After the user uploads the image, create a unique string and store it in the session and also a record in the database (A user is logged in, so its the current_user.session_token), then when the user clicks submit on /uploads/new, I grab the session token, and verify that the current_user.session_token == session_token.
At this point, I can only verify that the current user was the one that uploaded the image.. I then need to somehow grab the base64 string that was from the uploaded QR code.
Another proposed solution: I temporarily put the base64 string as an attribute of the user when they upload the file. So I will have current_user.session_token and current_user.base64_string. Then when the user clicks on the 2nd submit button, I do something like
#check if the user's token is equal to the sessions, and the string is not nil
if current_user.session_token == session_token && !current_user.base64_string.nil?
data = current_user.base64_string
#hooray! I have the QR code
end
Then delete the session token, and then delete the current_user's base64_string and session_token
if a malicious user attempts to forge their session token, it won't match their's store in the database, then when I handle the post request, I will not proceed. But If a legitimate user makes the second post request, the session Id matches, and I am able to grab the base64 string.
TL;DR, I need 2 concurrent post requests that carry the information without losing it, and can verify that both the first and second post requests were done by the same user.
If anyone had the patience to read through that, I appreciate it! if there are any suggestions I would greatly appreciate it, or if you think my solution is sufficient or not, please let me know. Thanks!
Sign the parameters generated from the first request, and verify the signature when you process the second request.
The technology to use for this is HMAC. Here's how to use one version available in Ruby:
require 'openssl'
secret = 'ABCDEFGHIJKLMNOP'
data = 'user:code'
signature = OpenSSL::HMAC.hexdigest( 'sha256', secret, data )
p signature
Output:
"bd7194c0604902d6594694d25e7f27bdc2d10926638e0ce8bdda3f6debb37f6a"
This is how you can use it to link two HTTP routes together so that the second one can trust that parameters sent to it via the first one have not been tampered with:
When the first route is called, generate or fetch a secret. It is important that this secret value is not ever sent or exposed to the end user. It can simply be application configuration (which then applies to all linked requests), but if you can store it associated with perhaps the QR code, then the strongest protection is to generate a long random string just before creating the signature, and to store it ready to use to confirm the second step. Something like SecureRandom.hex is great for a short-term secret if you have somewhere server-side to store it.
Combine all the parameters on the form that you want to be tamper-free into one long message. Easiest thing to do is .join them in an array, and you should use a delimiter that is not allowed in any value, and that you are also not accepting due to validation. This string is the value to use for data in the example.
Generate the form that calls the second route. In addition to the params you want to accept at next stage, add the signature value generated as above. Do not send the value of secret to the client by putting in the form or cookie etc.
When you receive the request from the second route to finalise the multi-stage request, generate the signature from the user-sent params (after validating them), and compare with the one sent to you from the form. If it is the same, then the request is valid. If it is different then the data may have been tampered (provided you have no bugs - do check things such as consistent character encoding if any param can contain non-ASCII characters)
Provided you have kept the secret truly secret from the end user, they have next to no chance of generating a correct signature. Only your code in routes one and two knows how to do it (because it has access to correct secret, not because of any special fact on how it is written). Therefore you can trust that the values have not been modified.

Redirecting URL in JBOSS AS 7

Hi everyone currently i am passing query string in my url like
ip:port/contextroot/page.jsf?id=22&tsid=1234
the query string is a user id and tsid. the doesnt specifically need to type in the query string values. my requirement is to hide the query string in the url and still be able to use the query string values in my app. i was thinking if there is a way to strip off the query string using jboss redirection.
To Summarize:
i wanna access my page.jsf like
ip:port/contextroot/page.jsf
and still get id and tsid from the query string.
any help is geartly appreciated.
thanks in advance :)
On your .NET application, encrypt all sensible data using a symmetric cipher (e.g. AES), then POST it to a JBOSS servlet. In that servlet, decrypt the transmitted data and store it in a session scoped bean. This way, you can subsequently access the data from your beans without needing to carry it aound in GET params.
I think you're looking for Pretty Faces ( http://ocpsoft.org/prettyfaces/ )

is there a simple way to get URL in java

I am working on an email validation link for a website. When a user registers and finishes filling in their personal data (and it passes all the checks), they are sent to a jsp page saying that an email has been sent to the address they entered as the username, with a link to click to validate the email address. So that part is all well and good, I generate the link (for now just using my localhost) and it looks like this as an example http://localhost:9999/javawork/msc/validate/?6FRQ8RAT&u=1s3w1Iih64egX01188HT. When they click the link it goes to the jsp page index.jsp in the validation folder. At this point I need to grab the entire URL and send it to a function to make sure the URL is formatted properly (for security purposes). If it passes and the format is fine, I need to grab the 8 digit code immediately after the '?' and also the value of 'u'. I then send those values to a function that checks that they match what we have in our DB, and if they do, I update the DB record with a validation date so we know they have validated their email address.
So my question is first, how do I grab the entire URL to check the format, and second, how do I grab the 8 digit code, and the value of 'u'? I have been looking online and all examples require creating multiple functions or classes, and using the URL class. And they all want me to make an instance of a URL object and initialize it using the entire URL. But it is not a static URL, it will be different for every user that registers, as it generates a random 8 digit code to check against, and the value of 'u' is the masked user id from the DB. I don't understand how it can require you to initialize the entire URL in order to get the values, when you don't know what the values are until you get them from the URL.
Is there a simple way to grab the values, and the entire URL? Even if I can just get everything after the '?', I know the base URL and can build a new String to check the formatting if I can get from the '?' and after. Please help with that part. Thanks.
The Interface HTTPServletRequest contains a method getRequestURL which returns a StringBuffer which you may use to check the format of the entire URL.
You can get it, in a jsp page with :
<%=request.getRequestURL()%>
If you are using the format of request that you specified above, then your second question :
how do I grab the 8 digit code, and the value of 'u'?
May be answered by manipulating that StringBuffer to split at the ? and & for the 8 digit code.
Or use another request method,
ServletRequest.getParameter(java.lang.String name)
To grab each parameters, though, i'm not certain how it will end up handling the unnamed parameter of the 8 digit code. Let me know how that goes.
Don't think of the 8-digit code as an unnamed parameter. Think of it as a parameter without a value.
request.getParameterNames() will give you the 8-digit code as well as "u". So you can loop through like so:
String code = "";
for(String paramName : request.getParameterNames()) {
if(!paramName.equalsIgnoreCase("u"))
code = paramName;
}

Multiple key/value pairs in HTTP POST where key is the same name

I'm working on an API that accepts data from remote clients, some of which where the key in an HTTP POST almost functions as an array. In english what this means is say I have a resource on my server called "class". A class in this sense, is the type a student sits in and a teacher educates in. When the user submits an HTTP POST to create a new class for their application, a lot of the key value pairs look like:
student_name: Bob Smith
student_name: Jane Smith
student_name: Chris Smith
What's the best way to handle this on both the client side (let's say the client is cURL or ActiveResource, whatever..) and what's a decent way of handling this on the server-side if my server is a Ruby on Rails app? Need a way to allow for multiple keys with the same name and without any namespace clashing or loss of data.
My requirement has to be that the POST data is urlencoded key/value pairs.
There are two ways to handle this, and it's going to depend on your client-side architecture how you go about doing it, as the HTTP standards do not make the situation cut and dry.
Traditionally, HTTP requests would simply use the same key for repeated values, and leave it up to the client architecture to realize what was going on. For instance, you could have a post request with the following values:
student_name=Bob+Smith&student_name=Jane+Smith&student_name=Chris+Smith
When the receiving architecture got that string, it would have to realize that there were multiple keys of student_name and act accordingly. It's usually implemented so that if you have a single key, a scalar value is created, and if you have multiples of the same key, the values are put into an array.
Modern client-side architectures such as PHP and Rails use a different syntax however. Any key you want to be read in as an array gets square brackets appended, like this:
student_name[]=Bob+Smith&student_name[]=Jane+Smith&student_name[]=Chris+Smith
The receiving architecture will create an array structure named "student_name" without the brackets. The square bracket syntax solves the problem of not being able to send an array with only a single value, which could not be handled with the "traditional" method.
Because you're using Rails, the square bracket syntax would be the way to go. If you think you might switch server-side architectures or want to distribute your code, you could look into more agnostic methods, such as JSON-encoding the string being sent, which adds overhead, but might be useful if it's a situation you expect to have to handle.
There's a great post on all this in the context of JQuery Ajax parameters here.
Send your data as XML or JSON and parse whatever you need out of it.

How to avoid conflict when not using ID in URLs

I see often (rewritten) URLs without ID in it, like on some wordpress installations. What is the best way of achieve this?
Example: site.com/product/some-product-name/
Maybe to keep an array of page names and IDs in cache, to avoid DB query on every page request?
How to avoid conflicts, and what are other issues on using urls without IDs?
Using an ID presents the same conundrum, really--you're just checking for a different value in your database. The "some-product-name" part of your URL above is also something unique. Some people call them slugs (Wordpress, also permalinks). So instead of querying the database for a row that has the particular ID, you're querying the database for a row that has a particular slug. You don't need to know the ID to retrieve the record.
As long as product names are unique it shouldn't be an issue. It won't take any longer (at least not significant) to look up a product by unique name than numeric ID as long as the column is indexed.
Wordpress has a field in the wp_posts table for the slug. When you create the post, it creates a slug from the post title (if that's how you have it configured), replacing spaces with dashes (or I think you can set it to underscores). It also takes out the apostrophes, commas, or whatnot. I believe it also limits the overall length of the slug, too.
So, in short, it isn't dynamically decoding the URL into the post's title--there's a field in the table that matches the URL version of the post name directly.
As you may or may not know, the URLs are being re-written with Apache's mod_rewrite module. As mentioned here, Wordpress is, in the background, assigning a slug after sanitizing the title or post name.
But, to answer your question, what you're describing is Wordpress' "Pretty Permalinks" feature and you can learn more about it in the Wordpress codex. Newer versions of Wordpress do the re-writing internally (no .htaccess editin, wp_rewrite instead). Which is why you'll see the same ruleset for any permalink structure.
Though, if you do some digging you can find the old rewrite rules. For example:
RewriteRule ^([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/?$ /index.php?year=$1&monthnum=$2&day=$3 [QSA,L]
Will take a URL like /2008/01/01/ and direct it to /index.php?year=2008&monthnum=01&day=01 (and load a date category).
But, as mentioned, a page like product-name exists only because Wordpress already sanitized the post title and stored it as a field in the database.

Resources