File: nonce.c

package info (click to toggle)
ekeyd 1.1.5-4
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 752 kB
  • sloc: ansic: 5,259; sh: 337; makefile: 262; perl: 150
file content (80 lines) | stat: -rw-r--r-- 1,522 bytes parent folder | download | duplicates (5)
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
/* daemon/nonce.c
 *
 * Entropy key nonce generation
 *
 * Copyright 2009 Simtec Electronics
 *
 * For licence terms refer to the COPYING file.
 */

#include <stdbool.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <syslog.h>

#include "nonce.h"

#if defined(EKEY_OS_OPENBSD) || defined(EKEY_OS_MIRBSD)

#include <stdlib.h>

/* exported interface documented in nonce.h */
bool
fill_nonce(uint8_t *buff, size_t count)
{
    arc4random_buf(buff, count);
    return true;
}

/* exported interface documented in nonce.h */
void
close_nonce(void)
{
}

#else

/** File descriptor for the urandom device. */
static int noncefd = -2;

/* exported interface documented in nonce.h */
bool
fill_nonce(uint8_t *buff, size_t count)
{
    int rd;
    bool status = true;

    if (noncefd < 0) {
        if (noncefd == -2) {
            noncefd = open("/dev/urandom", O_RDONLY);
        }
        if (noncefd < 0) {
            syslog(LOG_ERR, "Unable to prepare nonce");
            return false;
        }
    }

    rd = read(noncefd, buff, count);
    if (rd < 0) {
        syslog(LOG_ERR, "Error %s reading nonce data", strerror(errno));
        status = false;
    } else if (rd != count) {
        syslog(LOG_ERR, "Short read of nonce data (%d/%zd)", rd, count);
        status = false;
    }
    return status;
}

/* exported interface documented in nonce.h */
void
close_nonce(void)
{
    if (noncefd >=0 ) {
        close(noncefd);
    }
    noncefd = -2;
}
#endif