Coverage Report

Created: 2020-12-02 17:02

/libfido2/src/random.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2018 Yubico AB. All rights reserved.
3
 * Use of this source code is governed by a BSD-style
4
 * license that can be found in the LICENSE file.
5
 */
6
7
#include <sys/types.h>
8
#include <sys/stat.h>
9
#ifdef HAVE_SYS_RANDOM_H
10
#include <sys/random.h>
11
#endif
12
13
#include <fcntl.h>
14
#include <stdint.h>
15
#include <stdlib.h>
16
#include <string.h>
17
#ifdef HAVE_UNISTD_H
18
#include <unistd.h>
19
#endif
20
21
#include "fido.h"
22
23
#if defined(_WIN32)
24
#include <windows.h>
25
26
#include <winternl.h>
27
#include <winerror.h>
28
#include <stdio.h>
29
#include <bcrypt.h>
30
#include <sal.h>
31
32
int
33
fido_get_random(void *buf, size_t len)
34
{
35
        NTSTATUS status;
36
37
        status = BCryptGenRandom(NULL, buf, (ULONG)len,
38
            BCRYPT_USE_SYSTEM_PREFERRED_RNG);
39
40
        if (!NT_SUCCESS(status))
41
                return (-1);
42
43
        return (0);
44
}
45
#elif defined(HAVE_ARC4RANDOM_BUF)
46
int
47
fido_get_random(void *buf, size_t len)
48
{
49
        arc4random_buf(buf, len);
50
        return (0);
51
}
52
#elif defined(HAVE_GETRANDOM)
53
int
54
fido_get_random(void *buf, size_t len)
55
27.6k
{
56
27.6k
        ssize_t r;
57
27.6k
58
27.6k
        if ((r = getrandom(buf, len, 0)) < 0 || (size_t)r != len)
59
0
                return (-1);
60
27.6k
61
27.6k
        return (0);
62
27.6k
}
63
#elif defined(HAVE_DEV_URANDOM)
64
int
65
fido_get_random(void *buf, size_t len)
66
{
67
        int     fd = -1;
68
        int     ok = -1;
69
        ssize_t r;
70
71
        if ((fd = open(FIDO_RANDOM_DEV, O_RDONLY)) < 0)
72
                goto fail;
73
        if ((r = read(fd, buf, len)) < 0 || (size_t)r != len)
74
                goto fail;
75
76
        ok = 0;
77
fail:
78
        if (fd != -1)
79
                close(fd);
80
81
        return (ok);
82
}
83
#else
84
#error "please provide an implementation of fido_get_random() for your platform"
85
#endif /* _WIN32 */