Passing a token securely from one controller method to another - ruby-on-rails

I want to generate a random token for my user. For UX reasons, I want to generate this token in MyController#new in order to show it in new view. Then I need to pass it to create method. However, I want to prevent user from changing it.
I know of 3 ways to do it:
pass it as hidden field
pass it through sessions
write it to database, marked as incomplete, then set it to complete in create method
The first two approaches are not secure, while the last is overkill.
Is there a way to securely pass a parameter from new to create method in controller?

Sessions in Rails and # and above are very very secure because they are hashed. The official library says there are no practically evidences of session hash been compromised so the user can only delete that token from the browser but they can't change it to a logically correct value.
What you can do is save the value in sessions and make a hash value yourself from that token and save it also in session then on the receiving side you can regenerate the hash from the session and verify the value.
no user can edit both the session values that they match. If its not matching you can discard the values and throw to an error page.
I hope i answered you, if there is any misunderstanding pls ask.

Related

Can I safely tell Rails to remember the result of an expensive instance method?

My current_user has a has_privilege? method which calls the database to check whether this user has a certain admin privilege or a superceding one (system is similar to Wordpress privileges). As has_privilege? gets called several times per page, can I tell Rails to remember the result for as long as the instance exists, using the method explained at How can I save the value of an instance method?, or would this make the app insecure? It's a bad idea to put this information into the session variable or cache, right?
as long as the instance exists
It depends what you mean by that.
Rails treat each HTTP requests in a separated process so you can cache the has_privilege? method output for the current request (so calling many times the method will query the DB only the first time), but on the next request, it will be executed again and then cached (and actually you want that as you may change the permissions and don't want the user to keep the old permissions).
In order to do so you can use this simple trick:
class User < ActiveRecord
def has_privilege?
#has_privilege ||= begin
# You code here. The returned value will be cached in #has_privilege.
end
end
end
So the first time the method is called, #has_privilege is nil for your instance of the user, so the || will its right side part which is the = begin ... end.
Excepted if the code return nil, the value will be assigned to #has_privilege.
On the next call, #has_privilege is no more nil, therefore || will no trigger its right side part and return immediately.
I need a cross request cache
In this case, you have to go with JWT and save the value in the token.
JWT is a token generated and signed by the server, and it must be sent back in to each requests, otherwise the server will reject it.
As only the server can sign the token, in the case the user tries to change it, the server will reject and sign out the user.
You can read more on their website, it's quite simple to use.

How do you create a unique identifier for users for tracking purposes?

I would like to be able to add a user referal params on all invite links sent out from my site... example:
http://site.com/invited_by?=ajraux
How can I generate a code that is short like "ajraux" for all users on my site? Does it need to be a field in the database? Can it be created on the spot? How are web companies doing this?
Thanks
You could create random numbers and encode them in base-36, something simple like this:
rand(1e12).to_s(36)
Generate one for each user on first use and store it with the user. Add a unique constraint on your random token (in both your model and the database) and generate a new one if you get a uniqueness violation. You might want to log a warning somewhere that you'll see it if you need to try more than, say, five times to get a unique value; if you start getting a lot of warnings then bump that 1e12 up to 1e15 (or higher).
That would give you a random looking token attached to each user, the tokens would be URL-safe, they're quick and easy to generate, you shouldn't get that many collisions, and it will be easy to backtrack from a token to the user.
One way of doing this is to use the unique identifier of the user, say "id", that's in the database, but this is also dangerous because you are revealing too much about your database.
So you can add a twist to the previous situation and encrypt and decrypt the id so that when it's in the url it is encrypted and then when you receive it you can decrypt it and use it.
As cjapes said, using ID is not a good solution and mu is too short's answer is good for most cases. However if you have a site which offers vanity URLs, like about.me does then each user will have a permalink kind of column storing their vanity URL. You can just use the value from that column when building the URL.
On the receiving end you can do:
#referring_friend = User.find_by_permalink(params[:permalink])

Thoughts regarding model ids in rails routes and validation

I am new to RoR and started working on a typical 'has_many' association (ie. a user has many friends). I have everything working correctly, but I don't like having the ids exposed in the url. I find that I need to add extra validation in my controller to make sure the ids represent valid associations in case the user manually entered different ids.
Personally I would like to see the ids out of the url and passed via some other means but that is not always possible. Shallow nesting of resources will help reduce the number of ids I need to validate at least.
What is the RoR philosophy on this? I have not seen anything specific to this issue.
Thanks
the URL has parameters if it is a GET url.
Try using POST parameters, which means your url will no longer be cluttered. Note that a malicious user can still send a made-up POST request using curl.
My approach to this is implementing proper authorization. If the user requests information for an object he is not permitted to read, this should be handled by an authorization framework.
With CanCan or Declarative Authorization you can define rules that replace your "manual" (and error-prone) checks in controllers.
I like the IDs being in the URL. That is what REST is about. Getting information for specific Resources, which have to be identified with an ID.
You can use Friendly ID in order to replace the integer ID by a slug (e.g. users/tollbooth instead of users/42).
basically ror routes by default takes id as key to generate urls. If you are not fan of id based urls then you can always override urls by using to_param inside model.
def to_param
# make sure this field is always present & unique
username
end
then by default you will start seeing username instead of id inside urls
How to find object inside controller actions
User.find_by_username(params[:id])
If you dont want to do this manually make use of slug gems like friendly id

Rails 3 Cookie Based Sessions Question

With Rails 3, the default session storage mechanism is cookie_store. I assume that this means that the contents within the session hash are serialized, encoded and stored within a cookie in the browser? Does this mean that nothing (or very little) of the session is stored in the server?
I've had a few issues where I had a cookie overflow error and I'm assuming because I kept on adding to my user instance (which was also linked/fetched from the cookie).
u = session[:user]
u.add_this lots_of_data
so eventually I got a cookie overflow error.
Am I correct about this? Are sessions fully stored within cookies in Rails 3 (by default)?
Yes, if you use the cookie store, the session data is stored in the cookie. If you'd like to store it on the server, you will need to use another session store.
However, if you are storing model objects or "lots of data" in the session, you are most likely doing it wrong in the first place. Your data should go to the database, and the session should only contain as much information as you need to retrieve it.
In you case, this would mean to store the user id int he session, and load the user from the db in a before_filter.
Yes, you are right. The problem might come up if you keep on adding data to session.
But there are some other things that affect it.
Once, I ended up with CookieOverflow error, and the reason was the flash[:notice] messages.
If you use flash[:notice] = "message" and then redirect, the text "message" will be stored in the cookie. If the size of the text u pass is more than 4KBs, you get "CookieOverflow" error

Generate temporary URL to reset password

I am looking to implement a Forgot Password feature on my website. I like the option where an email containing a temporary one-time use URL that expires after some time is sent to the user.
I have looked at the following pages to get these ideas but I am not sure how to implement this using ASP.NET and C#. As one of the users indicated, if I can implement this without storing this information inside the database, that will be ideal. Please advise.
Password reset by emailing temporary passwords
Thanks.
Probably the easiest way is going to be to modify your users table to add 2 extra columns, OR if you don't want to modify the existing table you could add a new dependent table called "UserPasswordReset" or something like that. The columns are like this:
PasswordResetToken UNIQUEIDENTIFIER,
PasswordResetExpiration DATETIME
If you go with the additional table route, you could do also add the UserID column, make it a primary key and a foriegn key reference back to your users table. A UNIQUE constraint would also be recommended. Then you simply use a Guid in your asp.net application as the token.
The flow could be something like this:
User requests password reset for their account
You insert a new record in the table (or update their user record) by setting the PasswordResetExpiration to a date in the future (DateTime.Now.AddDays(1)), and set the token to Guid.NewGuid()
Email the user a link to your ResetPassword.aspx page with the guid in the query string (http://www.yoursite.com/ResetPassword.aspx?token=Guid-here)
Use the ResetPassword.aspx page to validate the token and expiration fields. (I.E. Make sure DateTime.Now < PasswordResetExpiration)
Provide a simple form that allows the user to reset this password.
I know you wanted to avoid modifying the database, but it really is probably the simplest method.
#Alex
You can also use System.Security.Cryptography classes in .NET for the hash algorithms. For example:
using System.Security.Cryptography;
...
var hash = SHA256CryptoServiceProvider.Create().ComputeHash(myTokenToHash);
...
Here, the System.Guid class in your friend, as it will generate a unique (well, unique enough) 128-bit number:
Generate a new Guid ( System.Guid.NewGuid() )
Store that Guid somewhere (Application object maybe?)
Send a custom URL in an email with that Guid
When the user hits the site, make them enter the password you sent in the email
If the passwords match, go ahead and force them to enter a new password
I used a Hashing Class to create unique automatic logins made up of the current date/time and the users email address:
string strNow = DateTime.Now.ToString();
string strHash = strNow + strEmail;
strHash = Hash.GetHash(strHash, Hash.HashType.SHA1);
get the Hash Class from: http://www.developerfusion.com/code/4601/create-hashes-md5-sha1-sha256-sha384-sha512/
Then just take it from the URL using:
if (Request.QueryString["hash"] != null)
{
//extract Hash from the URL
string strHash = Request.QueryString["hash"];
}
I would definitely include the database in this process. Once a reset is requested, it's a good idea to indicate that the account is locked out.
For example, if you are changing your pw because you think your account may have been compromised, you definitely don't want it to remain accessible while you go about the change process.
Also, inclusion of "real" information in the reset token could be decoded if someone really wants it and has the horsepower. It would be safer to generate a random string, save it in the db in the row for that user, and then key back to it when the link is clicked.
This gives you two things:
1) There's nothing to decrypt, and therefore nothing of value can be gained from it.
2) The presence of the token in the user record indicates that reset is in progress and the account should be treated as locked out.
The goal of sending some data|string to user email is validation of account owner. Please care about some points:
Avoid sending important information in reset or activate link.
It's best way to store unique string data conjunction with user
account and send it as that link. but be aware if you send just one
section as link to user email and just check it in page, your
application may be in dangerous by brute-force or dictionary
attacker. It's enough to check a list of string to find some links
and change password. I know that has a little chance, but not zero.
Result:
I think it's better if you
combine user email with string link then encrypt them
(not hash because hashed value can't be reverse) and send to user
email.
User click and your page get the encrypted value.
decrypt value.
extract user email.
find email in database.
compare string from received link with other one attached to user
email in database.
Good luck.
I'd use a hash code to validate details in the password reset url. This can all be done without writing anything to the DB or sending any privileged info to an attaker.
To briefly explain normal password salt and hashing; say the salt is 1111 and the pasword is password, you'd concatenate the two and hash the string 1111password, say this gives you a hash of 9999, you'd then store the original salt 1111 and hash 9999 in your user record.
When you are validating a password you use the stored salt, concatenate the password attempt, hash it and compare with the stored hash. For example asecret becomes 1111asecret but hashes to 8888. This doesn't match the original hash so the password match fails.
Of course the salt and hash would normally be properly generated and calculated with established crypto libraries (don't invent your own!).
For the password reset URL I'd put in the unique identifier for the user, i.e. email address, the date the request is made, and a new hash. This hash would be generated from those details concatenated together plus the salt and hash already stored for the user.
For example:
Email: user#example.com
Request Date: 2014-07-17
Salt: 1111
Hash: 9999
Generate a new hash of those concatenated, i.e. 'user#example.com2014-07-1711119999', say this gives a hash of 7777.
The URL I then generate would then have the email, request date and the new hash:
https:\\www.example.com\ResetPassword?email=user#example.com&requestdate=2014-07-17&hash=7777
The server will combine the email and supplied date with it's salt and hash and confirm the hash it generated is the same as the supplied one. If this is Ok then it will show the reset form with the same three parameters hidden behind it, otherwise an error. These get resubmitted and rechecked when the new password is entered to prevent that form being spoofed.
The email address needs to be supplied to make the request and it is only sent out in an email to the same address. the date is hardly priveleged info and the hash is not reversible so gives nothing anyway. Nothing has been written to the database and any tampering with the parameters causes the hash to fail and the URL to report an error.
There is an issues with this approach. A safe hash makes the token really long. Either you integrate the salt into the hash itself (makes it about 20 charactes longer), or you store this unique salt in the database. If you store the salt in the database, you could as well store a random token which is not derrived from any existing
Depending on your needs, you could encrypt information, in a format similar to the following format
(UserId)-(ExpireDate)
Encrypt the data, make that the link, then decrypt the data and take action from there...
Crude, but most likely usable, and not requiring DB usage

Resources