How are passwords stored in Linux (Understanding hashing with shadow utils)
The above shown encoded hash value can be further classified into three different fields as below.
1. The first field is a numerical number that tell’s you the hashing algorithm that’s being used.
- $1 = MD5 hashing algorithm.
- $2 =Blowfish Algorithm is in use.
- $2a=eksblowfish Algorithm
- $5 =SHA-256 Algorithm
- $6 =SHA-512 Algorithm
2. The second field is the salt value
Salt value is nothing but a random data that’s generated to combine with the original password, inorder to increase the strength of the hash..
3.The last field is the hash value of salt+user password (we will be discussing this shortly).
So in our example entry of root, as shown below,
$1$Etg2ExUZ$F9NTP7omafhKIlqaBMqng1
The above shown encoded password is using MD5 hashing algorithm (because the of $1$ )
Salt value is Etg2ExUZ (the content between the second and third $ sign)
And the hash value of «PASSWORD + SALT» . Let’ s reproduce the same output by providing the salt value of Etg2ExUZ and the original password.
[root@slashroot1 ~]# openssl passwd -1 -salt Etg2ExUZ redhat $1$Etg2ExUZ$F9NTP7omafhKIlqaBMqng1 [root@slashroot1 ~]#
With the help of the above openssl command, you can see that the encoded entry can only be reproduced with the exact same salt value (which is always randomly selected by the password program).
This is what is done by the login program when you enter the password, it uses the salt value and your entered password to create an encoded string. If that encoded string matches the encoded string from the shadow file, then the user login is considered as successful.
Changing the salt will change the entry in shadow file. -1 option used in the above command, tell’s which hashing algorithm to use( 1 indicates md5 algorithm).
What will happen if there is no salt value at all?
- Salt value is a major component that strengthens the way a linux system stores password. Imagine that there is no salt value applied before storing passwords in linux. As we have discussed in the beginning of this article, a dictionary attack with common dictionary words will become much more easier to do.
By using the salt value(which is randomly generated while generating passwords), an attacker needs to go throgh different combinations of salt values as well as password string’s to guess what the original password is.
- An attacker cannot easily guess that two user’s are using same passwords. Because even if the attacker has somehow gained access to the shadow file, he cannot say looking at two encoded passwords, that they are using the same password. This is because both of them will be having different salt values.
How to Display hashing Algorthm used in your Linux Machine?
[root@localhost ~]# authconfig --test|grep hashing password hashing algorithm is md5
Above command clearly shows that, at present the algorithm used by your Linux machine is md5(Which will be used for all the user’s by default).
How will you configure your Linux machine to use SHA-512 hashing algorithm?
[root@localhost ~]# authconfig --passalgo=sha512 --update
Please note the fact that unless you change the password of your users, SHA-512 hashing algorithm will not be updated for already existing users.
You can also force your Linux users to change their passwords during the next login by using chage command(which is also provided by the shadow-utils package).
I am doing it for the user tiwary, so that user will need to compulsorily, change the password on next login.
[root@localhost ~]# chage -d 0 tiwary
Above command will force user tiwary to change his password at next Login.
Now when you see /etc/shadow file you can see that the user tiwary, has a different algorithm than all other user’s after the password change.
[root@localhost ~]# cat /etc/shadow root:$1$flVALfyK$kJfaoYnsAm7/plT3.PCmJ/:15816:0:99999:7. satish::15804:0:99999:7. slashroot:$1$MIyV9col$Up9YON8Z.TI1x37xgFvuO0:15804:0:99999:7. u1::15813:0:99999:7. himanshu:$1$0Iwvz7CA$QOJLfOSJZuSLC19LSFxt1.:15810:0:99999:7 tiwary:$6$QXBJkK8N$owDISwfo1wMH1BqoL9Rx/RD49jXpS/EZS8NbIgAUGLtZbkA1YDfZoM1GbeIlDp4p99ugzBMcijNYrxy2rrRdY0:15819:0:99999:7.
In the above shown output $6$ stands for sha512 algorithm.
How to generate a shadow style password hash?
[root@localhost ~]# openssl passwd -1 redhat123 $1$jp5rCMS4$mhvf4utonDubW5M00z0Ow0
In this case salt value is the eight characters between the 2nd and 3rd $ sign. i.e jp5rCMS4.
You can paste the above output into your shadow file for a particular user and then that user can easily login with the password «redhat123».
Comments
That was very informative..
That was very informative..
In this section where we can force Linux users to change their passwords during the next login by using chage command, i got an unusual situation where my linux(RHEL6) allow me to change password at login time but it is not accepting new password.
Every time i set new password an error message will prompt saying «Bad password» or «Too short» and after some try it will eventually be exhausted.
Hi siddharth,Good to know
Good to know that the article was informative. So let’s get back to the problem faced by you in Red Hat Enterprise Linux 6 version, for password change.
According to the error codes you mentioned («Bad Password» & «Too short»), it appears to me that RHEL 6 has by default, a strict password complexity enabled through PAM. PAM stands for Pluggable Authentication Module, and is responsible for different authentication schemes under Linux. The basic file that helps you to configure password complexity, or i must say the file that has the module and options, which enables password complexity is /etc/pam.d/system-auth.
Let’s have a look at the contents of that file(Please note the fact that am using RHEL 5 instead of 6, for showing you this example. Most red hat versions have the same contents inside this file.)
[root@myvm1 ~]# cat /etc/pam.d/system-auth #%PAM-1.0 # This file is auto-generated. # User changes will be destroyed the next time authconfig is run. auth required pam_env.so auth sufficient pam_unix.so nullok try_first_pass auth requisite pam_succeed_if.so uid >= 500 quiet auth required pam_deny.so account required pam_unix.so account sufficient pam_succeed_if.so uid < 500 quiet account required pam_permit.so password requisite pam_cracklib.so try_first_pass retry=3 password sufficient pam_unix.so md5 shadow nullok try_first_pass use_authtok password required pam_deny.so session optional pam_keyinit.so revoke session required pam_limits.so session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid session required pam_unix.so
The line that matters to us as far as password complexity is considered is
password requisite pam_cracklib.so try_first_pass retry=3
Red Hat Enterprise Linux 6(or the one in which you are getting those errors while setting up password), must have a couple of other parameters as well, due to which you are getting a strict password policy enforced. You might see something like the below as arguments to the above shown line.
minlength, lcredit, ucredit, dcredit, ocredit. Each of these mentioned arguments has got their own meanings, that makes up the required complexity in the password.
minlength=10 specifies a minimum password length of 10 letters, lcredit=3 specifies that the password must have 3 lover case letters, ucredit=3 specifies that the password must have 3 upper case letters, dcredit=3 specifies there must be atleast 3 digits in the password, ocredit=3 specifies there must be atleast 3 other characters in the password.
So a strict password policy will look something like the below.
password requisite pam_cracklib.so try_first_pass retry=2 minlength=15 lcredit=2 ucredit=3 dcredit=3 ocredit=4 difok=3
So if you have something like the above shown complexity policy in the file /etc/pam.d/system-auth, you can remove them if you want to get rid of them. But if you look from a security point of view they are a good method that can significantly increase the security of the system.
You can even disable the use of the module pam_cracklib.so by modifying the file /etc/sysconfig/authconfig, and setting USECRACKLIB=no
Hope this solves your issue, and was helpful in understanding password complexity settings in Linux.
Какой алгоритм хеширования паролей в Linux? [дубликат]
Все мы занем что в /etc/shadow хранится хеш sudo паролей. Если я захочу брутфоросом "подобрать" пароль с таким же хешем, то это займет много времени потому, что есть некоторая задержка по ответу в теорминал при вводе неправильного пароля. Выходит, что нужно искать другие лазейки - и первым шагом можно рассматривать алгоритм хеширования. Подскажите какой используется в linux-е и какие у него есть "особенности"(слабые места)?
1 ответ 1
Спасибо @Mike за комментарий. Действительно, алгоритм указан в самом хеше. Хеш имеет несколько "полей":
пусть хеш такой : kaktus:$1$jbdsfj$ewryh4hferf444f3w:213:3:123:6:8:17:
kaktus это имя пользователя
сам хеш $1$jbdsfj$ewryh4hferf444f3w - делится на несколько секторов, разделяемых $ таким образом : $id$salt$hashed . Id описывает алгоритм хеширования:
$1$ это MD5,
$2a$ это Blowfish,
$2y$ это Blowfish,
$5$ это SHA-256,
$6$ это SHA-512,
salt - соль, подробнее : https://andreyex.ru/linux/kriptograficheskie-hesh-funktsii/
hashed - выходное значение хеш функции
Далее 213 это дата последнего изменения пароля (в днях с 1 января 1970 )
Далее 3 минимально допустимое кол-во дней между сменами пароля
Далее 123 максимально допустимое кол-во дней между сменами пароля(через такое кол-во дней с момента установки пароля его необходимо обязательно сменить)
Далее 6 Кол-во дней, за которое пользователь получит предупреждение о смене пароля(см. предыдущий пункт)
Далее 8 Кол-во дней, в течение которых после истечения срока действия пароля учетная запись будет отключена.
Далее 17 Дата истечения срока действия учетной записи, выраженная в количестве дней с 1 января 1970 года.
Поправьте меня, если я где-то ошибся
Источники :