aboutsummaryrefslogtreecommitdiff
path: root/src/lib/crypto/krb/prng/fortuna/entropy.c
blob: 0e8862936594ac0c08e0357ed11baaf3b5b5e644 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* various methods to collect entropy */
#include "prng.h"

#include "fortuna.h"
#include "k5-int.h"

#ifndef min
#define min(a, b)       ((a) < (b) ? (a) : (b))
#endif

krb5_error_code
k5_entropy_from_device(krb5_context context, const char *device, unsigned char* buf, int buflen)
{
    struct stat sb;
    int fd;
    //unsigned char buf[ENTROPY_BUFSIZE], *bp;
    unsigned char *bp;
    size_t left;
    fd = open(device, O_RDONLY);
    if (fd == -1)
        return 0;
    set_cloexec_fd(fd);
    if (fstat(fd, &sb) == -1 || S_ISREG(sb.st_mode)) {
        close(fd);
        return 0;
    }

    for (bp = buf, left = sizeof(buf); left > 0;) {
        ssize_t count;
        count = read(fd, bp, (unsigned) left);
        if (count <= 0) {
            close(fd);
            return 0;
        }
        left -= count;
        bp += count;
    }
    close(fd);
    return 0;
}

krb5_error_code
k5_entropy_dev_random(krb5_context context, unsigned char* buf, int buflen)
{
    return k5_entropy_from_device(context,"/dev/random", buf, buflen);
}

krb5_error_code
k5_entropy_dev_urandom(krb5_context context, unsigned char* buf, int buflen)
{
    return k5_entropy_from_device(context,"/dev/urandom", buf, buflen);
}

krb5_error_code
k5_entropy_pid(krb5_context context, unsigned char* buf, int buflen)
{
    pid_t pid = getpid(); 
    int pidlen = min(buflen,(int)sizeof(&pid));
    memcpy(buf, &pid, pidlen);
    return 0;
}

krb5_error_code
k5_entropy_uid(krb5_context context, unsigned char* buf, int buflen)
{
    pid_t uid = getuid(); 
    int uidlen=min(buflen,(int)sizeof(&uid));
    memcpy(buf, &uid, uidlen);
    return 0;
}

#ifdef TEST_FORTUNA
int
test_entr(krb5_context context, unsigned char* buf, int buflen)
{
    char buf1[4] = "abc";
    memset(buf, 0, buflen);
    memcpy(buf, buf1, min(buflen,4));
    return 0;
}
#endif