File: optee_impl.go

package info (click to toggle)
snapd 2.72-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 80,412 kB
  • sloc: sh: 16,506; ansic: 16,211; python: 11,213; makefile: 1,919; exp: 190; awk: 58; xml: 22
file content (316 lines) | stat: -rw-r--r-- 9,020 bytes parent folder | download
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// -*- Mode: Go; indent-tabs-mode: t -*-
//go:build optee && linux && (arm || arm64)

/*
 * Copyright (C) Canonical Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package optee

/*
#cgo CFLAGS: -I./
#cgo LDFLAGS: -lteec
#include <tee_client_api.h>
#include <fde_key_handler_ta_type.h>
#include <stdint.h>
#include <stdlib.h>

TEEC_UUID fde_ta_uuid = FDE_KEY_HANDLER_UUID_ID;

TEEC_UUID pta_device_uuid = { 0x7011a688, 0xddde, 0x4053, \
	{ \
		0xa5, 0xa9, 0x7b, 0x3c, 0x4d, 0xdf, 0x13, 0xb8 \
	} \
};
*/
import "C"

import (
	"bytes"
	"errors"
	"fmt"
	"unsafe"

	"github.com/snapcore/snapd/logger"
)

type opteeClient struct{}

func (c *opteeClient) Present() bool {
	// the first time we invoke the PTA without sending a buffer to fill. the
	// PTA handles this by just returning the size of the buffer it will need.
	bufferSize, err := devicesBufferSize()
	if err != nil {
		return false
	}

	// parameters:
	// - output parameter containing a slice of bytes, each 16 byte segment is a UUID
	// - none
	// - none
	// - none
	params := teecParamTypes(C.TEEC_MEMREF_TEMP_OUTPUT, C.TEEC_NONE, C.TEEC_NONE, C.TEEC_NONE)
	op := &C.TEEC_Operation{
		started:    1,
		paramTypes: params,
	}

	outputMemRef, free := addMemRefToOp(op, 0, make([]byte, bufferSize))
	defer free()

	// this PTA (psuedo trusted application) command returns a list of PTA and
	// early TA UUIDs. we know that our TA will always be an early TA.
	if err := invoke(C.pta_device_uuid, 0x0 /* PTA_CMD_GET_DEVICES */, op); err != nil {
		return false
	}

	// output here is a slice of bytes, each 16 byte segment is a UUID
	output := C.GoBytes(outputMemRef.buffer, C.int(outputMemRef.size))

	// fdeUUID is the byte encoding of the FDE TA UUID (FDE_KEY_HANDLER_UUID_ID
	// in fde_key_handler_ta_type.h). having this pre-calculated eliminates some
	// code that would be required to do the conversion.
	fdeUUID := [...]byte{0xfd, 0x1b, 0x2a, 0x86, 0x36, 0x68, 0x11, 0xeb, 0xad, 0xc1, 0x2, 0x42, 0xac, 0x12, 0x0, 0x2}

	for i := 0; i+16 < len(output)+1; i += 16 {
		if !bytes.Equal(fdeUUID[:], output[i:i+16]) {
			continue
		}

		version, err := c.Version()
		if err != nil {
			logger.Noticef("FDE TA found")
		} else {
			logger.Noticef("FDE TA version %q found", version)
		}

		return true
	}

	return false
}

func devicesBufferSize() (int, error) {
	// parameters:
	// - output parameter containing a slice of bytes, each 16 byte segment is a
	//   UUID; in this case, we will send in an empty slice to just retrieve the
	//   required buffer size
	// - none
	// - none
	// - none
	params := teecParamTypes(C.TEEC_MEMREF_TEMP_OUTPUT, C.TEEC_NONE, C.TEEC_NONE, C.TEEC_NONE)
	op := &C.TEEC_Operation{
		started:    1,
		paramTypes: params,
	}

	// we don't use addMemRefToOp here because we don't need to allocate
	// anything
	memRef := unionAsType[C.TEEC_TempMemoryReference](&op.params[0])
	memRef.size = 0
	memRef.buffer = nil

	// the first time we invoke the PTA without sending a buffer to fill. the
	// PTA handles this by just returning the size of the buffer it will need.
	res, err := invokeUnchecked(C.pta_device_uuid, 0x0 /* PTA_CMD_GET_DEVICES */, op)
	if err != nil {
		return 0, err
	}

	if res != C.TEEC_ERROR_SHORT_BUFFER {
		return 0, fmt.Errorf("expected short buffer error from PTA: %v", res)
	}

	return int(memRef.size), nil
}

func addMemRefToOp(op *C.TEEC_Operation, index int, buffer []byte) (*C.TEEC_TempMemoryReference, func()) {
	malloced := C.CBytes(buffer)

	memRef := unionAsType[C.TEEC_TempMemoryReference](&op.params[index])
	memRef.size = C.size_t(len(buffer))
	memRef.buffer = malloced

	return memRef, func() {
		C.free(malloced)
	}
}

func (c *opteeClient) DecryptKey(input []byte, handle []byte) ([]byte, error) {
	if len(input) == 0 || len(handle) == 0 {
		return nil, errors.New("internal error: input and handle both must contain data")
	}

	// parameters:
	// - input parameter containing the encrypted key
	// - input parameter containing the handle
	// - output parameter containing the decrypted key
	// - none
	params := teecParamTypes(C.TEEC_MEMREF_TEMP_INPUT, C.TEEC_MEMREF_TEMP_INPUT, C.TEEC_MEMREF_TEMP_OUTPUT, C.TEEC_NONE)
	op := &C.TEEC_Operation{
		started:    1,
		paramTypes: params,
	}

	_, free := addMemRefToOp(op, 0, input)
	defer free()

	_, free = addMemRefToOp(op, 1, handle)
	defer free()

	unsealedMemRef, free := addMemRefToOp(op, 2, make([]byte, C.MAX_BUF_SIZE))
	defer free()

	err := invoke(C.fde_ta_uuid, C.TA_CMD_KEY_DECRYPT, op)
	if err != nil {
		return nil, err
	}

	unsealed := C.GoBytes(unsealedMemRef.buffer, C.int(unsealedMemRef.size))

	return unsealed, nil
}

func (c *opteeClient) EncryptKey(input []byte) (handle []byte, sealed []byte, err error) {
	if len(input) == 0 {
		return nil, nil, errors.New("internal error: input must contain data")
	}

	// parameters:
	// - input parameter containing the key to encrypt
	// - output parameter containing the handle
	// - output parameter containing the encrypted key
	// - none
	params := teecParamTypes(C.TEEC_MEMREF_TEMP_INPUT, C.TEEC_MEMREF_TEMP_OUTPUT, C.TEEC_MEMREF_TEMP_OUTPUT, C.TEEC_NONE)
	op := &C.TEEC_Operation{
		started:    1,
		paramTypes: params,
	}

	_, free := addMemRefToOp(op, 0, input)
	defer free()

	handleMemRef, free := addMemRefToOp(op, 1, make([]byte, C.HANDLE_SIZE))
	defer free()

	sealedMemRef, free := addMemRefToOp(op, 2, make([]byte, C.MAX_BUF_SIZE))
	defer free()

	err = invoke(C.fde_ta_uuid, C.TA_CMD_KEY_ENCRYPT, op)
	if err != nil {
		return nil, nil, err
	}

	handle = C.GoBytes(handleMemRef.buffer, C.int(handleMemRef.size))
	sealed = C.GoBytes(sealedMemRef.buffer, C.int(sealedMemRef.size))

	return handle, sealed, nil
}

func (c *opteeClient) Lock() error {
	op := &C.TEEC_Operation{
		started:    1,
		paramTypes: teecParamTypes(C.TEEC_NONE, C.TEEC_NONE, C.TEEC_NONE, C.TEEC_NONE),
	}

	return invoke(C.fde_ta_uuid, C.TA_CMD_LOCK, op)
}

func (c *opteeClient) Version() (int, error) {
	// parameters:
	// - output parameter containing the version
	// - none
	// - none
	// - none
	params := teecParamTypes(C.TEEC_VALUE_OUTPUT, C.TEEC_NONE, C.TEEC_NONE, C.TEEC_NONE)
	op := &C.TEEC_Operation{
		started:    1,
		paramTypes: params,
	}

	value := unionAsType[C.TEEC_Value](&op.params[0])

	if err := invoke(C.fde_ta_uuid, C.TA_CMD_TA_VERSION, op); err != nil {
		return 0, err
	}

	return int(value.a), nil
}

func newFDETAClient() FDETAClient {
	return &opteeClient{}
}

// unionAsType interprets the memory that union points to as a T. This is useful
// when working with C unions, since they are converted to byte arrays when used
// from Go.
func unionAsType[T any, U any](union *U) *T {
	return (*T)(unsafe.Pointer(union))
}

// teecParamTypes is a Go version of TEEC_PARAM_TYPES, since that is a macro and
// cannot be used from Go.
//
// OPTEE TAs support a few parameter types, we use these:
//   - TEEC_MEMREF_TEMP_INPUT: input parameter containing a slice of bytes
//   - TEEC_MEMREF_TEMP_OUTPUT: output parameter containing a slice of bytes
//   - TEEC_NONE: unused parameter
func teecParamTypes(p0, p1, p2, p3 C.uint32_t) C.uint32_t {
	return p0 | (p1 << 4) | (p2 << 8) | (p3 << 12)
}

func invoke(uuid C.TEEC_UUID, cmd uint32, op *C.TEEC_Operation) error {
	res, err := invokeUnchecked(uuid, cmd, op)
	if err != nil {
		return err
	}

	if res != C.TEEC_SUCCESS {
		return fmt.Errorf("cannot invoke op-tee command: 0x%x", uint32(res))
	}
	return nil
}

func invokeUnchecked(uuid C.TEEC_UUID, cmd uint32, op *C.TEEC_Operation) (C.TEEC_Result, error) {
	// the optee library stores a pointer to the context (ctx) when opening a
	// session (sess) inside of the session struct. to avoid passing a go
	// pointer containing another go pointer into C (which cgo forbids), we must
	// allocate the context itself in C memory
	ctx := (*C.TEEC_Context)(C.malloc(C.size_t(unsafe.Sizeof(C.TEEC_Context{}))))
	if ctx == nil {
		return 0, errors.New("cannot allocate op-tee context")
	}
	defer C.free(unsafe.Pointer(ctx))

	res := C.TEEC_InitializeContext(nil, ctx)
	if res != 0 {
		return 0, fmt.Errorf("cannot initalize op-tee context: 0x%x", uint32(res))
	}
	defer C.TEEC_FinalizeContext(ctx)

	var code C.uint32_t
	var sess C.TEEC_Session

	res = C.TEEC_OpenSession(ctx, &sess, &uuid, C.TEEC_LOGIN_PUBLIC, nil, nil, &code)
	if res != 0 {
		return 0, fmt.Errorf("cannot open op-tee session: 0x%x", uint32(res))
	}
	defer C.TEEC_CloseSession(&sess)

	code = 0

	return C.TEEC_InvokeCommand(&sess, C.uint32_t(cmd), op, &code), nil
}