Best option for persisting a string value between pages in Razor CORE - razor-pages

I want to display the user's name on each page after they log in. Once I've retrieved their name from the database, what's the best way of storing that name in terms of speed and complexity of code? I've looked at sessions and cookies as options but wondered which is better or if some other way (like persisting a base ViewModel) is recommended.
I just don't want to have to go back to the database each page just to display some simple text.

In the end I went with putting all the pretty into cookies and reading them in the _Layout page.
Write once, read many and as the values are stored on the end-user's computer so the browser can pick them up locally, rather than from the server in any fashion and if someone hacks the values, it doesn't matter as they're just used for prettification.

Related

Why the long hashes in AB testing cookies?

I was wondering if someone could explain why do websites using AB testing, have a very long hash stored inside a cookie.
In the context of a single page application, let's assume that I just want to show a different background color. I can store an "AB identifier", for example 0 or 1, inside a cookie when the user logs in, and then, in my javascript code, check for that cookie's value, and render the right color.
But why are others not using simple identifiers, and they use long hashes? I mean, this can't be a security thing right? Because, no matter how long the hash might be, it still needs to be readable by the client side (javascript), so the decoding script, which might be as simple as multiple if/else statements, is still available to everyone.
Thank you.
Techmaestro,
These things aren’t universal and depend on the tool, but typically these keys aren’t refering to your experience or a list of experiences, but rather a session key, just like your jsessionid cookie. The a/b server uses that to look up your a/b session, which isnt necessarily your HTTP session. The key has to be large to reduce the chance of collision.

How to sanitize data coming out of a database

This is my first question on stack overflow and I have taken a lot of time to search for the similar question but surprisingly could not find one.
So I read that no data should be trusted, whether from a client or that which is coming out of a database. Now while there are lots of examples that show how to sanitize data from a user ($_POST or $_GET), I could not find one that shows how the data from a database should be sanitized.
Now maybe it's the same as the data coming from a user / client (that's what I think it should be) but I found no example of it. So I am asking it just to make sure.
So for example if the result of a query yields as follows:-
$row=mysqli_fetch_assoc($result);
$pw = $row['Password'];
$id = $row['ID'];
$user = $row['Username'];
then do the variables $pw, $id and $user have to be sanitized before they should be used in the program? If so, then how ?
Thanks to all.
Your thinking is back to front here. By the time you are able to sanitise inputs using php, it's probably too late. The data is already in php. You don't sanitise inputs. You:
validate input & sanitise output
Normally a database is wrapped by the application tier. So the only data in there should have been filtered and escaped by your code. You should be able to trust it. But even then, in a relational database the data is fairly strongly typed. Hence there is little scope for attacking php from the data tier.
But you should be sanitising (escaping or encoding) any output. How you do that depends on where and how you are sending the data, hence it should be done at the point where it leaves php, not the point where it enters php. And the method you use (mysqli_escape, HTMLentities, base64, urlencode.....) Should be appropriate to where the data is going. Indeed it is better practice to change the representation of a copy of the data (and discard it after use) rather than the original.
It depends... How are you accessing this database? Who works on / maintains it? Going in is definitely a far bigger concern. However, if you wanted to sanitize it coming out of a database you need to know what you are sanitizing for. If you want to sanitize web traffic against XSS you'd probably want to remove all url's not on a whitelist, perhaps script tags and a few other things as well. Are you sanitizing data going into a C/C++ program? Then you probably want to make sure you're protecting yourself against buffer overflow issues as this is a legitimate avenue of attack.
I'm drawing some assumptions about your design here but I'm going to assume you're just working on the model aspect of an MVC application using PHP. PHP, in this case, has been most vulnerable to SQL Injection attacks on the backend, and XSS (cross site scripting) attacks on the front end. (NOTE: This isn't a PHP problem exclusively, this is a problem in all programming and different languages provide different solutions to different problems. Remember - you need to know what you're sanitizing for what reason. There is no one size fits all.
So really, unless you are sanitizing against something universal in all the code this model will sanitize for, you probably don't want to sanitize here. XSS would be a bigger concern to you now than sql injection... the way out is too late to stop an injection attack.
To take some liberty just to get the juices flowing - From a security standpoint, given your code seems to revolve around authentication, I would be much more immediately concerned around how you are storing and processing your credentialing data. A few things should definitely be doing:
Running the password through a secure, 1-way hash BEFORE storage (such as BCrypt).
Salting these hashes (with a different salt for EACH user) before storing them in the database to protect your user's data from things such as rainbow table attacks.
Using TLS for all communications.
Establishing and maintaining a secure session (track user-login without exposing password data with every single request sent, amongst other things).

Is a Modification Number to mask an Id in a query string necessary?

My coworker is insisting that the use of a global modification number to mask query string IDs is a good idea.
public static readonly int ModificationNumber = 9081234;
And Elsewhere:
_addressID = Convert.ToInt32(Request.QueryString["AddressId"]) - ModificationNumber;
I can't seem to get my head around this. If someone wanted to try some url hacking then a modification number makes no difference at all.
Are there other reasons this would make a site more secure?
Furthermore, are there explicit reasons this is bad? In my mind the less globals the better.
IMVHO your colleague is kind of on the right track, but not quite.
A good rule to follow is that you should never expose actual IDs in the query string, as that gives a clue as to the structure of your database, and makes it just that little bit easier for someone to carry out a SQL injection type attack (they can target specific records because they know the ID).
So your colleague is attempting to achieve this, albeit in a very round-about way. Personally I wouldn't do it this way because it will simply be a matter of time before a smart attacker works out what you are doing and then works out what the magic number is. It also doesn't really do anything to prevent a SQL injection attack against specific records, as the generated number may match an existing key anyway. If you are relying on this methodology to avoid SQL attacks then you have deeper issues that need to be addressed.
Edit
Mentioning an alternative is probably a fair thing to do.
As you are using C# and pulling parameters out of the querystring, I will assume you are using ASP.NET. In that case, important IDs can be kept in Session or the Cache. You can store a bunch of items in a custom data object, which you then store in Session (this saves having to keep track of lots of IDs, you just need to know one). ASP.NET manages the web app's Session for you, it is unique to each user, and you can use it to store stuff when you transition from page to page.
If you are manually tracking session or using a database to keep your session related info then you can still serialize the aforementioned data object into the database using a generated GUID as its key, and append that GUID to the query string (there is only an incredibly low chance of success if a user messes with a GUID to try and assume someone else's session, you can lower that chance even further by concatenating two GUIDs as a key, etc.).

Protecting application url

How do I protect the url generated by my application?
example
http://www.mydomain.com/jsp/get_article.jsp?id=1
how do I make these url unreadable to human beings?
What you can do is use a hash such as http://www.mydomain.com/jsp/get_article.jsp?hash=[base32 MD-5 hash value] or similar. Then you have a table hash -> article on the server (as hashes are unique enough, you don't have to care about "clashes" between the hashes of different articles). Of course, you would still have to have the hash on the client side, so you either have to calculate it there, or you have to simply give it within the page.
The hash would be the hash over the article itself, so it will be unique for the article at all times, and cannot be guessed without knowing the actual article. Titles are too easy to guess.
Howevery you look at it, you will not get perfect security from this, but you can get security from people trying to guess the URL without requesting the page before it. In other words, it's a lot of work without too much gain. But as you are trying to achieve a DRM scheme, it's probably the best you can get...
Not sure what you mean by "unreadable". I think the short answer is: It can't be done. The URL has to be visible to the browser or how will it request the resource? Your question sounds a little like saying, "How can I let people call me without telling them my telephone number?"
You could, I suppose, encrypt your URLs. But why?
If there is information in the URL that you don't want the user to see, then ... don't put it in the URL. Like, if you had a customer help system that directs users who give impossible answers to the "moron" section of your system, I wouldn't make the url be "http://example.com/help/moron.jsp?screen=17". Call it something non-descript. More seriously, you certainly should not make the customer's password or other confidential information part of the URL. Keep this sort of thing in data on the server side that is accessed via "safe" data, like a user id.

What should I be doing to secure my web form UI?

I have a mostly desktop programming background. In my spare time I dabble in web development, page faulting my way from problem to solution with some success. I have reached the point were I need to allow site logins and collect some data from a community of users (that is the plan anyway).
So, I realize there is a whole world of nefarious users out there who are waiting eagerly for an unsecured site to decorate, vandalize and compromise. If I am really lucky, a couple of those users might make their way to my site. I would like to be reasonably prepared for them.
I have a UI to collect information from a logged in user and some of that information is rendered into HTML pages. My site is implemented with PHP/MySQL on the back end and some javascript stuff on the front. I am interested in any suggestions/advice on how I should tackle any of the following issues:
Cross Site Scripting : I am hoping this will be reasonably simple for me since I am not supporting marked down input, just plain text. Should I be just scanning for [A-Za-z ]* and throwing everything else out? I am pretty ignorant about the types of attacks that can be used here, so I would love to hear your advice.
SQL injection : I am using parametized queries (mysqli) here , so I am hoping I am OK in this department. Is there any extra validation I should be doing on the user entered data to protect myself?
Trollish behaviour : I am supporting polylines drawn by the user on a Google Map, so (again if I am lucky enough to get some traffic) I expect to see a few hand drawn phallices scrawled across western Europe. I am planning to implement some user driven moderation (flag inaproriate SO style), but I would be interested in any other suggestions for discouraging this kind of behavior.
Logins : My current login system is a pretty simple web form, MySQL query in PHP, mp5 encoded password validation, and a stored session cookie. I hope the system is simple enough to be secure, but I wonder if their are vulnerabilies here I am not aware of?
I hope I haven't been too verbose here and look forward to hearing your comments.
Your first problem is that you are concerned with your UI. A simple rule to follow is that you should never assume the submitted data is coming from a UI that you created. Don't trust the data coming in, and sanitize the data going out. Use PHP's strip_tags and/or htmlentities.
Certain characters (<,>,",') can screw up your HTML and permit injection, but should be allowed. Especially in passwords. Use htmlentities to permit the use of these characters. Just think about what would happen if certain characters were output without being "escaped".
Javascript based checks and validation should only be used to improve the user experience (i.e. prevent a page reload). Do not use eval except as an absolute last resort.
Cross Site Scripting can be easily taken care of with htmlentities, there is also a function called strip tags which removes the tags from the post and you'll note that this allows you to whitelist certain tags. If you do decide to allow specific tags through in the future keep in mind that the attributes on these tags are not cleaned in any way, this can be used to insert javascript in the page (onClick etc.) and is not really recommended. If you want to have formatting in the future I'd recommend implementing a formatting language (like [b] for bold or something similar) to stop your users from just entering straight html into the page.
SQL Injection is also easily taken care of as you can prepare statements and then pass through the user data as arguments to the prepared statement. This will stop any user input from modifying the sql statement.
CSRF (Cross-Site Request Forgery) is an often overlooked vulnerability that allows an attacker to submit data from a victims account using the form. This is usually done either by specifying your form get string for an img src (the image loads for the victim, the get loads and the form is processed, but the user is unaware ). Additionally if you use post the attacker can use javascript to auto-submit a hidden form to do the same thing as above. To solve this one you need to generate a key for each form, keep one in the session and one on the form itself (as a hidden input). When the form is submitted you compare the key from the input with the key in the session and only continue if they match.
Some security companies also recommend that you use the attribute 'autocomplete="off"' on login forms so the password isn't saved.
Against XSS htmlspecialchars is pretty enough, use it to clear the output.
SQL injection: if mysql parses your query before adds the parameters, afaik its not possible to inject anything malicious.
I would look into something else besides only allowing [A-Za-z]* into your page. Just because you have no intention of allowing any formatting markup now doesn't mean you won't have a need for it down the line. Personally I hate rewriting things that I didn't design to adapt to future needs.
You might want to put together a whitelist of accepted tags, and add/remove from that as necessary, or look into encoding any markup submitted into plain text.

Resources