immortal
immortal

Reputation: 3188

Is there a standard way to generate a salt for crypt syscall?

I need to implement account management for my application, and I would rather not use chpasswd subprocess, or otherwise let the plaintext password out my my application's memory space.

I want to use putspent with a password hash I generate with crypt, but I can't find any standard function to randomize a salt for crypt. An online search only found weird hashing function implementations I'd rather not copy into my code. Is there a standard function that would generate a salt for me?

Otherwise, would it be wise to just re-use the current salt stored in my shadow file? I couldn't think of why it WOULD be a security hazard (it will not weaken my shadow file against a rainbow table attack), it just feels wrong because in systems security a rule of thumb is to always randomize everything... (Users are added with system utilities)

Upvotes: 3

Views: 1752

Answers (3)

heine
heine

Reputation: 597

It depends on your libc version. In newer Versions there is crypt_gensalt which should be what you need. Use the *_rn versions to be thread-safe.

Example:

#include <crypt.h>
#include <stddef.h>
#include <stdio.h>

int main() {
    char result[CRYPT_GENSALT_OUTPUT_SIZE];
    const char* salt = crypt_gensalt_rn("$6$", 0, NULL, 0, result, sizeof(result));

    if(salt == NULL)
        return -1;

    printf("salt: %s\n", salt);

    struct crypt_data state_data = {0};
    const char* hash = crypt_rn("password", salt, &state_data, sizeof(state_data));

    printf("hash: %s\n", hash);
}

Upvotes: 0

user803422
user803422

Reputation: 2814

For generating a salt for crypt(), you need 2 random bytes. For this, you can use openssl:

#include <openssl/rand.h>
int RAND_bytes(unsigned char *buf, int num);
int RAND_pseudo_bytes(unsigned char *buf, int num);

Ref: https://www.openssl.org/docs/man1.0.2/crypto/RAND_bytes.html

Example:

unsigned char salt[2];
RAND_pseudo_bytes(salt, 2);
char *ptr = crypt(password, salt);

Upvotes: -2

user803422
user803422

Reputation: 2814

OpenSSL provides functions for sha512:

https://www.openssl.org/docs/man1.0.2/crypto/SHA512.html

int SHA256_Init(SHA256_CTX *c);
int SHA256_Update(SHA256_CTX *c, const void *data, size_t len);
int SHA256_Final(unsigned char *md, SHA256_CTX *c);
unsigned char *SHA256(const unsigned char *d, size_t n,
      unsigned char *md);

Upvotes: -1

Related Questions