How to encode decode string in thymeleaf - spring-mvc

I want to encode string or any primitives values in Thymeleaf and decode same on server, mostly path variable or in hidden fields. Actually i want this due to security reasons.
Effort
<a th:href="#{/administrator/{id}edit/(id=${data.id})}" class="instructionbt">Edit</a>
This is a simple link to edit data and can be see in url something like this:
localhost:8080/testapp/administrator/1/edit
but i want something like
localhost:8080/testapp/administrator/$Htf1w==/edit
Now can replace 1 by 2, 3 even any number and can edit any data. I want that 1 (the id field) must be encode, so that id will be hard to guess and a normal user will not edit url directly.
I have search a lot on internet, but i did not found any clue. I know i can use Base64Utils or any similar class to achieve, but question is how to do in Thymeleaf.
Please friends help me. I am stuck in my project and i am having very less time.

A normal user will not edit the URL anyway. A user that is not "normal" will never be stopped by Base64. That is for sure and that is why you won't find anything on the Internet. You need to protect the resource server side - e.g. check if number 1 belongs to the current user and he can edit it.
Skipping these checks is a very common security bug and is part of the OWASP Top 10 list. It is A4-Insecure Direct Object References. Please read more about this vulnerability and how to prevent it. In short:
Each use of a direct object reference from an untrusted source must include an access control check to ensure the user is authorized for the requested object.

Related

Prevent users change of hidden field value

I'm currently developing one project and I just discovered that the value of hidden fields can be edited. So that causes me a problem of security.
Imagine that I have a form to edit personal information. Currently, the form has a hidden input that has the value of the primary key. So if someone change that value can update data from another people.
I already check here and on google and found a possible solution on https://mvcsecurity.codeplex.com/. But unfortunately, that's not available to the recent version of ASP.NET MVC.
So I want to know if someone knows the properly way to prevent that.
The short answer is, Never trust data coming from client!
You should never trust data coming from a client browser. It can be altered by the end user. So don't simply trust the value. Always do needed validations on server side to make sure that the data / operation is valid.
In your specific case, When the form is submitted, you should check the value of the hidden field (the primary key value of the record being edited) is valid for the current user to be edited. Depending upon your systems user permissions/role system, you can do some if checks and determine whether the current user is authorized to do this operation with the value coming from client.
One solution is to encrypt the primary key before putting it in the hidden variable. That's the approach alot of site use, although often the encrypted var will be in the query string.

Script exploits in ASP.NET - Is setting validateRequest="true" good advice?

I was reading about ASP.NET Script Exploits, and one of the suggestions is: (emphasis is mine; and the suggestion is #3 in section "Guarding Against Scripting Exploits
" in the web page)
If you want your application to accept some HTML (for example, some formatting instructions from users), you should encode the HTML at the client before it is submitted to the server. For more information, see How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.
Isn't that really bad advice? I mean, an exploiter could send the HTML via curl or something similar, and the HTML would then be sent un-encoded to the server, which can't be good(?)
Am I missing something here or mis-interpreting the statement?
Microsoft is not wrong in their sentence, but on the other hand far from complete, and their sentence is dangerous.
Since by default, validateRequest == true, you indeed should encode special HTML characters in the client in order for them to get into the server in the first place and bypass validateRequest.
But - they should have emphasized that this is certainly not a replacement for server side filtering and validation.
Specifically, if you must accept HTML, the strongest advice is to use white-listing instead of black filtering (i.e. allow very specific HTML tags and eliminate all the others). Use of Microsoft AntiXSS library is highly recommended for strong user input filtering. It's far better than "re-inventing the wheel" yourself.
I don't think that advice is good...
From my experience I would totally agree with your thought and replace that advice with the following:
all input has to be checked server-side first thing on arrival
all input that can possibly contain "active content" (like HTML, JavaScript...) has to be escaped on arrival and never be sent to any client till full sanitazion took place
I would never trust the client to send trusted data. As you stated there are simply too many ways that data can be submitted. Even non-malicious users may be able to bypass the system on the client if they have JavaScript disabled.
However on the link from that item it becomes clear what they mean with point 3:
You can help protect against script exploits in the following ways:
Perform parameter validation on form variables, query-string
variables, and cookie values. This validation should include two types
of verification: verification that the variables can be converted to
the expected type (for example, convert to an integer, convert to
date-time, and so on), and verification of expected ranges or
formatting. For example, a form post variable that is intended to be
an integer should be checked with the Int32.TryParse method to verify
the variable really is an integer. Furthermore, the resulting integer
should be checked to verify the value falls within an expected range
of values.
Apply HTML encoding to string output when writing values back out
to the response. This helps ensure that any user-supplied string input
will be rendered as static text in the browsers instead of executable
script code or interpreted HTML elements.
HTML encoding converts HTML elements using HTML–reserved characters so
that they are displayed rather than executed.
I think that this is just a case of a misplaced word because there is no way you can perform this level of validation on the client and in the examples contained in the link it is clearly server side code being presented without any mention of the client.
Edit:
You also have request validation enabled by default right? So clearly the focus of protecting content is on the server as far as Microsoft is concerned.
I think the author of the article misspoke. If you go to the linked web page, it talks about encoding data before it's sent back to the client, not the other way around. I think this is just an editing error by the author and he intended to say the opposite.. to encode it before it's returned to the client.

How to encrypt the address bar url using asp.net?

How to encrypt this url in asp.net (VB.NET), so that user cannot view this address bar text in their browser address bar ?
http://localhost:2486/volvobusesindia/passenger_info.aspx?from=Delhi&to=Manali&journey=21-Nov-2010
You can't. And before someone suggests using POST, that doesn't really hide anything. It's trivial to use Wireshark, Firebug, etc. either way.
Any communication between the user's machine and your server, in either direction, encrypted or unencrypted, can be monitored by the user.
EDIT: An alternative is to generate a unique GUID or session identifier, then keep track of the meaning on the server. This is not encryption, but it may serve the desired purpose.
You can do some really good obfuscating, but you probably want to roll-your-own, as if you are using this for security, you don't want everybody knowing how to decode your encoding.
We do it by using a single querystring parameter that contains ALL of the information we need from the request in our own format. Of course, this does mean giving up all of the handy .Request[] methods, but you've got to make the trade off somewhere.
The full path to a file with the fully encrypted URL also can get obscenely long with everything thrown in there. For example, this is a link that will display an image of a ring with the word "Landrum" on it (in both directions). The image is created the moment you request it, from the information contained in the encrypted query string.
http://www.flipscript.com/data/default/images/catalog/medium/AMBIRingTitanBlue_G1F88E4X57,409-945,591O0M0S2V6.jpgx?xq=45C35129$6zvtnw6m1280kwz8ucqjt6jjb2vtea43bio5ixmnge-5r4i-o1o32j43y58nv
I hope that helps a bit! There is no "out of the box" solution, but this one works pretty well.
Instead of hiding it, you could call this site internally from within some other site and do whatever you wish with the returned results (e.g. display them on your site). That would guarantee you that the user won't ever have the chance to see the actual site being called.

Auto-generated Form Value

Looking for guidance on how to achieve something in ASP.NET Web Form - the behaviour is a bit like that seen in ASP.NET AutocompleteExtender, but I can't find anything that gives the flexibility I need. Here is what I am trying to do:
2 TextBox fields on the form,
CompanyName and CompanyRef
(CompanyRef an abbreviated unique
Company identifier)
User types in the CompanyName
As soon as there are 3 characters in the
CompanyName an internal webservice is
called (AJAX?)
Webservice checks what has been entered so far and
evaluates a 3 character representation of it - for instance
"Stack" would be returned as STA0001.
If there is already an STA0001 in the db it would return STA0002 and so on
The value returned would be targetted at the
CompanyRef TextBox
User needs to be able to edit the CompanyRef if they so wish
I'm not looking for code per se, more high level guidance on how this can be done, or if there are any components available that I am missing that you may be able to point me in the direction of. Googling and searching on SO has returned nothing - not sure if I'm looking for the right thing though.
Generating the CompanyRef is easy enough. There are lots of articles etc which cover combining say an autonumber or counter with a string. The difficulty I have with your approach is that you intend to let users fiddle with the ref, and make their own up. What for?
[EDIT - Follow up to comment]
The comment box didn't allow for enough characters to answer your comment fully (and I'm still getting used to the conventions in place here....)
You could use AJAX to call the web service and return currently available values, and then use javascript to update the field. The problem with this is that once a user has decided he or she likes one, it may no longer be available when it is passed back to the database. That means you will have to do one final check, which may result in a message to the user that they can't now have the value they were told was available when they started the process. Only you know the likelihood of this happening. It will depend on the number of concurrent users you have.
I've done an article on calling web services etc using jQuery which should give you a starting point for the AJAX part: http://www.mikesdotnetting.com/Article/104/Many-ways-to-communicate-with-your-database-using-jQuery-AJAX-and-ASP.NET

Query String Parameters make my app at risk?

I'm writing an Asp.Net WebForms app where I am calling an edit page an passing in the data about the record to be edited using query string parameters in the URL.
Like:
http://myapp.path/QuoteItemEdit.aspx?PK=1234&DeviceType=12&Mode=Edit
On a previous page in the app, I have presented the user with a GridView of screened items he can edit based on his account privileges, and I call the edit page with these above parameter list, and the page know what to do. I do NOT do any additional checking on the target page to validate whether the user has access to the passed in PK record value as I planned to rely on the previous page to filter the list down and I would be fine.
However, it is clear the user can now type in a URL to a different PK and get access to edit that record. (Or, he may have access to Mode=View, but not Mode=Edit or Mode=Delete. Basically, I was hoping to avoid validating the record and access rights on the target page.
I have also tested the same workflow using Session variables to store PK, DeviceType, and Mode before calling the target page, and then reading them from Session in the target page. So there are no query string paramaters involved. This would take control away from the user.
So, I'm looking for feedback on these two approaches so that I choose an accepted/standard way of dealing with this, as it seems like a very common app design pattern for CRUD apps.
Agreed, you'll want to validate permissions on the target page, it's the only way to be absolutely sure. When it comes to security, redundancy isn't a bad thing. Secure your database as if you don't trust the business layer, secure your business layer as if you don't trust the UI, and secure the UI as well.
You should always validate before the real execution of the action, especially if passing the parameters by query string. For the second page that does the execution you might not need as much feedback for the user since you do not have to be nice to the user if he tries to cirumvent your security, so error handling should be a lot easier.
Passing the variables per session is acceptable but imho you should still validate the values.
We always use querystrings so records can be bookmarked easily, however always validate in both places, if you write you access control code nicely it should just be a case of re-using the existing code...
I believe the common practice is to do what you're avoiding: On the original page, you need to check to see what the user should have capabilities to do, and display their options appropriately. Then on the actual work page, you need to check the user again to verify they are allowed to be there, with access to that specific task.
From a usability standpoint, this is what the user would want (keeps it simple, allows them to bookmark certain pages, etc), and security on both pages is the only way to do this.
If you really don't want to check access rights on the target page:
You could hash the PK with the UserID and then add the hash value to the query string.
string hash = hashFunction(PK.toString() + UserID.toString());
Then you have to make sure the hash in the queryString equals the hash value calculated before loading the page.
Assuming this is an internal organization Web application.
Session variables can be manipulated as well, although not as easily. Whatever authentication you're using throughout your site, you should definitely use on your target page as well. Otherwise, you'll be open to exposing data you may not want as you have found out.
You could do the following to make your URLs a bit more secure:
-Use Guids for Primary Keys so users cant guess other record ID's
-The Mode couls be implicit: Guid = Edit, no Guid = New
and..
-Server-side validation is the only way to go.

Resources