m4sterchain commented on code in PR #178: URL: https://github.com/apache/incubator-teaclave-trustzone-sdk/pull/178#discussion_r2033022953
########## examples/inter_ta-rs/ta/src/main.rs: ########## @@ -0,0 +1,126 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#![no_std] +#![no_main] + +use optee_utee::{ + ta_close_session, ta_create, ta_destroy, ta_invoke_command, ta_open_session, trace_println, +}; +use optee_utee::{Error, ErrorKind, Parameters, Result, Uuid}; +use optee_utee::{ParamIndex, TaSession, TeeParams}; +use proto::{ + Command, HelloWorldTaCommand, SystemPtaCommand, HELLO_WORLD_USER_TA_UUID, SYSTEM_PTA_UUID, +}; + +#[ta_create] +fn create() -> Result<()> { + trace_println!("[+] TA create"); + Ok(()) +} + +#[ta_open_session] +fn open_session(_params: &mut Parameters) -> Result<()> { + trace_println!("[+] TA open session"); + Ok(()) +} + +#[ta_close_session] +fn close_session() { + trace_println!("[+] TA close session"); +} + +#[ta_destroy] +fn destroy() { + trace_println!("[+] TA destroy"); +} + +fn test_invoke_system_pta() -> Result<()> { + let system_pta_uuid = + Uuid::parse_str(SYSTEM_PTA_UUID).map_err(|_| Error::from(ErrorKind::BadParameters))?; + let mut session = TaSession::new(system_pta_uuid).open()?; + trace_println!("[+] TA open PTA session success"); + + let input: [u8; 32] = [0; 32]; + let mut output: [u8; 32] = [0; 32]; + + let mut params = TeeParams::new() + .with_memref_in(ParamIndex::Arg0, &input) + .with_memref_out(ParamIndex::Arg1, &mut output); + + session.invoke_command(SystemPtaCommand::DeriveTaUniqueKey as u32, &mut params)?; + + if let Some(written_slice) = params[ParamIndex::Arg1].written_slice() { Review Comment: For demonstrations of using the inout `written_slice`, this might be further improved by converting the option to Result using `.ok_or()?` or anyhow::context, to avoid nested if/else {return Err} pattern. ########## examples/inter_ta-rs/ta/src/main.rs: ########## @@ -0,0 +1,126 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#![no_std] +#![no_main] + +use optee_utee::{ + ta_close_session, ta_create, ta_destroy, ta_invoke_command, ta_open_session, trace_println, +}; +use optee_utee::{Error, ErrorKind, Parameters, Result, Uuid}; +use optee_utee::{ParamIndex, TaSession, TeeParams}; +use proto::{ + Command, HelloWorldTaCommand, SystemPtaCommand, HELLO_WORLD_USER_TA_UUID, SYSTEM_PTA_UUID, +}; + +#[ta_create] +fn create() -> Result<()> { + trace_println!("[+] TA create"); + Ok(()) +} + +#[ta_open_session] +fn open_session(_params: &mut Parameters) -> Result<()> { + trace_println!("[+] TA open session"); + Ok(()) +} + +#[ta_close_session] +fn close_session() { + trace_println!("[+] TA close session"); +} + +#[ta_destroy] +fn destroy() { + trace_println!("[+] TA destroy"); +} + +fn test_invoke_system_pta() -> Result<()> { + let system_pta_uuid = + Uuid::parse_str(SYSTEM_PTA_UUID).map_err(|_| Error::from(ErrorKind::BadParameters))?; + let mut session = TaSession::new(system_pta_uuid).open()?; + trace_println!("[+] TA open PTA session success"); + + let input: [u8; 32] = [0; 32]; + let mut output: [u8; 32] = [0; 32]; + + let mut params = TeeParams::new() + .with_memref_in(ParamIndex::Arg0, &input) + .with_memref_out(ParamIndex::Arg1, &mut output); + + session.invoke_command(SystemPtaCommand::DeriveTaUniqueKey as u32, &mut params)?; + + if let Some(written_slice) = params[ParamIndex::Arg1].written_slice() { + trace_println!("[+] TA invoke PTA command, output: {:?}", written_slice); + if written_slice.len() != 32 { + return Err(Error::new(ErrorKind::Generic)); + } + // check if it's same as the output + if written_slice.iter().all(|&x| x == 0) { Review Comment: According to the comment, it seems that the written_slice should be checked against output. But I don't think that is allowed as output is still mut borrowed by params[Arg1]. So maybe we can just change the comment to ensure the written_slice contains updated content, which are not all zeros. ########## optee-utee/src/tee_parameter.rs: ########## @@ -0,0 +1,302 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::ParamType; +use core::ops::{Index, IndexMut}; +use optee_utee_sys as raw; + +#[derive(Copy, Clone, Debug)] +pub enum ParamIndex { + Arg0, + Arg1, + Arg2, + Arg3, +} + +impl ParamIndex { + fn to_usize(self) -> usize { + match self { + ParamIndex::Arg0 => 0, + ParamIndex::Arg1 => 1, + ParamIndex::Arg2 => 2, + ParamIndex::Arg3 => 3, + } + } +} + +enum ParamContent<'a> { + None, + MemrefInput { + buffer: &'a [u8], + }, + MemrefOutput { + buffer: &'a mut [u8], + written: usize, + }, + MemrefInout { + buffer: &'a mut [u8], + written: usize, + }, + ValueInput { + a: u32, + b: u32, + }, + ValueOutput { + a: u32, + b: u32, + }, + ValueInout { + a: u32, + b: u32, + }, +} + +pub struct Param<'a> { + content: ParamContent<'a>, +} + +impl<'a> Param<'a> { + fn new() -> Self { + Self { + content: ParamContent::None, + } + } + + pub fn written_slice(&self) -> Option<&[u8]> { + match &self.content { + ParamContent::MemrefOutput { buffer, written } => Some(&buffer[..*written]), + ParamContent::MemrefInout { buffer, written } => Some(&buffer[..*written]), + _ => None, + } + } + + pub fn output_value(&self) -> Option<(u32, u32)> { + match &self.content { + ParamContent::ValueOutput { a, b } => Some((*a, *b)), + ParamContent::ValueInout { a, b } => Some((*a, *b)), + _ => None, + } + } + + fn get_type(&self) -> ParamType { + match &self.content { + ParamContent::None => ParamType::None, + ParamContent::MemrefInput { .. } => ParamType::MemrefInput, + ParamContent::MemrefOutput { .. } => ParamType::MemrefOutput, + ParamContent::MemrefInout { .. } => ParamType::MemrefInout, + ParamContent::ValueInput { .. } => ParamType::ValueInput, + ParamContent::ValueOutput { .. } => ParamType::ValueOutput, + ParamContent::ValueInout { .. } => ParamType::ValueInout, + } + } + + fn get_raw_type(&self) -> u32 { + self.get_type() as u32 + } + + fn as_raw(&mut self) -> raw::TEE_Param { + match &mut self.content { + ParamContent::None => raw::TEE_Param { + memref: raw::Memref { + buffer: core::ptr::null_mut(), + size: 0, + }, + }, + ParamContent::MemrefInput { buffer } => raw::TEE_Param { + memref: raw::Memref { + buffer: (*buffer).as_ptr() as *mut core::ffi::c_void, + size: buffer.len(), + }, + }, + ParamContent::MemrefOutput { buffer, written: _ } => raw::TEE_Param { + memref: raw::Memref { + buffer: (*buffer).as_mut_ptr() as *mut core::ffi::c_void, + size: buffer.len(), + }, + }, + ParamContent::MemrefInout { buffer, written: _ } => raw::TEE_Param { + memref: raw::Memref { + buffer: (*buffer).as_mut_ptr() as *mut core::ffi::c_void, + size: buffer.len(), + }, + }, + ParamContent::ValueInput { a, b } => raw::TEE_Param { + value: raw::Value { a: *a, b: *b }, + }, + ParamContent::ValueInout { a, b } => raw::TEE_Param { + value: raw::Value { a: *a, b: *b }, + }, + ParamContent::ValueOutput { a, b } => raw::TEE_Param { + value: raw::Value { a: *a, b: *b }, + }, + } + } + + fn update_size_from_raw(&mut self, raw_param: &raw::TEE_Param) { + match &mut self.content { + ParamContent::MemrefOutput { buffer: _, written } => { + *written = unsafe { raw_param.memref.size }; + } + ParamContent::MemrefInout { buffer: _, written } => { + *written = unsafe { raw_param.memref.size }; + } + _ => {} + } + } + + fn update_value_from_raw(&mut self, raw_param: &raw::TEE_Param) { + match &mut self.content { + ParamContent::ValueInout { a, b } => { + *a = unsafe { raw_param.value.a }; Review Comment: I am curious why we consider accessing `raw::TEE_Param` is `unsafe` here. Can you add comment about the reason to the code? ########## optee-utee/src/tee_parameter.rs: ########## @@ -0,0 +1,302 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::ParamType; +use core::ops::{Index, IndexMut}; +use optee_utee_sys as raw; + +#[derive(Copy, Clone, Debug)] +pub enum ParamIndex { + Arg0, + Arg1, + Arg2, + Arg3, +} + +impl ParamIndex { + fn to_usize(self) -> usize { + match self { + ParamIndex::Arg0 => 0, + ParamIndex::Arg1 => 1, + ParamIndex::Arg2 => 2, + ParamIndex::Arg3 => 3, + } + } +} + +enum ParamContent<'a> { + None, + MemrefInput { + buffer: &'a [u8], + }, + MemrefOutput { + buffer: &'a mut [u8], + written: usize, + }, + MemrefInout { + buffer: &'a mut [u8], + written: usize, + }, + ValueInput { + a: u32, + b: u32, + }, + ValueOutput { + a: u32, + b: u32, + }, + ValueInout { + a: u32, + b: u32, + }, +} + +pub struct Param<'a> { + content: ParamContent<'a>, +} + +impl<'a> Param<'a> { + fn new() -> Self { + Self { + content: ParamContent::None, + } + } + + pub fn written_slice(&self) -> Option<&[u8]> { + match &self.content { + ParamContent::MemrefOutput { buffer, written } => Some(&buffer[..*written]), + ParamContent::MemrefInout { buffer, written } => Some(&buffer[..*written]), + _ => None, + } + } + + pub fn output_value(&self) -> Option<(u32, u32)> { + match &self.content { + ParamContent::ValueOutput { a, b } => Some((*a, *b)), + ParamContent::ValueInout { a, b } => Some((*a, *b)), + _ => None, + } + } + + fn get_type(&self) -> ParamType { + match &self.content { + ParamContent::None => ParamType::None, + ParamContent::MemrefInput { .. } => ParamType::MemrefInput, + ParamContent::MemrefOutput { .. } => ParamType::MemrefOutput, + ParamContent::MemrefInout { .. } => ParamType::MemrefInout, + ParamContent::ValueInput { .. } => ParamType::ValueInput, + ParamContent::ValueOutput { .. } => ParamType::ValueOutput, + ParamContent::ValueInout { .. } => ParamType::ValueInout, + } + } + + fn get_raw_type(&self) -> u32 { + self.get_type() as u32 + } + + fn as_raw(&mut self) -> raw::TEE_Param { + match &mut self.content { + ParamContent::None => raw::TEE_Param { + memref: raw::Memref { + buffer: core::ptr::null_mut(), + size: 0, + }, + }, + ParamContent::MemrefInput { buffer } => raw::TEE_Param { + memref: raw::Memref { + buffer: (*buffer).as_ptr() as *mut core::ffi::c_void, + size: buffer.len(), + }, + }, + ParamContent::MemrefOutput { buffer, written: _ } => raw::TEE_Param { + memref: raw::Memref { + buffer: (*buffer).as_mut_ptr() as *mut core::ffi::c_void, + size: buffer.len(), + }, + }, + ParamContent::MemrefInout { buffer, written: _ } => raw::TEE_Param { + memref: raw::Memref { + buffer: (*buffer).as_mut_ptr() as *mut core::ffi::c_void, + size: buffer.len(), + }, + }, + ParamContent::ValueInput { a, b } => raw::TEE_Param { + value: raw::Value { a: *a, b: *b }, + }, + ParamContent::ValueInout { a, b } => raw::TEE_Param { + value: raw::Value { a: *a, b: *b }, + }, + ParamContent::ValueOutput { a, b } => raw::TEE_Param { + value: raw::Value { a: *a, b: *b }, + }, + } + } + + fn update_size_from_raw(&mut self, raw_param: &raw::TEE_Param) { + match &mut self.content { + ParamContent::MemrefOutput { buffer: _, written } => { + *written = unsafe { raw_param.memref.size }; Review Comment: I am curious why we consider accessing `raw::TEE_Param` is `unsafe` here. Can you add comment about the reason to the code? ########## optee-utee/src/ta_session.rs: ########## @@ -0,0 +1,150 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use core::ptr; +use optee_utee_sys as raw; + +use crate::{Error, Result, TeeParams, Uuid}; + +/// Represents a connection between a trusted application and another trusted application (can be user TA or pseudo TA). +pub struct TaSession { + raw: raw::TEE_TASessionHandle, + target_uuid: Uuid, + default_timeout: u32, +} + +impl TaSession { + /// Start configuring a new TA session with infinite timeout by default. + pub fn new(uuid: Uuid) -> Self { + Self { + raw: core::ptr::null_mut(), + target_uuid: uuid, + default_timeout: raw::TEE_TIMEOUT_INFINITE, + } + } + + /// Set the default timeout for this session. + /// Can be called both before and after opening the session. + pub fn timeout(mut self, timeout: u32) -> Self { + self.default_timeout = timeout; + self + } + + /// Set the default timeout for this session (mutable version). + /// Returns self to allow method chaining with invoke(). + pub fn with_timeout(&mut self, timeout: u32) -> &mut Self { + self.default_timeout = timeout; + self + } + + /// Open the session without parameters. + pub fn open(mut self) -> Result<Self> { + let mut err_origin: u32 = 0; + let mut raw_session: raw::TEE_TASessionHandle = core::ptr::null_mut(); + + match unsafe { + raw::TEE_OpenTASession( + self.target_uuid.as_raw_ptr(), + self.default_timeout, + 0, + ptr::null_mut(), + &mut raw_session, + &mut err_origin, + ) + } { + raw::TEE_SUCCESS => { + self.raw = raw_session; + Ok(self) + } + code => Err(Error::from_raw_error(code)), + } + } + + /// Open the session with parameters. + pub fn open_with_params(mut self, params: &mut TeeParams) -> Result<Self> { + let mut err_origin: u32 = 0; + let mut raw_session: raw::TEE_TASessionHandle = core::ptr::null_mut(); + let mut raw_params = params.as_raw(); + let param_types = params.raw_param_types(); + + match unsafe { + raw::TEE_OpenTASession( + self.target_uuid.as_raw_ptr(), + self.default_timeout, + param_types, + raw_params.as_mut_ptr(), + &mut raw_session, + &mut err_origin, + ) + } { + raw::TEE_SUCCESS => { + // Update the parameters with any results + params.update_from_raw(&raw_params); + self.raw = raw_session; + Ok(self) + } + code => Err(Error::from_raw_error(code)), + } + } + + /// Get the default timeout value for this session. + pub fn get_default_timeout(&self) -> u32 { + self.default_timeout + } + + /// Invokes a command with the provided parameters using the session's default timeout. + /// Returns the result directly without allowing further method chaining. + pub fn invoke_command(&mut self, command_id: u32, params: &mut TeeParams) -> Result<()> { + let mut err_origin: u32 = 0; + let mut raw_params = params.as_raw(); + let param_types = params.raw_param_types(); + + match unsafe { + raw::TEE_InvokeTACommand( + self.raw, + self.default_timeout, + command_id, + param_types, + raw_params.as_mut_ptr(), + &mut err_origin, + ) + } { + raw::TEE_SUCCESS => { + // Update the parameters with the results + params.update_from_raw(&raw_params); + trace_println!("TEE_InvokeTACommand: command_id: {} finished", command_id); + Ok(()) Review Comment: We'd better avoid using `println!` by default inside SDK APIs. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: dev-unsubscr...@teaclave.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@teaclave.apache.org For additional commands, e-mail: dev-h...@teaclave.apache.org