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.Threading;
20 using System.Threading.Tasks;
22 namespace Tizen.Security.TEEC
25 /// This type denotes Session Login Method used in OpenSession
27 /// <since_tizen> 3 </since_tizen>
28 public class LoginMethod
30 /// <summary>No login data is provided.</summary>
31 public const uint Public = 0x00000000;
32 /// <summary>Login data about the user running the Client Application process is provided.</summary>
33 public const uint User = 0x00000001;
34 /// <summary>Login data about the group running the Client Application process is provided.</summary>
35 public const uint Group = 0x00000002;
36 /// <summary>Login data about the running Client Application itself is provided.</summary>
37 public const uint Application = 0x00000003;
41 /// This type denotes Value parameter
43 /// <since_tizen> 3 </since_tizen>
44 public enum TEFValueType : UInt32
46 /// <summary>The Parameter is a ValueType tagged as input.</summary>
48 /// <summary>The Parameter is a ValueType tagged as output.</summary>
50 /// <summary>The Parameter is a ValueType tagged as both as input and output.</summary>
55 /// This type denotes TempMemoryReference parameter
56 /// describing a region of memory which needs to be temporarily registered for the duration of the operation.
58 /// <since_tizen> 3 </since_tizen>
59 public enum TEFTempMemoryType : UInt32
61 /// <summary>The Parameter is a TempMemoryType and is tagged as input.</summary>
63 /// <summary>Same as Input, but the Memory Reference is tagged as output.</summary>
65 /// <summary>A Temporary Memory Reference tagged as both input and output.</summary>
70 /// This type denotes SharedMemoryReference parameter
72 /// <since_tizen> 3 </since_tizen>
73 public enum TEFRegisteredMemoryType : UInt32
75 /// <summary>The Parameter is a Registered Memory Reference that refers to the entirety of its parent Shared Memory block.</summary>
77 /// <summary>A Registered Memory Reference structure that refers to a partial region of its parent Shared Memory block and is tagged as input.</summary>
78 PartialInput = 0x0000000D,
79 /// <summary>A Registered Memory Reference structure that refers to a partial region of its parent Shared Memory block and is tagged as output.</summary>
80 PartialOutput = 0x0000000E,
81 /// <summary>A Registered Memory Reference structure that refers to a partial region of its parent Shared Memory block and is tagged as both input and output.</summary>
82 PartialInOut = 0x0000000F,
86 /// This type denotes SharedMemory access direction
88 /// <since_tizen> 3 </since_tizen>
90 public enum SharedMemoryFlags : UInt32
92 /// <summary>A flag indicates Shared Memory can be read.</summary>
94 /// <summary>A flag indicates Shared Memory can be written.</summary>
96 /// <summary>A flag indicates Shared Memory can be read and written.</summary>
97 InOut = Input | Output,
101 /// This type denotes a Shared Memory block which has either been registered
102 /// with the implementation or allocated by it.
104 /// <since_tizen> 3 </since_tizen>
105 public sealed class SharedMemory
107 internal Interop.TEEC_SharedMemory shm;
108 internal SharedMemory(Interop.TEEC_SharedMemory shm)
113 /// This property represents shared memory size in bytes.
115 /// <since_tizen> 3 </since_tizen>
118 get { return shm.size; }
121 /// This property represents start address of shared memory block.
123 /// <since_tizen> 3 </since_tizen>
124 public IntPtr Address
126 get { return shm.buffer; }
130 /// This function makes a copy and is designed for convenient operations on small buffers.
131 /// For large buffers direct address should be used.
133 /// <since_tizen> 3 </since_tizen>
134 /// <param name="data">Source data buffer to copy data from</param>
135 /// <param name="dstOffs">Starting offset in destination shared memory</param>
136 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
137 public void SetData(byte[] data, int dstOffs)
139 if ((shm.flags & (uint)SharedMemoryFlags.Output) == 0) throw new InvalidOperationException("No write access");
140 //TODO copy data into shared memory starting at given offset
143 /// This function makes a copy and is designed for convenient operations on small buffers.
144 /// For large buffers direct address should be used.
146 /// <since_tizen> 3 </since_tizen>
147 /// <param name="data">Destination data buffer to copy data into</param>
148 /// <param name="srcOffs">Starting offset in source shared memory</param>
149 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
150 public void GetData(byte[] data, int srcOffs)
152 if ((shm.flags & (uint)SharedMemoryFlags.Input) == 0) throw new InvalidOperationException("No read access");
153 //TODO copy data from shared memory starting at given offset
158 /// This type defines the payload of either an open Session operation or an invoke Command operation. It is
159 /// also used for cancellation of operations, which may be desirable even if no payload is passed.
160 /// Parameters are used to exchange data between CA and TA
162 /// <since_tizen> 3 </since_tizen>
163 public abstract class Parameter
165 internal Parameter(uint t)
169 internal uint NativeType { get; }
173 /// This type defines a template for parameter types.
175 /// <since_tizen> 3 </since_tizen>
176 public abstract class BaseParameter<TEnum> : Parameter where TEnum : struct, IComparable, IFormattable, IConvertible // as close to Enum as possible
178 internal BaseParameter(TEnum t) : base((uint)(object)t)
184 /// This property represents access type to this parameter.
186 /// <since_tizen> 3 </since_tizen>
187 public TEnum Type { get; }
191 /// This type defines a temporary memory reference.
193 /// <since_tizen> 3 </since_tizen>
194 public sealed class TempMemoryReference : BaseParameter<TEFTempMemoryType>
197 /// Constructs Prameter object which holds info about temporary memory copied to/from TA
199 /// <since_tizen> 3 </since_tizen>
200 /// <param name="buffer">Address of allocated memory buffer</param>
201 /// <param name="size">Size of the buffer</param>
202 /// <param name="type">Kind of access allowed for TA <see cref="TEFTempMemoryType"/></param>
203 public TempMemoryReference(IntPtr buffer, uint size, TEFTempMemoryType type) :
206 this.Buffer = buffer;
210 /// This property represents memory address of buffer.
212 /// <since_tizen> 3 </since_tizen>
213 public IntPtr Buffer { get; }
215 /// This property represents size of buffer.
217 /// <since_tizen> 3 </since_tizen>
218 public uint Size { get; }
222 /// This type defines a memory reference that uses a pre-registered or pre-allocated Shared Memory block.
224 /// <since_tizen> 3 </since_tizen>
225 public sealed class RegisteredMemoryReference : BaseParameter<TEFRegisteredMemoryType>
228 /// Constructs Prameter object which holds info about registered memory shared with TA
230 /// <since_tizen> 3 </since_tizen>
231 /// <param name="parent">Shared memory - registered or allocated</param>
232 /// <param name="size">Size of the buffer part</param>
233 /// <param name="offset">Offset of buffer in shared memory</param>
234 /// <param name="type">Kind of access allowed for TA <see cref="TEFRegisteredMemoryType"/></param>
235 public RegisteredMemoryReference(SharedMemory parent, uint size, uint offset, TEFRegisteredMemoryType type) :
238 this.Parent = parent;
240 this.Offset = offset;
243 /// This property represents SharedMemory that is referred to.
245 /// <since_tizen> 3 </since_tizen>
246 public SharedMemory Parent { get; }
248 /// This property represents size (in bytes) of SharedMemory.
250 /// <since_tizen> 3 </since_tizen>
251 public uint Size { get; }
253 /// This property represents offset (in bytes) from the begin of SharedMemory.
255 /// <since_tizen> 3 </since_tizen>
256 public uint Offset { get; }
260 /// This type defines a parameter that is not referencing shared memory, but carries instead small raw data
263 /// <since_tizen> 3 </since_tizen>
264 public sealed class Value : BaseParameter<TEFValueType>
267 /// Constructs Prameter object which holds info about int values copied to/from TA
269 /// <since_tizen> 3 </since_tizen>
270 /// <param name="a">User paramter A</param>
271 /// <param name="b">User paramter B</param>
272 /// <param name="type">Kind of access allowed for TA <see cref="TEFValueType"/></param>
273 public Value(uint a, uint b, TEFValueType type) :
280 /// This property represents unsigned integer A.
282 /// <since_tizen> 3 </since_tizen>
283 public uint A { get; }
285 /// This property represents unsigned integer B.
287 /// <since_tizen> 3 </since_tizen>
288 public uint B { get; }
293 /// This type denotes a TEE Session, the logical container linking a Client Application with a particular Trusted Application.
295 /// <since_tizen> 3 </since_tizen>
296 public sealed class Session
298 private Interop.TEEC_Context context;
299 private Interop.TEEC_Session session;
301 internal Session(Interop.TEEC_Context context) {
302 this.context = context;
303 this.session = new Interop.TEEC_Session();
311 internal void Open(Guid destination, uint loginMethod, byte[] connectionData, Parameter[] paramlist)
313 Interop.TEEC_UUID uuid = new Interop.TEEC_UUID();
314 Interop.TEEC_Operation op = new Interop.TEEC_Operation();
317 int ret = Interop.Libteec.OpenSession(ref context, ref session, uuid, loginMethod, connectionData, ref op, out ro);
318 //MAYBE map origin of return code to specyfic Exception
319 Interop.CheckNThrowException(ret, string.Format("OpenSession('{0}')", destination));
323 /// This function closes a Session which has been opened with a Trusted Application.
324 /// All Commands within the Session MUST have completed before this function can be called.
326 /// <since_tizen> 3 </since_tizen>
327 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
328 /// <privlevel>partner</privlevel>
329 /// <feature>http://tizen.org/feature/security.tee</feature>
330 /// <exception cref="UnauthorizedAccessException">Thrown when application does not have privilege to access this method.</exception>
331 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
332 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
333 public void Close() {
334 Interop.Libteec.CloseSession(ref session);
339 /// This function invokes a Command within the specified Session.
340 /// The parameter commandID is an identifier that is used to indicate which of the exposed Trusted
341 /// Application functions should be invoked. The supported command identifier values are defined by the
342 /// Trusted Application's protocol.
343 /// There can be up to four Parameter objects given in the <paramref name="paramlist"/> array
345 /// <since_tizen> 3 </since_tizen>
346 /// <param name="commandID">The command</param>
347 /// <param name="paramlist">The array of parameters</param>
348 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
349 /// <privlevel>partner</privlevel>
350 /// <feature>http://tizen.org/feature/security.tee</feature>
351 /// <exception cref="UnauthorizedAccessException">Thrown when application does not have privilege to access this method.</exception>
352 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
353 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
354 /// <exception cref="ArgumentException">The argument <paramref name="paramlist"/> is wrong</exception>
355 public void InvokeCommand(uint commandID, Parameter[] paramlist)
357 Interop.TEEC_Operation op = new Interop.TEEC_Operation();
361 for (int i=0; i < 4; ++i) {
362 Parameter p = paramlist[i];
363 //TODO fill TEEC_Operation struct
367 int ret = Interop.Libteec.InvokeCommand(ref session, commandID, ref op, out ro);
368 //MAYBE map origin of return code to specific Exception
369 Interop.CheckNThrowException(ret, string.Format("InvokeCommand({0})", commandID));
373 /// Asynchronous version of InvokeCommand
375 /// <since_tizen> 3 </since_tizen>
376 /// <param name="commandID">The command</param>
377 /// <param name="paramlist">The array of parameters</param>
378 /// <param name="token">The token for task manipulation</param>
379 /// <returns>Returns Task executing invoke command in backgroung</returns>
380 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
381 /// <privlevel>partner</privlevel>
382 /// <feature>http://tizen.org/feature/security.tee</feature>
383 /// <exception cref="UnauthorizedAccessException">Thrown when application does not have privilege to access this method.</exception>
384 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
385 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
386 /// <exception cref="ArgumentException">One of arguments is wrong</exception>
387 public async Task InvokeCommandAsync(uint commandID, Parameter[] paramlist, CancellationToken token = default(CancellationToken))
389 await Task.Factory.StartNew(() => InvokeCommand(commandID, paramlist));
395 /// This type denotes a TEE Context, the main logical container linking a Client Application with a particular TEE.
397 /// <since_tizen> 3 </since_tizen>
398 public sealed class Context : IDisposable
400 private Interop.TEEC_Context context;
403 /// This function (constructor) initializes a new TEE Context, forming a connection between this Client Application and the
404 /// TEE identified by the string identifier name (empty or null name denotes default TEE).
406 /// <since_tizen> 3 </since_tizen>
407 /// <param name="name">The TEE name</param>
408 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
409 /// <privlevel>partner</privlevel>
410 /// <feature>http://tizen.org/feature/security.tee</feature>
411 /// <exception cref="UnauthorizedAccessException">Thrown when application does not have privilege to access this method.</exception>
412 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
413 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
414 public Context(string name)
416 context = new Interop.TEEC_Context();
417 int ret = Interop.Libteec.InitializeContext(name, ref context);
418 Interop.CheckNThrowException(ret, string.Format("InititalizeContext('{0}')", name));
427 /// This function implements IDisposable interface
429 /// <since_tizen> 3 </since_tizen>
430 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
431 /// <privlevel>partner</privlevel>
432 /// <feature>http://tizen.org/feature/security.tee</feature>
433 public void Dispose() {
434 Interop.Libteec.FinalizeContext(ref context);
435 //context.imp = null;
439 /// This function opens a new Session between the Client Application and the specified Trusted Application.
440 /// The target Trusted Application is identified by a UUID passed in the parameter destination.
441 /// There can be up to four Parameter objects given in the <paramref name="paramlist"/> array
443 /// <since_tizen> 3 </since_tizen>
444 /// <param name="destination">The UUID of destination TA</param>
445 /// <param name="loginMethod">The authentication algorithm <see cref="LoginMethod" /></param>
446 /// <param name="connectionData">The data to be verified by given login method</param>
447 /// <param name="paramlist">The parameters to be passed to TA open-session-callback</param>
448 /// <returns>Returns opened session</returns>
449 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
450 /// <privlevel>partner</privlevel>
451 /// <feature>http://tizen.org/feature/security.tee</feature>
452 /// <exception cref="UnauthorizedAccessException">Thrown when application does not have privilege to access this method.</exception>
453 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
454 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
455 /// <exception cref="ArgumentException">One of arguments is wrong</exception>
456 public Session OpenSession(Guid destination, uint loginMethod, byte[] connectionData, Parameter[] paramlist)
458 Session ses = new Session(context);
459 ses.Open(destination, loginMethod, connectionData, paramlist);
463 /// @see OpenSession(Guid destination, uint connectionMethod, byte[] connectionData, Parameter[] paramlist, CancellationToken token)
465 /// <since_tizen> 3 </since_tizen>
466 /// <param name="destination">The UUID of destination TA</param>
467 /// <returns>Returns opened session</returns>
468 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
469 /// <privlevel>partner</privlevel>
470 /// <feature>http://tizen.org/feature/security.tee</feature>
471 /// <exception cref="UnauthorizedAccessException">Thrown when application does not have privilege to access this method.</exception>
472 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
473 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
474 public Session OpenSession(Guid destination)
476 Session ses = new Session(context);
477 ses.Open(destination, LoginMethod.Public, null, null);
482 /// Asynchronous version of OpenSession
483 /// @see OpenSession(Guid destination, uint connectionMethod, byte[] connectionData, Parameter[] paramlist, CancellationToken token)
485 /// <since_tizen> 3 </since_tizen>
486 /// <param name="destination">The UUID of destination TA</param>
487 /// <param name="loginMethod">The authentication algorithm <see cref="LoginMethod" /></param>
488 /// <param name="connectionData">The data to be verified by given login method</param>
489 /// <param name="paramlist">The parameters to be passed to TA open-session-callback</param>
490 /// <param name="token">The token for task manipulation</param>
491 /// <returns>Returns Task executing session open in backgroung</returns>
492 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
493 /// <privlevel>partner</privlevel>
494 /// <feature>http://tizen.org/feature/security.tee</feature>
495 /// <exception cref="UnauthorizedAccessException">Thrown when application does not have privilege to access this method.</exception>
496 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
497 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
498 /// <exception cref="ArgumentException">One of arguments is wrong</exception>
499 public async Task<Session> OpenSessionAsync(Guid destination, uint loginMethod, byte[] connectionData, Parameter[] paramlist, CancellationToken token = default(CancellationToken))
501 Task<Session> task = Task<Session>.Factory.StartNew(() =>
503 return OpenSession(destination, loginMethod, connectionData, paramlist);
508 /// Asynchronous version of OpenSession
509 /// @see OpenSession(Guid destination, uint connectionMethod, byte[] connectionData, Parameter[] paramlist, CancellationToken token)
511 /// <since_tizen> 3 </since_tizen>
512 /// <param name="destination">The UUID of destination TA</param>
513 /// <param name="token">The token for task manipulation</param>
514 /// <returns>Returns Task executing session open in backgroung</returns>
515 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
516 /// <privlevel>partner</privlevel>
517 /// <feature>http://tizen.org/feature/security.tee</feature>
518 /// <exception cref="UnauthorizedAccessException">Thrown when application does not have privilege to access this method.</exception>
519 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
520 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
521 public async Task<Session> OpenSessionAsync(Guid destination, CancellationToken token = default(CancellationToken))
523 Task<Session> task = Task<Session>.Factory.StartNew(() =>
525 return OpenSession(destination);
531 /// This function registers a block of existing Client Application memory as a block of Shared Memory within
532 /// the scope of the specified Context, in accordance with the parameters.
533 /// The input <paramref name="memaddr"/> MUST point to the shared memory region to register
535 /// <since_tizen> 3 </since_tizen>
536 /// <param name="memaddr">The address of shared memory</param>
537 /// <param name="size">The size of shared memory</param>
538 /// <param name="flags">The flags describing access modes (Input and/or Output)</param>
539 /// <returns>Returns SharedMemory handler</returns>
540 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
541 /// <privlevel>partner</privlevel>
542 /// <feature>http://tizen.org/feature/security.tee</feature>
543 /// <exception cref="UnauthorizedAccessException">Thrown when application does not have privilege to access this method.</exception>
544 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
545 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
546 /// <exception cref="ArgumentException">The argument <paramref name="memaddr"/> is wrong</exception>
547 public SharedMemory RegisterSharedMemory(IntPtr memaddr, UInt32 size, SharedMemoryFlags flags)
549 Interop.TEEC_SharedMemory shm = new Interop.TEEC_SharedMemory();
550 shm.buffer = memaddr;
552 shm.flags = (UInt32)flags;
553 int ret = Interop.Libteec.RegisterSharedMemory(ref context, ref shm);
554 Interop.CheckNThrowException(ret, "RegisterSharedMemory");
555 return new SharedMemory(shm);
559 /// This function allocates a new block of memory as a block of Shared Memory within the scope of the
560 /// specified Context, in accordance with the parameters.
562 /// <since_tizen> 3 </since_tizen>
563 /// <param name="size">The size of shared memory</param>
564 /// <param name="flags">The flags describing access modes (Input and/or Output)</param>
565 /// <returns>Returns SharedMemory handler</returns>
566 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
567 /// <privlevel>partner</privlevel>
568 /// <feature>http://tizen.org/feature/security.tee</feature>
569 /// <exception cref="UnauthorizedAccessException">Thrown when application does not have privilege to access this method.</exception>
570 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
571 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
572 public SharedMemory AllocateSharedMemory(UInt32 size, SharedMemoryFlags flags)
574 Interop.TEEC_SharedMemory shm = new Interop.TEEC_SharedMemory();
576 shm.flags = (UInt32)flags;
577 int ret = Interop.Libteec.AllocateSharedMemory(ref context, ref shm);
578 Interop.CheckNThrowException(ret, "AllocateSharedMemory");
579 return new SharedMemory(shm);
583 /// This function deregisters or deallocates a previously initialized block of Shared Memory.
586 /// For a memory buffer allocated using AllocateSharedMemory the Implementation MUST free the
587 /// underlying memory and the Client Application MUST NOT access this region after this function has been
588 /// called. In this case the Implementation MUST clear the buffer and size fields of the sharedMem
589 /// structure before returning.
590 /// For memory registered using RegisterSharedMemory the implementation MUST deregister the
591 /// underlying memory from the TEE, but the memory region will stay available to the Client Application for
592 /// other purposes as the memory is owned by it.
594 /// <since_tizen> 3 </since_tizen>
595 /// <param name="shm">The shared memory object returned by RegisterSharedMemory or AllocateSharedMemory</param>
596 /// <privilege>http://tizen.org/privilege/tee.client</privilege>
597 /// <privlevel>partner</privlevel>
598 /// <feature>http://tizen.org/feature/security.tee</feature>
599 /// <exception cref="UnauthorizedAccessException">Thrown when application does not have privilege to access this method.</exception>
600 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
601 /// <exception cref="InvalidOperationException">The operation is invalid.</exception>
602 /// <exception cref="ArgumentException">The argument is wrong</exception>
603 public void ReleaseSharedMemory(SharedMemory shm)
605 Interop.Libteec.ReleaseSharedMemory(ref shm.shm);