2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
18 using System.Collections.Generic;
19 using System.Runtime.InteropServices;
20 using System.Threading;
21 using System.Threading.Tasks;
23 namespace Tizen.Security.TEEC
26 /// This type denotes the Session Login Method used in OpenSession.
28 /// <since_tizen> 3 </since_tizen>
29 public class LoginMethod
31 /// <summary>No login data is provided.</summary>
32 public const uint Public = 0x00000000;
33 /// <summary>Login data about the user running the client application process is provided.</summary>
34 public const uint User = 0x00000001;
35 /// <summary>Login data about the group running the client application process is provided.</summary>
36 public const uint Group = 0x00000002;
37 /// <summary>Login data about the running client application itself is provided.</summary>
38 public const uint Application = 0x00000003;
42 /// This type denotes the Value parameter.
44 /// <since_tizen> 3 </since_tizen>
45 public enum TEFValueType : UInt32
47 /// <summary>The parameter is a ValueType tagged as the input.</summary>
49 /// <summary>The parameter is a ValueType tagged as the output.</summary>
51 /// <summary>The parameter is a ValueType tagged as both the input and the output.</summary>
56 /// This type denotes the TempMemoryReference parameter
57 /// describing a region of memory which needs to be temporarily registered for the duration of the operation.
59 /// <since_tizen> 3 </since_tizen>
60 public enum TEFTempMemoryType : UInt32
62 /// <summary>The parameter is a TempMemoryType and is tagged as the input.</summary>
64 /// <summary>Same as the input, but the Memory Reference is tagged as the output.</summary>
66 /// <summary>A Temporary Memory Reference tagged as both the input and the output.</summary>
71 /// This type denotes the SharedMemoryReference parameter.
73 /// <since_tizen> 3 </since_tizen>
74 public enum TEFRegisteredMemoryType : UInt32
76 /// <summary>The parameter is a registered memory reference that refers to the entirety of its parent shared memory block.</summary>
78 /// <summary>A registered memory reference structure that refers to a partial region of its parent shared mMemory block and is tagged as the input.</summary>
79 PartialInput = 0x0000000D,
80 /// <summary>A registered memory reference structure that refers to a partial region of its parent shared memory block and is tagged as the output.</summary>
81 PartialOutput = 0x0000000E,
82 /// <summary>A registered memory reference structure that refers to a partial region of its parent shared memory block and is tagged as both the input and the output.</summary>
83 PartialInOut = 0x0000000F,
87 /// This type denotes the SharedMemory access direction.
89 /// <since_tizen> 3 </since_tizen>
91 public enum SharedMemoryFlags : UInt32
93 /// <summary>A flag indicates the shared memory can be read.</summary>
95 /// <summary>A flag indicates the shared memory can be written.</summary>
97 /// <summary>A flag indicates the shared memory can be read and written.</summary>
98 InOut = Input | Output,
102 /// This type denotes a shared memory block which has been either registered
103 /// with the implementation or allocated by it.
105 /// <since_tizen> 3 </since_tizen>
106 public sealed class SharedMemory
108 internal Interop.TEEC_SharedMemory shm;
109 internal SharedMemory(Interop.TEEC_SharedMemory shm)
114 /// This property represents the shared memory size in bytes.
116 /// <since_tizen> 3 </since_tizen>
119 get { return shm.size; }
122 /// This property represents the start address of the shared memory block.
124 /// <since_tizen> 3 </since_tizen>
125 public IntPtr Address
127 get { return shm.buffer; }
131 /// This function makes a copy and is designed for convenient operations on small buffers.
132 /// For large buffers, the direct address should be used.
134 /// <since_tizen> 3 </since_tizen>
135 /// <param name="data">The source data buffer to copy data from.</param>
136 /// <param name="dstOffs">The starting offset in the destination shared memory.</param>
137 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
138 public void SetData(byte[] data, int dstOffs)
140 if ((shm.flags & (uint)SharedMemoryFlags.Output) == 0) throw new InvalidOperationException("No write access");
141 Marshal.Copy(data, 0, shm.buffer + dstOffs, data.Length);
144 /// This function makes a copy and is designed for convenient operations on small buffers.
145 /// For large buffers, the direct address should be used.
147 /// <since_tizen> 3 </since_tizen>
148 /// <param name="data">The destination data buffer to copy data into.</param>
149 /// <param name="srcOffs">The starting offset in the source shared memory.</param>
150 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
151 public void GetData(byte[] data, int srcOffs)
153 if ((shm.flags & (uint)SharedMemoryFlags.Input) == 0) throw new InvalidOperationException("No read access");
154 Marshal.Copy(shm.buffer + srcOffs, data, 0, data.Length);
159 /// This type defines the payload of either an open session operation or an invoke command operation. It is
160 /// also used for cancelation of operations, which may be desirable even if no payload is passed.
161 /// Parameters are used to exchange data between CA and TA.
163 /// <since_tizen> 3 </since_tizen>
164 public abstract class Parameter
166 internal Parameter(uint t)
170 internal uint NativeType { get; }
174 /// This type defines a template for the parameter types.
176 /// <since_tizen> 3 </since_tizen>
177 public abstract class BaseParameter<TEnum> : Parameter where TEnum : struct, IComparable, IFormattable, IConvertible // as close to Enum as possible
179 internal BaseParameter(TEnum t) : base((uint)(object)t)
185 /// This property represents the access type to this parameter.
187 /// <since_tizen> 3 </since_tizen>
188 public TEnum Type { get; }
192 /// This type defines a temporary memory reference.
194 /// <since_tizen> 3 </since_tizen>
195 public sealed class TempMemoryReference : BaseParameter<TEFTempMemoryType>
198 /// Constructs a parameter object which holds information about the temporary memory copied to or from TA.
200 /// <since_tizen> 3 </since_tizen>
201 /// <param name="buffer">The address of the allocated memory buffer.</param>
202 /// <param name="size">The size of the buffer.</param>
203 /// <param name="type">The kind of access allowed for TA <see cref="TEFTempMemoryType"/>.</param>
204 public TempMemoryReference(IntPtr buffer, uint size, TEFTempMemoryType type) :
207 this.Buffer = buffer;
211 /// This property represents the memory address of the buffer.
213 /// <since_tizen> 3 </since_tizen>
214 public IntPtr Buffer { get; }
216 /// This property represents the size of the buffer.
218 /// <since_tizen> 3 </since_tizen>
219 public uint Size { get; }
223 /// This type defines a memory reference that uses a pre-registered or pre-allocated shared memory block.
225 /// <since_tizen> 3 </since_tizen>
226 public sealed class RegisteredMemoryReference : BaseParameter<TEFRegisteredMemoryType>
229 /// Constructs a parameter object which holds information about the registered memory shared with TA.
231 /// <since_tizen> 3 </since_tizen>
232 /// <param name="parent">The shared memory - registered or allocated.</param>
233 /// <param name="size">The size of the buffer part.</param>
234 /// <param name="offset">The offset of the buffer in the shared memory.</param>
235 /// <param name="type">The kind of access allowed for TA <see cref="TEFRegisteredMemoryType"/>.</param>
236 public RegisteredMemoryReference(SharedMemory parent, uint size, uint offset, TEFRegisteredMemoryType type) :
239 this.Parent = parent;
241 this.Offset = offset;
244 /// This property represents the shared memory that is referred to.
246 /// <since_tizen> 3 </since_tizen>
247 public SharedMemory Parent { get; }
249 /// This property represents the size (in bytes) of the shared memory.
251 /// <since_tizen> 3 </since_tizen>
252 public uint Size { get; }
254 /// This property represents the offset (in bytes) from the start of the shared memory.
256 /// <since_tizen> 3 </since_tizen>
257 public uint Offset { get; }
261 /// This type defines a parameter that is not referencing the shared memory, but carries instead small raw data
262 /// passed by a value.
264 /// <since_tizen> 3 </since_tizen>
265 public sealed class Value : BaseParameter<TEFValueType>
268 /// Constructs a parameter object which holds information about integer values copied to or from TA.
270 /// <since_tizen> 3 </since_tizen>
271 /// <param name="a">User paramter A.</param>
272 /// <param name="b">User paramter B.</param>
273 /// <param name="type">The kind of access allowed for TA <see cref="TEFValueType"/>.</param>
274 public Value(uint a, uint b, TEFValueType type) :
281 /// This property represents an unsigned integer A.
283 /// <since_tizen> 3 </since_tizen>
284 public uint A { get; }
286 /// This property represents an unsigned integer B.
288 /// <since_tizen> 3 </since_tizen>
289 public uint B { get; }
294 /// This type denotes a TEE Session, the logical container linking a client application with a particular trusted application.
296 /// <since_tizen> 3 </since_tizen>
297 public sealed class Session
299 private Interop.TEEC_Context context;
300 private Interop.TEEC_Session session;
302 internal Session(Interop.TEEC_Context context) {
303 this.context = context;
304 this.session = new Interop.TEEC_Session();
312 internal void Open(Guid destination, uint loginMethod, byte[] connectionData, Parameter[] paramlist)
314 Interop.TEEC_UUID uuid = Interop.TEEC_UUID.ToTeecUuid(destination);
315 Interop.TEEC_Operation op = new Interop.TEEC_Operation();
318 int ret = Interop.Libteec.OpenSession(ref context, ref session, ref uuid, loginMethod, connectionData, ref op, out ro);
319 //MAYBE map origin of return code to specyfic Exception
320 Interop.CheckNThrowException(ret, string.Format("OpenSession('{0}')", destination));
324 /// This function closes a session which has been opened with a trusted application.
325 /// All commands within the session must be completed before this function can be called.
327 /// <since_tizen> 3 </since_tizen>
328 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
329 /// <privlevel>partner</privlevel>
330 /// <feature>http://tizen.org/feature/security.tee</feature>
331 /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have the privilege to access this method.</exception>
332 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
333 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
334 public void Close() {
335 Interop.Libteec.CloseSession(ref session);
340 /// This function invokes a command within the specified session.
341 /// The parameter commandID is an identifier that is used to indicate which of the exposed trusted
342 /// application functions should be invoked. The supported command identifier values are defined by the
343 /// trusted application's protocol.
344 /// There can be up to four parameter objects given in the <paramref name="paramlist"/> array.
346 /// <since_tizen> 3 </since_tizen>
347 /// <param name="commandID">The command.</param>
348 /// <param name="paramlist">The array of parameters.</param>
349 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
350 /// <privlevel>partner</privlevel>
351 /// <feature>http://tizen.org/feature/security.tee</feature>
352 /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have the privilege to access this method.</exception>
353 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
354 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
355 /// <exception cref="ArgumentException">The argument <paramref name="paramlist"/> is wrong.</exception>
356 public void InvokeCommand(uint commandID, Parameter[] paramlist)
358 Interop.TEEC_Operation op = new Interop.TEEC_Operation();
362 for (int i=0; i < 4; ++i) {
363 Parameter p = paramlist[i];
364 //TODO fill TEEC_Operation struct
368 int ret = Interop.Libteec.InvokeCommand(ref session, commandID, ref op, out ro);
369 //MAYBE map origin of return code to specific Exception
370 Interop.CheckNThrowException(ret, string.Format("InvokeCommand({0})", commandID));
374 /// The asynchronous version of the InvokeCommand.
376 /// <since_tizen> 3 </since_tizen>
377 /// <param name="commandID">The command.</param>
378 /// <param name="paramlist">The array of parameters.</param>
379 /// <param name="token">The token for task manipulation.</param>
380 /// <returns>Returns a task executing an invoke command in the background.</returns>
381 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
382 /// <privlevel>partner</privlevel>
383 /// <feature>http://tizen.org/feature/security.tee</feature>
384 /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have the privilege to access this method.</exception>
385 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
386 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
387 /// <exception cref="ArgumentException">One of the arguments is wrong.</exception>
388 public async Task InvokeCommandAsync(uint commandID, Parameter[] paramlist, CancellationToken token = default(CancellationToken))
390 await Task.Factory.StartNew(() => InvokeCommand(commandID, paramlist));
396 /// This type denotes a TEE Context, the main logical container linking a Client Application with a particular TEE.
398 /// <since_tizen> 3 </since_tizen>
399 public sealed class Context : IDisposable
401 private Interop.TEEC_Context context;
404 /// This function (constructor) initializes a new TEE Context, forming a connection between this client application and the
405 /// TEE identified by the string identifier name (empty or null name denotes a default TEE).
407 /// <since_tizen> 3 </since_tizen>
408 /// <param name="name">The TEE name.</param>
409 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
410 /// <privlevel>partner</privlevel>
411 /// <feature>http://tizen.org/feature/security.tee</feature>
412 /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have the privilege to access this method.</exception>
413 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
414 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
415 public Context(string name)
417 context = new Interop.TEEC_Context();
418 if (name != null && name.Length == 0)
420 int ret = Interop.Libteec.InitializeContext(name, ref context);
421 Interop.CheckNThrowException(ret, string.Format("InititalizeContext('{0}')", name));
430 /// This function implements the IDisposable interface.
432 /// <since_tizen> 3 </since_tizen>
433 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
434 /// <privlevel>partner</privlevel>
435 /// <feature>http://tizen.org/feature/security.tee</feature>
436 public void Dispose() {
437 Interop.Libteec.FinalizeContext(ref context);
438 //context.imp = null;
442 /// This function opens a new session between the client application and the specified trusted application.
443 /// The target trusted application is identified by an UUID passed in the parameter destination.
444 /// There can be up to four parameter objects given in the <paramref name="paramlist"/> array.
446 /// <since_tizen> 3 </since_tizen>
447 /// <param name="destination">The UUID of the destination TA.</param>
448 /// <param name="loginMethod">The authentication algorithm <see cref="LoginMethod" />.</param>
449 /// <param name="connectionData">The data to be verified by a given login method.</param>
450 /// <param name="paramlist">The parameters to be passed to TA open-session-callback.</param>
451 /// <returns>Returns opened session.</returns>
452 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
453 /// <privlevel>partner</privlevel>
454 /// <feature>http://tizen.org/feature/security.tee</feature>
455 /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have the privilege to access this method.</exception>
456 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
457 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
458 /// <exception cref="ArgumentException">One of the arguments is wrong.</exception>
459 public Session OpenSession(Guid destination, uint loginMethod, byte[] connectionData, Parameter[] paramlist)
461 Session ses = new Session(context);
462 ses.Open(destination, loginMethod, connectionData, paramlist);
466 /// @see OpenSession (Guid destination, uint connectionMethod, byte[] connectionData, Parameter[] paramlist, CancellationToken token).
468 /// <since_tizen> 3 </since_tizen>
469 /// <param name="destination">The UUID of the destination TA.</param>
470 /// <returns>Returns opened session.</returns>
471 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
472 /// <privlevel>partner</privlevel>
473 /// <feature>http://tizen.org/feature/security.tee</feature>
474 /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have the privilege to access this method.</exception>
475 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
476 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
477 public Session OpenSession(Guid destination)
479 Session ses = new Session(context);
480 ses.Open(destination, LoginMethod.Public, null, null);
485 /// The asynchronous version of the OpenSession.
486 /// @see OpenSession (Guid destination, uint connectionMethod, byte[] connectionData, Parameter[] paramlist, CancellationToken token).
488 /// <since_tizen> 3 </since_tizen>
489 /// <param name="destination">The UUID of the destination TA.</param>
490 /// <param name="loginMethod">The authentication algorithm <see cref="LoginMethod" />.</param>
491 /// <param name="connectionData">The data to be verified by a given login method.</param>
492 /// <param name="paramlist">The parameters to be passed to the TA open-session-callback.</param>
493 /// <param name="token">The token for the task manipulation.</param>
494 /// <returns>Returns a Task executing the session open in the background.</returns>
495 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
496 /// <privlevel>partner</privlevel>
497 /// <feature>http://tizen.org/feature/security.tee</feature>
498 /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have the privilege to access this method.</exception>
499 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
500 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
501 /// <exception cref="ArgumentException">One of the arguments is wrong.</exception>
502 public async Task<Session> OpenSessionAsync(Guid destination, uint loginMethod, byte[] connectionData, Parameter[] paramlist, CancellationToken token = default(CancellationToken))
504 Task<Session> task = Task<Session>.Factory.StartNew(() =>
506 return OpenSession(destination, loginMethod, connectionData, paramlist);
511 /// The asynchronous version of the OpenSession.
512 /// @see OpenSession (Guid destination, uint connectionMethod, byte[] connectionData, Parameter[] paramlist, CancellationToken token).
514 /// <since_tizen> 3 </since_tizen>
515 /// <param name="destination">The UUID of the destination TA.</param>
516 /// <param name="token">The token for a task manipulation.</param>
517 /// <returns>Returns a task executing session open in the background.</returns>
518 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
519 /// <privlevel>partner</privlevel>
520 /// <feature>http://tizen.org/feature/security.tee</feature>
521 /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have the privilege to access this method.</exception>
522 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
523 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
524 public async Task<Session> OpenSessionAsync(Guid destination, CancellationToken token = default(CancellationToken))
526 Task<Session> task = Task<Session>.Factory.StartNew(() =>
528 return OpenSession(destination);
534 /// This function registers a block of the existing client application memory as a block of shared memory within
535 /// the scope of the specified context, in accordance with the parameters.
536 /// The input <paramref name="memaddr"/> must point to the shared memory region to register.
538 /// <since_tizen> 3 </since_tizen>
539 /// <param name="memaddr">The address of the shared memory.</param>
540 /// <param name="size">The size of the shared memory.</param>
541 /// <param name="flags">The flags describing the access modes (Input and/or Output).</param>
542 /// <returns>Returns the SharedMemory handler.</returns>
543 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
544 /// <privlevel>partner</privlevel>
545 /// <feature>http://tizen.org/feature/security.tee</feature>
546 /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have the privilege to access this method.</exception>
547 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
548 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
549 /// <exception cref="ArgumentException">The argument <paramref name="memaddr"/> is wrong.</exception>
550 public SharedMemory RegisterSharedMemory(IntPtr memaddr, UInt32 size, SharedMemoryFlags flags)
552 Interop.TEEC_SharedMemory shm = new Interop.TEEC_SharedMemory();
553 shm.buffer = memaddr;
555 shm.flags = (UInt32)flags;
556 int ret = Interop.Libteec.RegisterSharedMemory(ref context, ref shm);
557 Interop.CheckNThrowException(ret, "RegisterSharedMemory");
558 return new SharedMemory(shm);
562 /// This function allocates a new block of memory as a block of shared memory within the scope of the
563 /// specified context, in accordance with the parameters.
565 /// <since_tizen> 3 </since_tizen>
566 /// <param name="size">The size of shared memory.</param>
567 /// <param name="flags">The flags describing access modes (Input and/or Output).</param>
568 /// <returns>Returns the Shared Memory handler.</returns>
569 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
570 /// <privlevel>partner</privlevel>
571 /// <feature>http://tizen.org/feature/security.tee</feature>
572 /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have the privilege to access this method.</exception>
573 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
574 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
575 public SharedMemory AllocateSharedMemory(UInt32 size, SharedMemoryFlags flags)
577 Interop.TEEC_SharedMemory shm = new Interop.TEEC_SharedMemory();
579 shm.flags = (UInt32)flags;
580 int ret = Interop.Libteec.AllocateSharedMemory(ref context, ref shm);
581 Interop.CheckNThrowException(ret, "AllocateSharedMemory");
582 return new SharedMemory(shm);
586 /// This function deregisters or deallocates a previously initialized block of the shared memory.
589 /// For a memory buffer allocated using AllocateSharedMemory, the implementation must free the
590 /// underlying memory and the client application must not access this region after this function has been
591 /// called. In this case, the implementation must clear the buffer and size fields of the shared memory
592 /// structure before returning.
593 /// For memory registered using RegisterSharedMemory, the implementation must deregister the
594 /// underlying memory from the TEE, but the memory region will stay available to the client application for
595 /// other purposes as the memory is owned by it.
597 /// <since_tizen> 3 </since_tizen>
598 /// <param name="shm">The shared memory object returned by RegisterSharedMemory or AllocateSharedMemory.</param>
599 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
600 /// <privlevel>partner</privlevel>
601 /// <feature>http://tizen.org/feature/security.tee</feature>
602 /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have the privilege to access this method.</exception>
603 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
604 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
605 /// <exception cref="ArgumentException">The argument is wrong.</exception>
606 public void ReleaseSharedMemory(SharedMemory shm)
608 Interop.Libteec.ReleaseSharedMemory(ref shm.shm);