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 #define TEEC_ERROR_STORAGE_NO_SPACE        0xFFFF3041
189 
190 /**
191  * Function error origins, of type TEEC_ErrorOrigin. These indicate where in
192  * the software stack a particular return value originates from.
193  *
194  * TEEC_ORIGIN_API          The error originated within the TEE Client API
195  *                          implementation.
196  * TEEC_ORIGIN_COMMS        The error originated within the underlying
197  *                          communications stack linking the rich OS with
198  *                          the TEE.
199  * TEEC_ORIGIN_TEE          The error originated within the common TEE code.
200  * TEEC_ORIGIN_TRUSTED_APP  The error originated within the Trusted Application
201  *                          code.
202  */
203 #define TEEC_ORIGIN_API          0x00000001
204 #define TEEC_ORIGIN_COMMS        0x00000002
205 #define TEEC_ORIGIN_TEE          0x00000003
206 #define TEEC_ORIGIN_TRUSTED_APP  0x00000004
207 
208 /**
209  * Session login methods, for use in TEEC_OpenSession() as parameter
210  * connectionMethod. Type is uint32_t.
211  *
212  * TEEC_LOGIN_PUBLIC    	 No login data is provided.
213  * TEEC_LOGIN_USER         	Login data about the user running the Client
214  *                         	Application process is provided.
215  * TEEC_LOGIN_GROUP        	Login data about the group running the Client
216  *                         	Application process is provided.
217  * TEEC_LOGIN_APPLICATION  	Login data about the running Client Application
218  *                         	itself is provided.
219  * TEEC_LOGIN_USER_APPLICATION  Login data about the user and the running
220  *                          	Client Application itself is provided.
221  * TEEC_LOGIN_GROUP_APPLICATION Login data about the group and the running
222  *                          	Client Application itself is provided.
223  */
224 #define TEEC_LOGIN_PUBLIC       0x00000000
225 #define TEEC_LOGIN_USER         0x00000001
226 #define TEEC_LOGIN_GROUP        0x00000002
227 #define TEEC_LOGIN_APPLICATION  0x00000004
228 #define TEEC_LOGIN_USER_APPLICATION  0x00000005
229 #define TEEC_LOGIN_GROUP_APPLICATION  0x00000006
230 
231 /**
232  * Encode the paramTypes according to the supplied types.
233  *
234  * @param p0 The first param type.
235  * @param p1 The second param type.
236  * @param p2 The third param type.
237  * @param p3 The fourth param type.
238  */
239 #define TEEC_PARAM_TYPES(p0, p1, p2, p3) \
240 	((p0) | ((p1) << 4) | ((p2) << 8) | ((p3) << 12))
241 
242 /**
243  * Get the i_th param type from the paramType.
244  *
245  * @param p The paramType.
246  * @param i The i-th parameter to get the type for.
247  */
248 #define TEEC_PARAM_TYPE_GET(p, i) (((p) >> (i * 4)) & 0xF)
249 
250 typedef uint32_t TEEC_Result;
251 
252 /**
253  * struct TEEC_Context - Represents a connection between a client application
254  * and a TEE.
255  */
256 typedef struct {
257 	/* Implementation defined */
258 	int fd;
259 	bool reg_mem;
260 	bool memref_null;
261 } TEEC_Context;
262 
263 /**
264  * This type contains a Universally Unique Resource Identifier (UUID) type as
265  * defined in RFC4122. These UUID values are used to identify Trusted
266  * Applications.
267  */
268 typedef struct {
269 	uint32_t timeLow;
270 	uint16_t timeMid;
271 	uint16_t timeHiAndVersion;
272 	uint8_t clockSeqAndNode[8];
273 } TEEC_UUID;
274 
275 /**
276  * struct TEEC_SharedMemory - Memory to transfer data between a client
277  * application and trusted code.
278  *
279  * @param buffer      The memory buffer which is to be, or has been, shared
280  *                    with the TEE.
281  * @param size        The size, in bytes, of the memory buffer.
282  * @param flags       Bit-vector which holds properties of buffer.
283  *                    The bit-vector can contain either or both of the
284  *                    TEEC_MEM_INPUT and TEEC_MEM_OUTPUT flags.
285  *
286  * A shared memory block is a region of memory allocated in the context of the
287  * client application memory space that can be used to transfer data between
288  * that client application and a trusted application. The user of this struct
289  * is responsible to populate the buffer pointer.
290  */
291 typedef struct {
292 	void *buffer;
293 	size_t size;
294 	uint32_t flags;
295 	/*
296 	 * Implementation-Defined
297 	 */
298 	int id;
299 	size_t alloced_size;
300 	void *shadow_buffer;
301 	int registered_fd;
302 	union {
303 		bool dummy;
304 		uint8_t flags;
305 	} internal;
306 } TEEC_SharedMemory;
307 
308 /**
309  * struct TEEC_TempMemoryReference - Temporary memory to transfer data between
310  * a client application and trusted code, only used for the duration of the
311  * operation.
312  *
313  * @param buffer  The memory buffer which is to be, or has been shared with
314  *                the TEE.
315  * @param size    The size, in bytes, of the memory buffer.
316  *
317  * A memory buffer that is registered temporarily for the duration of the
318  * operation to be called.
319  */
320 typedef struct {
321 	void *buffer;
322 	size_t size;
323 } TEEC_TempMemoryReference;
324 
325 /**
326  * struct TEEC_RegisteredMemoryReference - use a pre-registered or
327  * pre-allocated shared memory block of memory to transfer data between
328  * a client application and trusted code.
329  *
330  * @param parent  Points to a shared memory structure. The memory reference
331  *                may utilize the whole shared memory or only a part of it.
332  *                Must not be NULL
333  *
334  * @param size    The size, in bytes, of the memory buffer.
335  *
336  * @param offset  The offset, in bytes, of the referenced memory region from
337  *                the start of the shared memory block.
338  *
339  */
340 typedef struct {
341 	TEEC_SharedMemory *parent;
342 	size_t size;
343 	size_t offset;
344 } TEEC_RegisteredMemoryReference;
345 
346 /**
347  * struct TEEC_Value - Small raw data container
348  *
349  * Instead of allocating a shared memory buffer this structure can be used
350  * to pass small raw data between a client application and trusted code.
351  *
352  * @param a  The first integer value.
353  *
354  * @param b  The second value.
355  */
356 typedef struct {
357 	uint32_t a;
358 	uint32_t b;
359 } TEEC_Value;
360 
361 /**
362  * union TEEC_Parameter - Memory container to be used when passing data between
363  *                        client application and trusted code.
364  *
365  * Either the client uses a shared memory reference, parts of it or a small raw
366  * data container.
367  *
368  * @param tmpref  A temporary memory reference only valid for the duration
369  *                of the operation.
370  *
371  * @param memref  The entire shared memory or parts of it.
372  *
373  * @param value   The small raw data container to use
374  */
375 typedef union {
376 	TEEC_TempMemoryReference tmpref;
377 	TEEC_RegisteredMemoryReference memref;
378 	TEEC_Value value;
379 } TEEC_Parameter;
380 
381 /**
382  * struct TEEC_Session - Represents a connection between a client application
383  * and a trusted application.
384  */
385 typedef struct {
386 	/* Implementation defined */
387 	TEEC_Context *ctx;
388 	uint32_t session_id;
389 } TEEC_Session;
390 
391 /**
392  * struct TEEC_Operation - Holds information and memory references used in
393  * TEEC_InvokeCommand().
394  *
395  * @param   started     Client must initialize to zero if it needs to cancel
396  *                      an operation about to be performed.
397  * @param   paramTypes  Type of data passed. Use TEEC_PARAM_TYPES macro to
398  *                      create the correct flags.
399  *                      0 means TEEC_NONE is passed for all params.
400  * @param   params      Array of parameters of type TEEC_Parameter.
401  * @param   session     Internal pointer to the last session used by
402  *                      TEEC_InvokeCommand with this operation.
403  *
404  */
405 typedef struct {
406 	uint32_t started;
407 	uint32_t paramTypes;
408 	TEEC_Parameter params[TEEC_CONFIG_PAYLOAD_REF_COUNT];
409 	/* Implementation-Defined */
410 	TEEC_Session *session;
411 } TEEC_Operation;
412 
413 /**
414  * TEEC_InitializeContext() - Initializes a context holding connection
415  * information on the specific TEE, designated by the name string.
416 
417  * @param name    A zero-terminated string identifying the TEE to connect to.
418  *                If name is set to NULL, the default TEE is connected to. NULL
419  *                is the only supported value in this version of the API
420  *                implementation.
421  *
422  * @param context The context structure which is to be initialized.
423  *
424  * @return TEEC_SUCCESS  The initialization was successful.
425  * @return TEEC_Result   Something failed.
426  */
427 TEEC_Result TEEC_InitializeContext(const char *name, TEEC_Context *context);
428 
429 /**
430  * TEEC_FinalizeContext() - Destroys a context holding connection information
431  * on the specific TEE.
432  *
433  * This function destroys an initialized TEE context, closing the connection
434  * between the client application and the TEE. This function must only be
435  * called when all sessions related to this TEE context have been closed and
436  * all shared memory blocks have been released.
437  *
438  * @param context       The context to be destroyed.
439  */
440 void TEEC_FinalizeContext(TEEC_Context *context);
441 
442 /**
443  * TEEC_OpenSession() - Opens a new session with the specified trusted
444  *                      application.
445  *
446  * @param context            The initialized TEE context structure in which
447  *                           scope to open the session.
448  * @param session            The session to initialize.
449  * @param destination        A structure identifying the trusted application
450  *                           with which to open a session.
451  *
452  * @param connectionMethod   The connection method to use.
453  * @param connectionData     Any data necessary to connect with the chosen
454  *                           connection method. Not supported, should be set to
455  *                           NULL.
456  * @param operation          An operation structure to use in the session. May
457  *                           be set to NULL to signify no operation structure
458  *                           needed.
459  *
460  * @param returnOrigin       A parameter which will hold the error origin if
461  *                           this function returns any value other than
462  *                           TEEC_SUCCESS.
463  *
464  * @return TEEC_SUCCESS      OpenSession successfully opened a new session.
465  * @return TEEC_Result       Something failed.
466  *
467  */
468 TEEC_Result TEEC_OpenSession(TEEC_Context *context,
469 			     TEEC_Session *session,
470 			     const TEEC_UUID *destination,
471 			     uint32_t connectionMethod,
472 			     const void *connectionData,
473 			     TEEC_Operation *operation,
474 			     uint32_t *returnOrigin);
475 
476 /**
477  * TEEC_CloseSession() - Closes the session which has been opened with the
478  * specific trusted application.
479  *
480  * @param session The opened session to close.
481  */
482 void TEEC_CloseSession(TEEC_Session *session);
483 
484 /**
485  * TEEC_InvokeCommand() - Executes a command in the specified trusted
486  * application.
487  *
488  * @param session        A handle to an open connection to the trusted
489  *                       application.
490  * @param commandID      Identifier of the command in the trusted application
491  *                       to invoke.
492  * @param operation      An operation structure to use in the invoke command.
493  *                       May be set to NULL to signify no operation structure
494  *                       needed.
495  * @param returnOrigin   A parameter which will hold the error origin if this
496  *                       function returns any value other than TEEC_SUCCESS.
497  *
498  * @return TEEC_SUCCESS  OpenSession successfully opened a new session.
499  * @return TEEC_Result   Something failed.
500  */
501 TEEC_Result TEEC_InvokeCommand(TEEC_Session *session,
502 			       uint32_t commandID,
503 			       TEEC_Operation *operation,
504 			       uint32_t *returnOrigin);
505 
506 /**
507  * TEEC_RegisterSharedMemory() - Register a block of existing memory as a
508  * shared block within the scope of the specified context.
509  *
510  * @param context    The initialized TEE context structure in which scope to
511  *                   open the session.
512  * @param sharedMem  pointer to the shared memory structure to register.
513  *
514  * @return TEEC_SUCCESS              The registration was successful.
515  * @return TEEC_ERROR_OUT_OF_MEMORY  Memory exhaustion.
516  * @return TEEC_Result               Something failed.
517  */
518 TEEC_Result TEEC_RegisterSharedMemory(TEEC_Context *context,
519 				      TEEC_SharedMemory *sharedMem);
520 
521 /**
522  * TEEC_AllocateSharedMemory() - Allocate shared memory for TEE.
523  *
524  * @param context     The initialized TEE context structure in which scope to
525  *                    open the session.
526  * @param sharedMem   Pointer to the allocated shared memory.
527  *
528  * @return TEEC_SUCCESS              The registration was successful.
529  * @return TEEC_ERROR_OUT_OF_MEMORY  Memory exhaustion.
530  * @return TEEC_Result               Something failed.
531  */
532 TEEC_Result TEEC_AllocateSharedMemory(TEEC_Context *context,
533 				      TEEC_SharedMemory *sharedMem);
534 
535 /**
536  * TEEC_ReleaseSharedMemory() - Free or deregister the shared memory.
537  *
538  * @param sharedMem  Pointer to the shared memory to be freed.
539  */
540 void TEEC_ReleaseSharedMemory(TEEC_SharedMemory *sharedMemory);
541 
542 /**
543  * TEEC_RequestCancellation() - Request the cancellation of a pending open
544  *                              session or command invocation.
545  *
546  * @param operation Pointer to an operation previously passed to open session
547  *                  or invoke.
548  */
549 void TEEC_RequestCancellation(TEEC_Operation *operation);
550 
551 #ifdef __cplusplus
552 }
553 #endif
554 
555 #endif
556