1 /*
2  * Copyright (c) 2014, STMicroelectronics International N.V.
3  * All rights reserved.
4  * Copyright (c) 2015, Linaro Limited
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright notice,
11  * this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright notice,
14  * this list of conditions and the following disclaimer in the documentation
15  * and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29 #ifndef TEE_CLIENT_API_H
30 #define TEE_CLIENT_API_H
31 
32 #ifdef __cplusplus
33 extern "C" {
34 #endif
35 
36 #include <stdint.h>
37 #include <stddef.h>
38 #include <stdbool.h>
39 #include <limits.h>
40 
41 /*
42  * Defines the number of available memory references in an open session or
43  * invoke command operation payload.
44  */
45 #define TEEC_CONFIG_PAYLOAD_REF_COUNT 4
46 
47 /**
48  * Defines the maximum size of a single shared memory block, in bytes, of both
49  * API allocated and API registered memory. There is no good value to put here
50  * (limits depend on specific config used), so this define does not provide any
51  * restriction in this implementation.
52  */
53 #define TEEC_CONFIG_SHAREDMEM_MAX_SIZE ULONG_MAX
54 
55 /**
56  * Flag constants indicating the type of parameters encoded inside the
57  * operation payload (TEEC_Operation), Type is uint32_t.
58  *
59  * TEEC_NONE                   The Parameter is not used
60  *
61  * TEEC_VALUE_INPUT            The Parameter is a TEEC_Value tagged as input.
62  *
63  * TEEC_VALUE_OUTPUT           The Parameter is a TEEC_Value tagged as output.
64  *
65  * TEEC_VALUE_INOUT            The Parameter is a TEEC_Value tagged as both as
66  *                             input and output, i.e., for which both the
67  *                             behaviors of TEEC_VALUE_INPUT and
68  *                             TEEC_VALUE_OUTPUT apply.
69  *
70  * TEEC_MEMREF_TEMP_INPUT      The Parameter is a TEEC_TempMemoryReference
71  *                             describing a region of memory which needs to be
72  *                             temporarily registered for the duration of the
73  *                             Operation and is tagged as input.
74  *
75  * TEEC_MEMREF_TEMP_OUTPUT     Same as TEEC_MEMREF_TEMP_INPUT, but the Memory
76  *                             Reference is tagged as output. The
77  *                             Implementation may update the size field to
78  *                             reflect the required output size in some use
79  *                             cases.
80  *
81  * TEEC_MEMREF_TEMP_INOUT      A Temporary Memory Reference tagged as both
82  *                             input and output, i.e., for which both the
83  *                             behaviors of TEEC_MEMREF_TEMP_INPUT and
84  *                             TEEC_MEMREF_TEMP_OUTPUT apply.
85  *
86  * TEEC_MEMREF_WHOLE           The Parameter is a Registered Memory Reference
87  *                             that refers to the entirety of its parent Shared
88  *                             Memory block. The parameter structure is a
89  *                             TEEC_MemoryReference. In this structure, the
90  *                             Implementation MUST read only the parent field
91  *                             and MAY update the size field when the operation
92  *                             completes.
93  *
94  * TEEC_MEMREF_PARTIAL_INPUT   A Registered Memory Reference structure that
95  *                             refers to a partial region of its parent Shared
96  *                             Memory block and is tagged as input.
97  *
98  * TEEC_MEMREF_PARTIAL_OUTPUT  Registered Memory Reference structure that
99  *                             refers to a partial region of its parent Shared
100  *                             Memory block and is tagged as output.
101  *
102  * TEEC_MEMREF_PARTIAL_INOUT   The Registered Memory Reference structure that
103  *                             refers to a partial region of its parent Shared
104  *                             Memory block and is tagged as both input and
105  *                             output, i.e., for which both the behaviors of
106  *                             TEEC_MEMREF_PARTIAL_INPUT and
107  *                             TEEC_MEMREF_PARTIAL_OUTPUT apply.
108  */
109 #define TEEC_NONE                   0x00000000
110 #define TEEC_VALUE_INPUT            0x00000001
111 #define TEEC_VALUE_OUTPUT           0x00000002
112 #define TEEC_VALUE_INOUT            0x00000003
113 #define TEEC_MEMREF_TEMP_INPUT      0x00000005
114 #define TEEC_MEMREF_TEMP_OUTPUT     0x00000006
115 #define TEEC_MEMREF_TEMP_INOUT      0x00000007
116 #define TEEC_MEMREF_WHOLE           0x0000000C
117 #define TEEC_MEMREF_PARTIAL_INPUT   0x0000000D
118 #define TEEC_MEMREF_PARTIAL_OUTPUT  0x0000000E
119 #define TEEC_MEMREF_PARTIAL_INOUT   0x0000000F
120 
121 /**
122  * Flag constants indicating the data transfer direction of memory in
123  * TEEC_Parameter. TEEC_MEM_INPUT signifies data transfer direction from the
124  * client application to the TEE. TEEC_MEM_OUTPUT signifies data transfer
125  * direction from the TEE to the client application. Type is uint32_t.
126  *
127  * TEEC_MEM_INPUT   The Shared Memory can carry data from the client
128  *                  application to the Trusted Application.
129  * TEEC_MEM_OUTPUT  The Shared Memory can carry data from the Trusted
130  *                  Application to the client application.
131  */
132 #define TEEC_MEM_INPUT   0x00000001
133 #define TEEC_MEM_OUTPUT  0x00000002
134 
135 /**
136  * Return values. Type is TEEC_Result
137  *
138  * TEEC_SUCCESS                 The operation was successful.
139  * TEEC_ERROR_GENERIC           Non-specific cause.
140  * TEEC_ERROR_ACCESS_DENIED     Access privileges are not sufficient.
141  * TEEC_ERROR_CANCEL            The operation was canceled.
142  * TEEC_ERROR_ACCESS_CONFLICT   Concurrent accesses caused conflict.
143  * TEEC_ERROR_EXCESS_DATA       Too much data for the requested operation was
144  *                              passed.
145  * TEEC_ERROR_BAD_FORMAT        Input data was of invalid format.
146  * TEEC_ERROR_BAD_PARAMETERS    Input parameters were invalid.
147  * TEEC_ERROR_BAD_STATE         Operation is not valid in the current state.
148  * TEEC_ERROR_ITEM_NOT_FOUND    The requested data item is not found.
149  * TEEC_ERROR_NOT_IMPLEMENTED   The requested operation should exist but is not
150  *                              yet implemented.
151  * TEEC_ERROR_NOT_SUPPORTED     The requested operation is valid but is not
152  *                              supported in this implementation.
153  * TEEC_ERROR_NO_DATA           Expected data was missing.
154  * TEEC_ERROR_OUT_OF_MEMORY     System ran out of resources.
155  * TEEC_ERROR_BUSY              The system is busy working on something else.
156  * TEEC_ERROR_COMMUNICATION     Communication with a remote party failed.
157  * TEEC_ERROR_SECURITY          A security fault was detected.
158  * TEEC_ERROR_SHORT_BUFFER      The supplied buffer is too short for the
159  *                              generated output.
160  * TEEC_ERROR_TARGET_DEAD       Trusted Application has panicked
161  *                              during the operation.
162  */
163 
164 /**
165  *  Standard defined error codes.
166  */
167 #define TEEC_SUCCESS                       0x00000000
168 #define TEEC_ERROR_STORAGE_NOT_AVAILABLE   0xF0100003
169 #define TEEC_ERROR_GENERIC                 0xFFFF0000
170 #define TEEC_ERROR_ACCESS_DENIED           0xFFFF0001
171 #define TEEC_ERROR_CANCEL                  0xFFFF0002
172 #define TEEC_ERROR_ACCESS_CONFLICT         0xFFFF0003
173 #define TEEC_ERROR_EXCESS_DATA             0xFFFF0004
174 #define TEEC_ERROR_BAD_FORMAT              0xFFFF0005
175 #define TEEC_ERROR_BAD_PARAMETERS          0xFFFF0006
176 #define TEEC_ERROR_BAD_STATE               0xFFFF0007
177 #define TEEC_ERROR_ITEM_NOT_FOUND          0xFFFF0008
178 #define TEEC_ERROR_NOT_IMPLEMENTED         0xFFFF0009
179 #define TEEC_ERROR_NOT_SUPPORTED           0xFFFF000A
180 #define TEEC_ERROR_NO_DATA                 0xFFFF000B
181 #define TEEC_ERROR_OUT_OF_MEMORY           0xFFFF000C
182 #define TEEC_ERROR_BUSY                    0xFFFF000D
183 #define TEEC_ERROR_COMMUNICATION           0xFFFF000E
184 #define TEEC_ERROR_SECURITY                0xFFFF000F
185 #define TEEC_ERROR_SHORT_BUFFER            0xFFFF0010
186 #define TEEC_ERROR_EXTERNAL_CANCEL         0xFFFF0011
187 #define TEEC_ERROR_TARGET_DEAD             0xFFFF3024
188 
189 /**
190  * Function error origins, of type TEEC_ErrorOrigin. These indicate where in
191  * the software stack a particular return value originates from.
192  *
193  * TEEC_ORIGIN_API          The error originated within the TEE Client API
194  *                          implementation.
195  * TEEC_ORIGIN_COMMS        The error originated within the underlying
196  *                          communications stack linking the rich OS with
197  *                          the TEE.
198  * TEEC_ORIGIN_TEE          The error originated within the common TEE code.
199  * TEEC_ORIGIN_TRUSTED_APP  The error originated within the Trusted Application
200  *                          code.
201  */
202 #define TEEC_ORIGIN_API          0x00000001
203 #define TEEC_ORIGIN_COMMS        0x00000002
204 #define TEEC_ORIGIN_TEE          0x00000003
205 #define TEEC_ORIGIN_TRUSTED_APP  0x00000004
206 
207 /**
208  * Session login methods, for use in TEEC_OpenSession() as parameter
209  * connectionMethod. Type is uint32_t.
210  *
211  * TEEC_LOGIN_PUBLIC    	 No login data is provided.
212  * TEEC_LOGIN_USER         	Login data about the user running the Client
213  *                         	Application process is provided.
214  * TEEC_LOGIN_GROUP        	Login data about the group running the Client
215  *                         	Application process is provided.
216  * TEEC_LOGIN_APPLICATION  	Login data about the running Client Application
217  *                         	itself is provided.
218  * TEEC_LOGIN_USER_APPLICATION  Login data about the user and the running
219  *                          	Client Application itself is provided.
220  * TEEC_LOGIN_GROUP_APPLICATION Login data about the group and the running
221  *                          	Client Application itself is provided.
222  */
223 #define TEEC_LOGIN_PUBLIC       0x00000000
224 #define TEEC_LOGIN_USER         0x00000001
225 #define TEEC_LOGIN_GROUP        0x00000002
226 #define TEEC_LOGIN_APPLICATION  0x00000004
227 #define TEEC_LOGIN_USER_APPLICATION  0x00000005
228 #define TEEC_LOGIN_GROUP_APPLICATION  0x00000006
229 
230 /**
231  * Encode the paramTypes according to the supplied types.
232  *
233  * @param p0 The first param type.
234  * @param p1 The second param type.
235  * @param p2 The third param type.
236  * @param p3 The fourth param type.
237  */
238 #define TEEC_PARAM_TYPES(p0, p1, p2, p3) \
239 	((p0) | ((p1) << 4) | ((p2) << 8) | ((p3) << 12))
240 
241 /**
242  * Get the i_th param type from the paramType.
243  *
244  * @param p The paramType.
245  * @param i The i-th parameter to get the type for.
246  */
247 #define TEEC_PARAM_TYPE_GET(p, i) (((p) >> (i * 4)) & 0xF)
248 
249 typedef uint32_t TEEC_Result;
250 
251 /**
252  * struct TEEC_Context - Represents a connection between a client application
253  * and a TEE.
254  */
255 typedef struct {
256 	/* Implementation defined */
257 	int fd;
258 	bool reg_mem;
259 	bool memref_null;
260 } TEEC_Context;
261 
262 /**
263  * This type contains a Universally Unique Resource Identifier (UUID) type as
264  * defined in RFC4122. These UUID values are used to identify Trusted
265  * Applications.
266  */
267 typedef struct {
268 	uint32_t timeLow;
269 	uint16_t timeMid;
270 	uint16_t timeHiAndVersion;
271 	uint8_t clockSeqAndNode[8];
272 } TEEC_UUID;
273 
274 /**
275  * struct TEEC_SharedMemory - Memory to transfer data between a client
276  * application and trusted code.
277  *
278  * @param buffer      The memory buffer which is to be, or has been, shared
279  *                    with the TEE.
280  * @param size        The size, in bytes, of the memory buffer.
281  * @param flags       Bit-vector which holds properties of buffer.
282  *                    The bit-vector can contain either or both of the
283  *                    TEEC_MEM_INPUT and TEEC_MEM_OUTPUT flags.
284  *
285  * A shared memory block is a region of memory allocated in the context of the
286  * client application memory space that can be used to transfer data between
287  * that client application and a trusted application. The user of this struct
288  * is responsible to populate the buffer pointer.
289  */
290 typedef struct {
291 	void *buffer;
292 	size_t size;
293 	uint32_t flags;
294 	/*
295 	 * Implementation-Defined
296 	 */
297 	int id;
298 	size_t alloced_size;
299 	void *shadow_buffer;
300 	int registered_fd;
301 	union {
302 		bool dummy;
303 		uint8_t flags;
304 	} internal;
305 } TEEC_SharedMemory;
306 
307 /**
308  * struct TEEC_TempMemoryReference - Temporary memory to transfer data between
309  * a client application and trusted code, only used for the duration of the
310  * operation.
311  *
312  * @param buffer  The memory buffer which is to be, or has been shared with
313  *                the TEE.
314  * @param size    The size, in bytes, of the memory buffer.
315  *
316  * A memory buffer that is registered temporarily for the duration of the
317  * operation to be called.
318  */
319 typedef struct {
320 	void *buffer;
321 	size_t size;
322 } TEEC_TempMemoryReference;
323 
324 /**
325  * struct TEEC_RegisteredMemoryReference - use a pre-registered or
326  * pre-allocated shared memory block of memory to transfer data between
327  * a client application and trusted code.
328  *
329  * @param parent  Points to a shared memory structure. The memory reference
330  *                may utilize the whole shared memory or only a part of it.
331  *                Must not be NULL
332  *
333  * @param size    The size, in bytes, of the memory buffer.
334  *
335  * @param offset  The offset, in bytes, of the referenced memory region from
336  *                the start of the shared memory block.
337  *
338  */
339 typedef struct {
340 	TEEC_SharedMemory *parent;
341 	size_t size;
342 	size_t offset;
343 } TEEC_RegisteredMemoryReference;
344 
345 /**
346  * struct TEEC_Value - Small raw data container
347  *
348  * Instead of allocating a shared memory buffer this structure can be used
349  * to pass small raw data between a client application and trusted code.
350  *
351  * @param a  The first integer value.
352  *
353  * @param b  The second value.
354  */
355 typedef struct {
356 	uint32_t a;
357 	uint32_t b;
358 } TEEC_Value;
359 
360 /**
361  * union TEEC_Parameter - Memory container to be used when passing data between
362  *                        client application and trusted code.
363  *
364  * Either the client uses a shared memory reference, parts of it or a small raw
365  * data container.
366  *
367  * @param tmpref  A temporary memory reference only valid for the duration
368  *                of the operation.
369  *
370  * @param memref  The entire shared memory or parts of it.
371  *
372  * @param value   The small raw data container to use
373  */
374 typedef union {
375 	TEEC_TempMemoryReference tmpref;
376 	TEEC_RegisteredMemoryReference memref;
377 	TEEC_Value value;
378 } TEEC_Parameter;
379 
380 /**
381  * struct TEEC_Session - Represents a connection between a client application
382  * and a trusted application.
383  */
384 typedef struct {
385 	/* Implementation defined */
386 	TEEC_Context *ctx;
387 	uint32_t session_id;
388 } TEEC_Session;
389 
390 /**
391  * struct TEEC_Operation - Holds information and memory references used in
392  * TEEC_InvokeCommand().
393  *
394  * @param   started     Client must initialize to zero if it needs to cancel
395  *                      an operation about to be performed.
396  * @param   paramTypes  Type of data passed. Use TEEC_PARAMS_TYPE macro to
397  *                      create the correct flags.
398  *                      0 means TEEC_NONE is passed for all params.
399  * @param   params      Array of parameters of type TEEC_Parameter.
400  * @param   session     Internal pointer to the last session used by
401  *                      TEEC_InvokeCommand with this operation.
402  *
403  */
404 typedef struct {
405 	uint32_t started;
406 	uint32_t paramTypes;
407 	TEEC_Parameter params[TEEC_CONFIG_PAYLOAD_REF_COUNT];
408 	/* Implementation-Defined */
409 	TEEC_Session *session;
410 } TEEC_Operation;
411 
412 /**
413  * TEEC_InitializeContext() - Initializes a context holding connection
414  * information on the specific TEE, designated by the name string.
415 
416  * @param name    A zero-terminated string identifying the TEE to connect to.
417  *                If name is set to NULL, the default TEE is connected to. NULL
418  *                is the only supported value in this version of the API
419  *                implementation.
420  *
421  * @param context The context structure which is to be initialized.
422  *
423  * @return TEEC_SUCCESS  The initialization was successful.
424  * @return TEEC_Result   Something failed.
425  */
426 TEEC_Result TEEC_InitializeContext(const char *name, TEEC_Context *context);
427 
428 /**
429  * TEEC_FinalizeContext() - Destroys a context holding connection information
430  * on the specific TEE.
431  *
432  * This function destroys an initialized TEE context, closing the connection
433  * between the client application and the TEE. This function must only be
434  * called when all sessions related to this TEE context have been closed and
435  * all shared memory blocks have been released.
436  *
437  * @param context       The context to be destroyed.
438  */
439 void TEEC_FinalizeContext(TEEC_Context *context);
440 
441 /**
442  * TEEC_OpenSession() - Opens a new session with the specified trusted
443  *                      application.
444  *
445  * @param context            The initialized TEE context structure in which
446  *                           scope to open the session.
447  * @param session            The session to initialize.
448  * @param destination        A structure identifying the trusted application
449  *                           with which to open a session.
450  *
451  * @param connectionMethod   The connection method to use.
452  * @param connectionData     Any data necessary to connect with the chosen
453  *                           connection method. Not supported, should be set to
454  *                           NULL.
455  * @param operation          An operation structure to use in the session. May
456  *                           be set to NULL to signify no operation structure
457  *                           needed.
458  *
459  * @param returnOrigin       A parameter which will hold the error origin if
460  *                           this function returns any value other than
461  *                           TEEC_SUCCESS.
462  *
463  * @return TEEC_SUCCESS      OpenSession successfully opened a new session.
464  * @return TEEC_Result       Something failed.
465  *
466  */
467 TEEC_Result TEEC_OpenSession(TEEC_Context *context,
468 			     TEEC_Session *session,
469 			     const TEEC_UUID *destination,
470 			     uint32_t connectionMethod,
471 			     const void *connectionData,
472 			     TEEC_Operation *operation,
473 			     uint32_t *returnOrigin);
474 
475 /**
476  * TEEC_CloseSession() - Closes the session which has been opened with the
477  * specific trusted application.
478  *
479  * @param session The opened session to close.
480  */
481 void TEEC_CloseSession(TEEC_Session *session);
482 
483 /**
484  * TEEC_InvokeCommand() - Executes a command in the specified trusted
485  * application.
486  *
487  * @param session        A handle to an open connection to the trusted
488  *                       application.
489  * @param commandID      Identifier of the command in the trusted application
490  *                       to invoke.
491  * @param operation      An operation structure to use in the invoke command.
492  *                       May be set to NULL to signify no operation structure
493  *                       needed.
494  * @param returnOrigin   A parameter which will hold the error origin if this
495  *                       function returns any value other than TEEC_SUCCESS.
496  *
497  * @return TEEC_SUCCESS  OpenSession successfully opened a new session.
498  * @return TEEC_Result   Something failed.
499  */
500 TEEC_Result TEEC_InvokeCommand(TEEC_Session *session,
501 			       uint32_t commandID,
502 			       TEEC_Operation *operation,
503 			       uint32_t *returnOrigin);
504 
505 /**
506  * TEEC_RegisterSharedMemory() - Register a block of existing memory as a
507  * shared block within the scope of the specified context.
508  *
509  * @param context    The initialized TEE context structure in which scope to
510  *                   open the session.
511  * @param sharedMem  pointer to the shared memory structure to register.
512  *
513  * @return TEEC_SUCCESS              The registration was successful.
514  * @return TEEC_ERROR_OUT_OF_MEMORY  Memory exhaustion.
515  * @return TEEC_Result               Something failed.
516  */
517 TEEC_Result TEEC_RegisterSharedMemory(TEEC_Context *context,
518 				      TEEC_SharedMemory *sharedMem);
519 
520 /**
521  * TEEC_AllocateSharedMemory() - Allocate shared memory for TEE.
522  *
523  * @param context     The initialized TEE context structure in which scope to
524  *                    open the session.
525  * @param sharedMem   Pointer to the allocated shared memory.
526  *
527  * @return TEEC_SUCCESS              The registration was successful.
528  * @return TEEC_ERROR_OUT_OF_MEMORY  Memory exhaustion.
529  * @return TEEC_Result               Something failed.
530  */
531 TEEC_Result TEEC_AllocateSharedMemory(TEEC_Context *context,
532 				      TEEC_SharedMemory *sharedMem);
533 
534 /**
535  * TEEC_ReleaseSharedMemory() - Free or deregister the shared memory.
536  *
537  * @param sharedMem  Pointer to the shared memory to be freed.
538  */
539 void TEEC_ReleaseSharedMemory(TEEC_SharedMemory *sharedMemory);
540 
541 /**
542  * TEEC_RequestCancellation() - Request the cancellation of a pending open
543  *                              session or command invocation.
544  *
545  * @param operation Pointer to an operation previously passed to open session
546  *                  or invoke.
547  */
548 void TEEC_RequestCancellation(TEEC_Operation *operation);
549 
550 #ifdef __cplusplus
551 }
552 #endif
553 
554 #endif
555