Linux password from hash

/etc/shadow – HowTo: Generate Password Hash in Linux

Linux stores users’ encrypted passwords, as well as other security information, such as account or password expiration values, in the /etc/shadow file.

Someday you may need to edit the /etc/shadow file manually to set or change ones password.

Unlike the /etc/passwd that is readable for everyone, the /etc/shadow file MUST be readable by the ROOT user only.

For this you would have to generate password hash in the format compatible with /etc/shadow .

Cool Tip: Want to create a USER with ROOT privileges? This can be very dangerous! But if you insist… Read more →

There is no need to install any additional tools as it can be easily done from the Linux command line using Python.

Generate Password Hash for /etc/shadow

The $ID indicates the type of encryption, the $SALT is a random (up to 16 characters) string and $ENCRYPTED is a password’s hash.

Hash Type ID Hash Length
MD5 $1 22 characters
SHA-256 $5 43 characters
SHA-512 $6 86 characters

Cool Tip: Got a hash but don’t know what type is it? Find out how to easily identify different hash types! Read more →

Use the below commands from the Linux shell to generate hashed password for /etc/shadow with the random salt.

Generate MD5 password hash:

Generate SHA-256 password hash:

Generate SHA-512 password hash:

Hope these commands will be helpful.

Just don’t forget to replace MySecretPassword with YourSecretPassword.

As you can see, it is really very easy to generate hashes for the /etc/shadow from the Linux command line using Python.

Particularly for the reason that the Python is installed by default on the most Linux distributions.

Источник

Как: Сгенерировать Хэш Пароля в Linux и как узнать тип хэша

Сгенерировать Хэш Пароля в Linux

Linux хранить зашифрованные пароли пользователей, также как и другую информацию связанную с безопасностью, например сроки действия аккаунтов или паролей, в файле /etc/shadow .

Однажды у вас может возникнуть необходимость вручную отредактировать файл /etc/shadow для того, чтобы задать или изменить чей-то пароль.

В отличие от файла /etc/passwd , который могут читать все, файл /etc/shadow должен быть доступен для чтения ИСКЛЮЧИТЕЛЬНО пользователю ROOT.

Для этого вам придется сгенерировать хэш пароля в формате, который будет совмести с /etc/shadow .

Нет необходимости устанавливать дополнительные утилиты, так как это может быть легко сделано из командной строки в Linux с помощью Python.

Создать Хэш Пароля для /etc/shadow

Зашифрованные пароли в /etc/shadow хранятся в следующем формате:

$ID обозначает тип шифрования, $SALT — это случайная (до 16 символов) строка и $ENCRYPTED — хэш пароля.

Тип Хэша ID Длина Хэша
MD5 $1 22 символов
SHA-256 $5 43 символов
SHA-512 $6 86 символов

Используйте следующие команды из терминала в Linux для создания хэшированых паролей со случайной солью для /etc/shadow .

Создать MD5 Хэш пароля:

Создать SHA-256 Хэш пароля:

Создать SHA-512 Хэш пароля:

Надеюсь эти команды будут вам полезны.

Только не забудьте поменять MySecretPassword на ваш YourSecretPassword.

Как вы видите, это действительно очень легко генерировать хэши для /etc/shadow из командной строки в Linux с помощью Python.

Читайте также:  Счетчик калорий mac os

В частности потому, что Python, по умолчанию, установлен в большинстве Linux дистрибутивах.

Узнать тип хэша

Существуют два основных параметра, которые могут помочь распознать тип используемой хэш-функции:

  • Длина ХЭШа (каждая хэш-функция имеет определенную выходную длину);
  • Используемый алфавит (есть ли английские буквы? числа 0-9 и A-F … возможно это hex? используются ли специальные символы?).

Step 1: Скачиваем последнюю версию (v1.1 на текущий момент)

Step 2: Запускаем скрипт и копируем интересующие нас ХЭШи

Добавить комментарий Отменить ответ

Для отправки комментария вам необходимо авторизоваться.

Источник

Tech Monger

Programming, Web Development and Computer Science.

Ubuntu Password Storage and Hashing with Python

Posted July 06, 2019

If you ever wondered where and how user passwords are stored in linux file system then this post will answer most of your questions. Below we will discuss password hashing in ubuntu but many other linux distributions follow this pattern. Below read assumes that you have basic familiarity with hash function like md5 or sha-256.

Hashed not Encrypted

In Linux Passwords are not stored by encrypting with some secret key rather hash of the password is stored. So you need not to worry about key getting compromised nor the file which actually stores password (Hashed Password) getting stolen.

To make storage more secure password are hashed with salt. Salt is just random string which is generated when you create password. This helps prevent rainbow table attacks.

Password File Location and Content

Ubuntu stores password content in file /etc/shadow . Only root user can write inside this file. Along with hashed password this file also stores content like username, password change date, expiry date etc. in colon (:) separated format. We will focus on the second field i.e salt with hashed password.

This line stores salt along with password hash. Note that each string between $ sign represent following things.

$ 6 $ ABCD1234 $ JnCx/.NCi4315V0AONxuVpUIRvPivoQjLzY0M28iYkOJU/FwVhXE4Me2f72fldvGEOpnTAB7IuVrsVfwpT/XT/

Value Explanation
$6$ Value between starting two $ sign represents algorithm used for hashing. Here number 6 suggests sha-512 been used.
$ABCD1234$ Value between second and third $ sign represents string salt which is used for hashing..
$JnCx/.NCi4315V0AON xuVpUIRvPivoQjLzY0M 28iYkOJU/FwVhXE4Me 2f72fldvGEOpnTAB7IuV rsVfwpT/XT/ Value after the third $ sign represents actual hashed password.

Regenerating Hashed Password in Python

Stored password hash is generated using crypt3 . You can use python crypt implementation to regenerate password. Note that the password used for the user techmonger is hunter2 .

In above example you can see that hash value generated by hashing password hunter2 with salt ABCD1234 using sha-512 is same as that present in the file /etc/shadow .

Conclusion

Above we have seen how password is stored in Linux like system and how hashed password is generated with the help of python code. Storing password this way is very secure and finding actual password from the stored hash is impossible*.

Источник

SHA password hashes

This article or section is a candidate for merging with Security#Password hashes.

The Secure Hash Algorithms (SHA) are a set of hash functions often used to hash passwords. By default Arch uses SHA-512 for passwords, but some systems may still be using the older MD5 algorithm. This article describes how to increase password security.

Benefits of SHA-2 over MD5

This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.

In Linux distributions login passwords are commonly hashed and stored in the /etc/shadow file using the MD5 algorithm. The security of the MD5 hash function has been severely compromised by collision vulnerabilities. This does not mean MD5 is insecure for password hashing but in the interest of decreasing vulnerabilities a more secure and robust algorithm that has no known weaknesses (e.g. SHA-512) is recommended.

Читайте также:  Show hidden folders mac os

The following tutorial uses the SHA-512 hash function, which has been recommended by the United States’ National Security Agency (NSA) for Red Hat Enterprise Linux 5. Alternatively, SHA-2 consists of four additional hash functions with digests that are 224, 256, 384, and 512 bits.

Increasing security

This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.

If your current password was created with shadow version prior to 4.1.4.3-3 (2011-11-26) you are using MD5. To start using a SHA-512 hash you just need to change your password with passwd.

The rounds=N option helps to improve key strengthening. The number of rounds has a larger impact on security than the selection of a hash function. For example, rounds=65536 means that an attacker has to compute 65536 hashes for each password he tests against the hash in your /etc/shadow . Therefore the attacker will be delayed by a factor of 65536. This also means that your computer must compute 65536 hashes every time you log in, but even on slow computers that takes less than 1 second. If you do not use the rounds option, then glibc will default to 5000 rounds for SHA-512. Additionally, the default value for the rounds option can be found in sha512-crypt.c .

Open /etc/pam.d/passwd with a text editor and add the rounds option at the end of of the uncommented line. After applying this change the line should look like this:

Re-hash the passwords

Even though you have changed the encryption settings, your passwords are not automatically re-hashed. To fix this, you must reset all user passwords so that they can be re-hashed.

As root issue the following command,

where username is the name of the user whose password you are changing. Then re-enter their current password, and it will be re-hashed.

To verify that your passwords have been re-hashed, check the /etc/shadow file as root. Passwords hashed with SHA-256 should begin with a $5 and passwords hashed with SHA-512 will begin with $6 .

Источник

How to get a password from a shell script without echoing

I have a script that automates a process that needs access to a password protected system. The system is accessed via a command-line program that accepts the user password as an argument.

I would like to prompt the user to type in their password, assign it to a shell variable, and then use that variable to construct the command line of the accessing program (which will of course produce stream output that I will process).

I am a reasonably competent shell programmer in Bourne/Bash, but I don’t know how to accept the user input without having it echo to the terminal (or maybe having it echoed using ‘*’ characters).

Can anyone help with this?

10 Answers 10

Here is another way to do it:

The read -s will turn off echo for you. Just replace the echo on the last line with the command you want to run.

A POSIX compliant answer. Notice the use of /bin/sh instead of /bin/bash . (It does work with bash, but it does not require bash.)

Under Linux (and cygwin) this form works in bash and sh. It may not be standard Unix sh, though.

Читайте также:  Intellij idea evaluation reset linux

For more info and options, in bash, type «help read».

The -s option of read is not defined in the POSIX standard. See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html. I wanted something that would work for any POSIX shell, so I wrote a little function that uses stty to disable echo.

This function behaves quite similar to the read command. Here is a simple usage of read followed by similar usage of read_secret . The input to read_secret appears empty because it was not echoed to the terminal.

Here is another that uses the -r option to preserve the backslashes in the input. This works because the read_secret function defined above passes all arguments it receives to the read command.

Finally, here is an example that shows how to use the read_secret function to read a password in a POSIX compliant manner.

I found to be the the askpass command useful

Every input character is replaced by *. See: Give a password ****

Turn echo off using stty , then back on again after.

You can also prompt for a password without setting a variable in the current shell by doing something like this:

You can add several of these prompted values with line break, doing this:

For anyone needing to prompt for a password, you may be interested in using encpass.sh. This is a script I wrote for similar purposes of capturing a secret at runtime and then encrypting it for subsequent occasions. Subsequent runs do not prompt for the password as it will just use the encrypted value from disk.

It stores the encrypted passwords in a hidden folder under the user’s home directory or in a custom folder that you can define through the environment variable ENCPASS_HOME_DIR. It is designed to be POSIX compliant and has an MIT License, so it can be used even in corporate enterprise environments. My company, Plyint LLC, maintains the script and occasionally releases updates. Pull requests are also welcome, if you find an issue. 🙂

To use it in your scripts simply source encpass.sh in your script and call the get_secret function. I’m including a copy of the script below for easy visibility.

#!/bin/sh ################################################################################ # Copyright (c) 2020 Plyint, LLC . All Rights Reserved. # This file is licensed under the MIT License (MIT). # Please see LICENSE.txt for more information. # # DESCRIPTION: # This script allows a user to encrypt a password (or any other secret) at # runtime and then use it, decrypted, within a script. This prevents shoulder # surfing passwords and avoids storing the password in plain text, which could # inadvertently be sent to or discovered by an individual at a later date. # # This script generates an AES 256 bit symmetric key for each script (or user- # defined bucket) that stores secrets. This key will then be used to encrypt # all secrets for that script or bucket. encpass.sh sets up a directory # (.encpass) under the user’s home directory where keys and secrets will be # stored. # # For further details, see README.md or run «./encpass ?» from the command line. # ################################################################################ encpass_checks() < if [ -n "$ENCPASS_CHECKS" ]; then return fi if [ ! -x "$(command -v openssl)" ]; then echo "Error: OpenSSL is not installed or not accessible in the current path." \ "Please install it and try again." >&2 exit 1 fi if [ -z «$ENCPASS_HOME_DIR» ]; then ENCPASS_HOME_DIR=$(encpass_get_abs_filename

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью