-
Notifications
You must be signed in to change notification settings - Fork 6
/
nsm.go
257 lines (209 loc) · 6.1 KB
/
nsm.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Package nsm implements the Nitro Security Module interface.
package nsm
import (
"bytes"
"errors"
"fmt"
"os"
"sync"
"syscall"
"unsafe"
"github.com/fxamacker/cbor/v2"
"github.com/hf/nsm/ioc"
"github.com/hf/nsm/request"
"github.com/hf/nsm/response"
)
const (
maxRequestSize = 0x1000
maxResponseSize = 0x3000
ioctlMagic = 0x0A
)
// FileDescriptor is a generic file descriptor interface that can be closed.
// os.File conforms to this interface.
type FileDescriptor interface {
// Provide the uintptr for the file descriptor.
Fd() uintptr
// Close the file descriptor.
Close() error
}
// Options for the opening of the NSM session.
type Options struct {
// A function that opens the NSM device file `/dev/nsm`.
Open func() (FileDescriptor, error)
// A function that implements the syscall.Syscall interface and is able to
// work with the file descriptor returned from `Open` as the `a1` argument.
Syscall func(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
}
// DefaultOptions can be used to open the default NSM session on `/dev/nsm`.
var DefaultOptions = Options{
Open: func() (FileDescriptor, error) {
return os.Open("/dev/nsm")
},
Syscall: syscall.Syscall,
}
// ErrorIoctlFailed is an error returned when the underlying ioctl syscall has
// failed.
type ErrorIoctlFailed struct {
// Errno is the errno returned by the syscall.
Errno syscall.Errno
}
// Error returns the formatted string.
func (err *ErrorIoctlFailed) Error() string {
return fmt.Sprintf("ioctl failed on device with errno %v", err.Errno)
}
// ErrorGetRandomFailed is an error returned when the GetRandom request as part
// of a `Read` has failed with an error code, is invalid or did not return any
// random bytes.
type ErrorGetRandomFailed struct {
ErrorCode response.ErrorCode
}
// Error returns the formatted string.
func (err *ErrorGetRandomFailed) Error() string {
if "" != err.ErrorCode {
return fmt.Sprintf("GetRandom failed with error code %v", err.ErrorCode)
}
return "GetRandom response did not include random bytes"
}
var (
// ErrSessionClosed is returned when the session is in a closed state.
ErrSessionClosed error = errors.New("Session is closed")
)
// A Session is used to interact with the NSM.
type Session struct {
fd FileDescriptor
options Options
reqpool *sync.Pool
respool *sync.Pool
}
type ioctlMessage struct {
Request syscall.Iovec
Response syscall.Iovec
}
func send(options Options, fd uintptr, req []byte, res []byte) ([]byte, error) {
iovecReq := syscall.Iovec{
Base: &req[0],
}
iovecReq.SetLen(len(req))
iovecRes := syscall.Iovec{
Base: &res[0],
}
iovecRes.SetLen(len(res))
msg := ioctlMessage{
Request: iovecReq,
Response: iovecRes,
}
_, _, err := options.Syscall(
syscall.SYS_IOCTL,
fd,
uintptr(ioc.Command(ioc.READ|ioc.WRITE, ioctlMagic, 0, uint(unsafe.Sizeof(msg)))),
uintptr(unsafe.Pointer(&msg)),
)
if 0 != err {
return nil, &ErrorIoctlFailed{
Errno: err,
}
}
return res[:msg.Response.Len], nil
}
// OpenSession opens a new session with the provided options.
func OpenSession(opts Options) (*Session, error) {
session := &Session{
options: opts,
}
fd, err := opts.Open()
if nil != err {
return session, err
}
session.fd = fd
session.reqpool = &sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, maxRequestSize))
},
}
session.respool = &sync.Pool{
New: func() interface{} {
return make([]byte, maxResponseSize)
},
}
return session, nil
}
// OpenDefaultSession opens a new session with the default options.
func OpenDefaultSession() (*Session, error) {
return OpenSession(DefaultOptions)
}
// Close this session. It is not thread safe to Close while other threads are
// Read-ing or Send-ing.
func (sess *Session) Close() error {
if nil == sess.fd {
return nil
}
err := sess.fd.Close()
sess.fd = nil
sess.reqpool = nil
sess.respool = nil
return err
}
// Send an NSM request to the device and await its response. It safe to call
// this from multiple threads that are Read-ing or Send-ing, but not Close-ing.
// Each Send and Read call reserves at most 16KB of memory, so having multiple
// parallel sends or reads might lead to increased memory usage.
func (sess *Session) Send(req request.Request) (response.Response, error) {
reqb := sess.reqpool.Get().(*bytes.Buffer)
defer sess.reqpool.Put(reqb)
reqb.Reset()
encoder := cbor.NewEncoder(reqb)
err := encoder.Encode(req.Encoded())
if nil != err {
return response.Response{}, err
}
resb := sess.respool.Get().([]byte)
defer sess.respool.Put(resb)
return sess.sendMarshaled(reqb, resb)
}
func (sess *Session) sendMarshaled(reqb *bytes.Buffer, resb []byte) (response.Response, error) {
res := response.Response{}
if nil == sess.fd {
return res, errors.New("Session is closed")
}
resb, err := send(sess.options, sess.fd.Fd(), reqb.Bytes(), resb)
if nil != err {
return res, err
}
err = cbor.Unmarshal(resb, &res)
if nil != err {
return res, err
}
return res, nil
}
// Read entropy from the NSM device. It is safe to call this from multiple
// threads that are Read-ing or Send-ing, but not Close-ing. This method will
// always attempt to fill the whole slice with entropy thus blocking until that
// occurs. If reading fails, it is probably an irrecoverable error. Each Send
// and Read call reserves at most 16KB of memory, so having multiple parallel
// sends or reads might lead to increased memory usage.
func (sess *Session) Read(into []byte) (int, error) {
reqb := sess.reqpool.Get().(*bytes.Buffer)
defer sess.reqpool.Put(reqb)
getRandom := request.GetRandom{}
reqb.Reset()
encoder := cbor.NewEncoder(reqb)
err := encoder.Encode(getRandom.Encoded())
if nil != err {
return 0, err
}
resb := sess.respool.Get().([]byte)
defer sess.respool.Put(resb)
for i := 0; i < len(into); i += 0 {
res, err := sess.sendMarshaled(reqb, resb)
if nil != err {
return i, err
}
if "" != res.Error || nil == res.GetRandom || nil == res.GetRandom.Random || 0 == len(res.GetRandom.Random) {
return i, &ErrorGetRandomFailed{
ErrorCode: res.Error,
}
}
i += copy(into[i:], res.GetRandom.Random)
}
return len(into), nil
}