M. Krajnak
M. Krajnak

Reputation: 109

Using useradd with --password to create new users, but the encrypted password being passed in is not stored correctly in /etc/shadow

I have a C++ program which adds new users to a Linux system by calling useradd.

This includes setting the password by using the --password option and passing in the encrypted (not plain text) password.

I encrypt the password by calling crypt() (actually crypt_rn()) so the plain text password is never passed on the command line.

After the call to crypt I have a string which follows the format I expect, something like:

$<algorithm>$<salt>$<encrypted-text>

I also see one or more "/" characters in the encrypted text, here's a fake example that gives a rough idea of what I see:

$6$abcdefg$xxxxx/yyyyyy

After the call to useradd what I see in the /etc/shadow file is that the $<algorithm>$ portion is missing as well as the first character of the salt. And all of the characters from the final $ of the salt to the first / are missing. So the example above looks like this:

bcdefg/yyyyyy

So the user cannot log in.

If I copy and paste the encrypted text as passed into useradd into the shadow file, the user can log in, so I believed encrypting the password is working as expected.

As part of debugging I've printed out the full useradd command and can see that the encrypted password is identical to what crypt returned so the string is not corrupted.

Additionally if I take the text for the useradd command as it was used in the progam and run it on the command line I observe the same behavior, that the encrypted text in the /etc/shadow file has missing portions in the same way that it does when I run it from the program.

This is all on a Yocto (3.4) system.

I did not generate the OS so I though it might have limited support for the SHA-512 algorithm I am using with crypt.

But if I add a user with useradd from the command line without a password, then set the password with passwd, I see that it is defaulting to the same algorithm that I use, SHA-512.

Upvotes: 1

Views: 1345

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 93948

Dollar signs + the directly following text get replaced if you use double quotation marks instead of single quotation marks. Those pieces of text are handled as if they are variables. That means that you are concatenating empty variables + the remaining text.

It is possible to escape the dollar signs instead, but I think that is less productive for this use case.

Upvotes: 1

Related Questions