forked from kata-containers/agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
random_linux.go
63 lines (54 loc) · 1.38 KB
/
random_linux.go
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
//
// Copyright (c) 2018 HyperHQ.Inc
//
// SPDX-License-Identifier: Apache-2.0
//
package main
import (
"fmt"
"io"
"os"
"syscall"
"unsafe"
)
const (
rngDev = "/dev/random"
// include/uapi/linux/random.h
// RNDADDTOENTCNT _IOW( 'R', 0x01, int )
// RNDRESEEDCRNG _IO( 'R', 0x07 )
iocRNDADDTOENTCNT = 0x40045201
iocRNDRESEEDCRNG = 0x5207
)
func reseedRNG(data []byte) error {
if len(data) == 0 {
return fmt.Errorf("missing entropy data")
}
// Write entropy
f, err := os.OpenFile(rngDev, os.O_WRONLY, 0)
if err != nil {
agentLog.WithError(err).Warn("Could not open rng device")
return err
}
defer f.Close()
n, err := f.Write(data)
if err != nil {
agentLog.WithError(err).Warn("Could not write to rng device")
return err
}
if n < len(data) {
agentLog.WithError(io.ErrShortWrite).Warn("Short write to rng device")
return io.ErrShortWrite
}
// Add data to the entropy count
_, _, errNo := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), iocRNDADDTOENTCNT, uintptr(unsafe.Pointer(&n)))
if errNo != 0 {
agentLog.WithError(errNo).Warn("Could not add to rng entropy count, ignoring")
}
// Newer kernel supports RNDRESEEDCRNG ioctl to actively kick-off reseed.
// Let's make use of it if possible.
_, _, errNo = syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), iocRNDRESEEDCRNG, 0)
if errNo != 0 {
agentLog.WithError(errNo).Warn("Could not reseed rng, ignoring")
}
return nil
}