Java generated Token not random - but what is it? - java

I am told to analyse the behavior of a web application and noticed that it generates password reset tokens based on the username+password combination. That means that if username and password combination of the account stays the same during the resets, the generated reset token stays also the same.
So it is NOT random and not based on a time stamp or anything that changes frequently.
It does not look random to me at all. But what is it?
I checked several Java functions like UUID, that generate tokens, but their output does not look like the tokens I am looking at.
Has anyone an idea what (Java function) generates this kind of tokens?
Account B
token=YwQAAAAAAAAmONpWfOI-dGQoZBbXxUaApbRQ7E
token=YwQAAAAAAAADIDSPpW_5vC8AvpNTi5LIgQZ080
token=YwQAAAAAAAAg5NcxcGeRWXA2m_K0cm0TNx8rO8
token=YwQAAAAAAAA0H4tkoER8tDfMR_V_TT3BPfC43g
token=YwQAAAAAAAApFrrJCJvb_zH0p5f-HkIt7EtWgA
token=YwQAAAAAAAAiDeQFrxpTSwrFNCV4AQW0sdoiyw
Account A
token=TwQAAAAAAAAi6M6tduIa6EdB3-VB1J_l8Cyza8
token=TwQAAAAAAAAM-yFuFKebUZA-2q0YgwnJeGrZuo
token=TwQAAAAAAAAg0We7RWTMM9PYv68RCJMUG_MuBw

For me this looks like a Base64 enoded something. Try to decode your token with Base64 and look what it looks like.

I think they are doing something like this to generate a base65 compressed string
Sign a string using SHA1, then shrink it using url-safe base65

Related

Standalone Java Windows software with password

I'm trying to develop a standalone software for windows in java. My goal is to have a completely standalone software which can encrypt some data and decrypt them when the user inserts a correct password. Following the standalone mindset I would love to avoid using some DB to store the data (mandatory installation of a MySQL DB sounds horrible to me), so I decided to store the data in a simple txt file, converting my java storing-data class to JSON and saving this string in the file. Obviously I would encrypt the string before saving it. The most weak part of my project (or at least in my opinion) is the login. I've come up with this idea:
using PBE from java.crypto to encrypt and decrypt data
a check string for checking the user password like "this is my check string"
I encrypt my check string using a particular algorithm, a particular salt and a particular first time password like "admin". Then I store my encrypted check string in a separate txt file. The first time the user execute the application he can log with "admin" password and then change it.
the authentication process is this: the user inputs his password, and my program tries to decrypt my check string using that password. If the decrypted string equals the original check string the log in is successful. On the contrary it gives an error message to retry cause the password is wrong.
My idea seems somehow solid to me (at least for a non professional point of view) but I've read that you can extract the source code from an exe file and this would mean that anyone can spoil my secret check string, my salt and my encryption algorithm (cause this data are all written explicitly in one of my java classes).
Since this is my first time with java.crypto and in general with a standalone authentication problem, I would love to receive some advices from someone more experienced. Anyway I have some experience with MYSQL and db in general, but I would love to have a light and not that expensive way to store data, cause i know that storing in txt files is quite "naive". Anyway I'm accepting any type of advice, especially cause I've no experience with this type of problem.

making hash more safe with a salt

Im new here, so please correct me on anything!
I was assigned to do a basic java program where i register and authenticate users, storing the username and the password in a .txt file. The password is stored as an MD5 hash. Also, i needed to make another program to try brute-forcing the .txt file to find the passwords, and measure the time needed to do so.
i managed to do that(suffering a bit), and the last step is to find and implement a way to reduce the chances of this brute-forcing to work. I searched a lot about it, and apart from people saying to use another safer method of storing passwords, the only thing i found useful(which i heard of before so i searched for it) was using salts, Which i know that they are concatenated within the password before hashing, and then both hash and salt are stored.
But i dont think this would work in this occasion, as the salt would also be stored in the .txt file, thus, even taking longer due to the bigger possible range of combinations, i could still do a brute force where i try a combination and add the salt in the .txt to it, then hash it and compare to the hash stored in the .txt.
Is this a viable way to make the brute force harder(at least in this assignment, for learning purposes) as it takes more time, or is there any other methods to do so?
thanks in advance!
first of all. md5-Hash is deprecated. Please use sha256 or sha512 instead.
The salt should not stored inside the text file. It is a config parameter of your programm.
Now, you can use your secret salt and the password to generate the hash.
hashedPw = sha256(salt + password)
This avoids that an attacker can retrieve the original password from look it up in an lookup table. (https://crackstation.net/)
Additionally you can encrypt your passwords with AES-Algorithm.

Generating a secure cookie token to store persistently

I am trying to create a login and register page for my website. I am looking to use cookies in order to track a users session however I'm trying to implement it in the most proper and secure way. I've tried looking at tutorials and forums but most of them are outdated and use techniques that people comment are not secure. I understand tokens needs to be randomly generated and encrypted so I found one response that suggested to use a MessageDigest on UUID. But I found more articles suggesting that this may not be as secure as I think... Any suggestions on a secure way to generate cookie tokens to store in my db?
When I tried using the UUID method I got stuck on how to place it into my db since I'm having trouble finding how to turn it into a string. Here is my code...
UUID uuid = UUID.randomUUID();
MessageDigest salt = MessageDigest.getInstance("SHA-256");
salt.update(uuid.toString().getBytes("UTF-8"));
Your current method is, well, rather terrible. Consider if I, an attacker, learnt that my victims UUID is some value x. I could then simply take the SHA-256 hash of x and store this as a cookie on your website. Tada. I'm now impersonating my victim.
In saying that, a very secure way to produce tokens for login systems is something relatively similar. Consider the following JSON object:
{ "expiry": "1:30:00 24/10/2012", "userID": "F68D4A77DC34" }
If we stored this JSON object as a cookie on the client-side, it would be an excellent way to determine who our user is and when this object expires and the user needs to login again.
But wait, this won't work, because anyone could change the user ID or the expiry and your server won't know!
We can solve this easily by introducing an HMAC. An HMAC is a Hashed Message Authentication Code. We first generate (once, ever) a random HMAC key, k, to use on the server. This key should remain on the server and never be transmitted.
When a user logs in, we create a JSON object similar to the one above and then feed it through an HMAC (say, HMAC-SHA256) with k as the key, and then append the result of this to the JSON object as base64 encoded bytes. It sometimes helps to use a splitting character too, say ".".
We then end up with the following:
{ "expiry": "1:30:00 24/10/2012", "userID": "F68D4A77DC34" }.ScvlfpUDqgxtDPH4jsK44d+4cMNG+5yCvASJkVEI11o
This token would be fine to use exactly like that, but some people like to base64 encode the JSON too. We end up with something like this in that case:
eyAiZXhwaXJ5IjogIjE6MzA6MDAgMjQvMTAvMjAxMiIsICJ1c2VySUQiOiAiRjY4RDRBNzdEQzM0IiB9.ScvlfpUDqgxtDPH4jsK44d+4cMNG+5yCvASJkVEI11o
It is easy for us to verify that this token is legitimate by taking the JSON object, performing the same operation again, and then comparing the result of the HMAC with the one that is attached to the token. If they match, we know that our server generated the token and that it is legitimate.
There appears to be some misconceptions about what this "secure" token actually means.
It can be anything, in theory. You could use a username, or an incremental id counter, or salted hash of the username, or a uuid.
The question is what are you using it for and why?
If you're using it because you just want information on how long requests are taking, a number works just fine (in theory; not saying I recommend it, more on that later). You don't lose anything major if someone fakes the id number and why would they? They don't see an actual benefit from it.
If you're using this token because it determines who a user is for permissions purposes, then obviously your goal is to make it so it can't be faked. If you want it to be faked, then you should make it truly random and unique. So you could, quite easily, just use UUID.randomUUID().toString() - This is highly unlikely to be spoofable as someone would need to know the exact nano-second precision on your machine as well as the ability to know what the state of the random number generator for the other bits of the uuid are. And that simply won't happen.

Do I need to enable canonicalization when using OWASP ESAPI?

We are adding ESAPI 2.x (owasp java security library) to an application.
The change is easy though quite repetitive. We are adding validations to all input parameters so we make sure all the characters they are composed by are within a whitelist.
This is it:
Validator instance = ESAPI.validator();
Assert.assertTrue(instance.isValidInput("test", "xxx#gmail.com", "Email", 100, false));
Then Email patterns is set in the validation.properties file like:
Validator.Email=^[A-Za-z0-9._%'-]+#[A-Za-z0-9.-]+\\.[a-zA-Z]{2,4}$
Easy!
We are not encoding output given that after the input validation, data becomes trusted.
I can see in ESAPI that it has a flag to canonicalize the input String. I understand that canonicalization is "de-encoding" so any encoded String is transformed in plain text.
The question is. Why do we need to canonicalize?
Can anybody show a sample of an attack that will be prevented by using canonicalization?? (in java)
thank you!
Here's one (of several thousand possible examples):
Take this simple XSS input:
<script>alert('XSS');</script>
//Now we URI encode it:
%3Cscript%3Ealert(%27XSS%27)%3B%3C%2Fscript%3E
//Now we URI encode it again:
%253Cscript%253Ealert(%2527XSS%2527)%253B%253C%252Fscript%253E
Canonicalization on the input that's been encoded once will result in the original input, but in ESAPI's case, the third input will throw an IntrusionException because there is NEVER a valid use case where user input will be URI-encoded more than once. In this particular example, canonicalization means "all URI data will be reduced into its actual character representation." ESAPI actually does more than just URI decoding, btw. This is important if you wish to perform both security and/or business validation using regular expressions--the primary use of regular expressions in most applications.
At a bare minimum, canonicalization gives you good assurance that sneaking malicious input into the application isn't easy: The goal is to restrict to known-good values (whitelist) and reject everything else.
In regards to your ill-advised comment here:
We are not encoding output given that after the input validation, data becomes trusted.
Here's the dirty truth: Javascript, XML, JSON, and HTML are not "regular languages." They're nondeterministic. What this means in practical terms is that it is mathematically impossible to write a regular expression to reject all attempts to insert HTML or Javascript into your application. Look at that XSS Filter Evasion Cheat sheet I posted above.
Does your application use jquery? The following input is malcious:
$=''|'',_=$+!"",__=_+_,___=__+_,($)[_$=($$=(_$=""+{})[__+__+_])+_$[_]+(""+_$[-__])[_]+(""+!_)[___]+($_=(_$=""+!$)[$])+_$[_]+_$[__]+$$+$_+(""+{})[_]+_$[_]][_$]((_$=""+!_)[_]+_$[__]+_$[__+__]+(_$=""+!$)[_]+_$[$]+"("+_+")")()
So you must encode all data when output to the user, for the proper context, this means that if the piece of data is going to be first input into a javascript function, and then displayed as HTML, you encode for Javascript, and then HTML. If its output into an HTML data field (such as a default input box) you encode it for an HTML Attribute.
Its actually MORE IMPORTANT to do output encoding than to do input filtering in protecting against XSS. (If I HAD to just choose one...)
The pattern you want to follow in web development is one where any input that is coming from the outside world is treated as malicious at all times. You encode any time you're handing off to a dynamic interpreter.
Canonicalization of data is also about deriving the data to its basic form. So if we take a different scenario where a file path(relative/symlink) and its allied directory permission is involved we need to first canonicalize the path and then validate else it will allow somebody to explore those files without permission by just passing the target acceptable data.

Secure way to use password in java file

I am developing an android application through which i am sending a mail via GMAIL API.
To send mail via GMAIL API i have to give them my ID and password.
GMailSender m = new GMailSender("myemailhere#gmail.com",
"mypasswordhere");
and i know writing password like this is not at all safe as my password could easily be stolen by extracting my apk and alsostoring the password in strings.xml is also not secure as xml can also retrieved.
my question is-
Is there any other way to write password in my file so that it remain secure??
The short answer is not. You shouldn't store your password anywhere in the code or in any file.
Even if you encrypt it like someone said you will have to store it's decryption algorithm/key somewhere in the code, which will be easily reverse engineered.
No,It's not safe to store passwords on the device.
small advice is always store passwords in char[] in encrypted form rather than storing in a String whenever it is mandatory to store.
Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since Strings are used in String pool for re-usability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text and that's another reason you should always use an encrypted password than plain text. Since Strings are immutable there is no way contents of Strings can be changed because any change will produce new String. So Storing password in character array clearly mitigates security risk of stealing password.
Storing passwords is not considered safe, and shouldn't be done if at all avoidable. There are a few considerations, if you have to for some reason.
The best place to store such things is in private SharedPreferences. These are not readable by anything but the app, or rooted devices. Do not store on external storage!!!
Encryption can always be undone, but if you have to, then it would be better than nothing, requiring more work to undo. Use a key which is unique to each device.
Some sort of a token, such as is used by Oauth, could be a solution. This isn't perfectly secure either, but it could be.
Google provides more secure APIs for it's functions. You really should look in to that.

Categories