You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@teaclave.apache.org by GitBox <gi...@apache.org> on 2020/06/02 03:23:23 UTC

[GitHub] [incubator-teaclave] mssun commented on a change in pull request #325: [function] Add a built-in function

mssun commented on a change in pull request #325:
URL: https://github.com/apache/incubator-teaclave/pull/325#discussion_r433598863



##########
File path: executor/src/builtin.rs
##########
@@ -49,6 +49,8 @@ impl TeaclaveExecutor for BuiltinFunctionExecutor {
             LogisticRegressionPredict::NAME => {
                 LogisticRegressionPredict::new().run(arguments, runtime)
             }
+            #[cfg(feature = "builtin-online-decrypt")]

Review comment:
       Use `_` instead of `-` for consistency.

##########
File path: function/src/online_decrypt.rs
##########
@@ -0,0 +1,159 @@
+// 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.
+
+#[cfg(feature = "mesalock_sgx")]
+use std::prelude::v1::*;
+extern crate base64;
+use anyhow::{anyhow, Result};
+use ring::aead::*;
+use std::convert::TryFrom;
+use std::str;
+use teaclave_types::{FunctionArguments, FunctionRuntime};
+
+#[derive(Default)]
+pub struct OnlineDecrypt;
+
+#[derive(serde::Deserialize)]
+struct OnlineDecryptArguments {
+    key: String,
+    nonce: String,
+    encrypted_data: String,
+    algorithm: String,
+}
+
+enum Error {
+    CryptoError,
+}
+
+impl From<ring::error::Unspecified> for Error {
+    fn from(_: ring::error::Unspecified) -> Self {
+        Error::CryptoError
+    }
+}

Review comment:
       These are no longer used.

##########
File path: examples/python/builtin_online_decrypt.py
##########
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+
+import sys
+import base64
+
+from teaclave import (AuthenticationService, FrontendService,
+                      AuthenticationClient, FrontendClient)
+from utils import (AUTHENTICATION_SERVICE_ADDRESS, FRONTEND_SERVICE_ADDRESS,
+                   AS_ROOT_CA_CERT_PATH, ENCLAVE_INFO_PATH, USER_ID,
+                   USER_PASSWORD)
+
+
+class BuiltinOnlineDecryptExample:
+    def __init__(self, user_id, user_password):
+        self.user_id = user_id
+        self.user_password = user_password
+
+    def decrypt(self, key, nonce, encrypted_data, algorithm):
+        channel = AuthenticationService(AUTHENTICATION_SERVICE_ADDRESS,
+                                        AS_ROOT_CA_CERT_PATH,
+                                        ENCLAVE_INFO_PATH).connect()
+        client = AuthenticationClient(channel)
+
+        print("[+] registering user")
+        client.user_register(self.user_id, self.user_password)
+
+        print("[+] login")
+        token = client.user_login(self.user_id, self.user_password)
+
+        channel = FrontendService(FRONTEND_SERVICE_ADDRESS,
+                                  AS_ROOT_CA_CERT_PATH,
+                                  ENCLAVE_INFO_PATH).connect()
+        metadata = {"id": self.user_id, "token": token}
+        client = FrontendClient(channel, metadata)
+
+        print("[+] registering function")
+        function_id = client.register_function(
+            name="builtin-online-decrypt",
+            description="Native Echo Function",
+            executor_type="builtin",
+            arguments=["key", "nonce", "encrypted_data", "algorithm"])
+
+        print("[+] creating task")
+        task_id = client.create_task(
+            function_id=function_id,
+            function_arguments={
+                "key": DataToBase64(key),
+                "nonce": DataToBase64(nonce),
+                "encrypted_data":
+                "CaZd8qSMMlBp8SjSXj2I4dQIuC9KkZ5DI/ATo1sWJw==",
+                "algorithm": algorithm
+            },
+            executor="builtin")
+
+        print("[+] invoking task")
+        client.invoke_task(task_id)
+
+        print("[+] getting result")
+        result = client.get_task_result(task_id)
+        print("[+] done")
+
+        return bytes(result)
+
+
+def DataToBase64(data):
+    return base64.standard_b64encode(bytes(data)).decode("utf-8")
+
+
+def main():
+    example = BuiltinOnlineDecryptExample(USER_ID, USER_PASSWORD)
+    key = [
+        106, 165, 29, 129, 157, 37, 38, 123, 179, 247, 40, 143, 146, 128, 241,
+        51, 166, 92, 77, 197, 85, 165, 222, 10, 40, 186, 179, 108, 112, 252,
+        240, 184
+    ]
+    nonce = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
+    encrypted_data = "CaZd8qSMMlBp8SjSXj2I4dQIuC9KkZ5DI/ATo1sWJw=="
+    algorithm = "aes256gcm" #Alogorithm can be "aes256gcm" or "aes128gcm"
+    rt = example.decrypt(key, nonce, encrypted_data, algorithm)
+    print("[+] function return: ", rt)
+
+
+if __name__ == '__main__':
+    main()

Review comment:
       Missing newline in the end of the file.

##########
File path: examples/python/builtin_online_decrypt.py
##########
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+
+import sys
+import base64
+
+from teaclave import (AuthenticationService, FrontendService,
+                      AuthenticationClient, FrontendClient)
+from utils import (AUTHENTICATION_SERVICE_ADDRESS, FRONTEND_SERVICE_ADDRESS,
+                   AS_ROOT_CA_CERT_PATH, ENCLAVE_INFO_PATH, USER_ID,
+                   USER_PASSWORD)
+
+
+class BuiltinOnlineDecryptExample:
+    def __init__(self, user_id, user_password):
+        self.user_id = user_id
+        self.user_password = user_password
+
+    def decrypt(self, key, nonce, encrypted_data, algorithm):
+        channel = AuthenticationService(AUTHENTICATION_SERVICE_ADDRESS,
+                                        AS_ROOT_CA_CERT_PATH,
+                                        ENCLAVE_INFO_PATH).connect()
+        client = AuthenticationClient(channel)
+
+        print("[+] registering user")
+        client.user_register(self.user_id, self.user_password)
+
+        print("[+] login")
+        token = client.user_login(self.user_id, self.user_password)
+
+        channel = FrontendService(FRONTEND_SERVICE_ADDRESS,
+                                  AS_ROOT_CA_CERT_PATH,
+                                  ENCLAVE_INFO_PATH).connect()
+        metadata = {"id": self.user_id, "token": token}
+        client = FrontendClient(channel, metadata)
+
+        print("[+] registering function")
+        function_id = client.register_function(
+            name="builtin-online-decrypt",
+            description="Native Echo Function",
+            executor_type="builtin",
+            arguments=["key", "nonce", "encrypted_data", "algorithm"])
+
+        print("[+] creating task")
+        task_id = client.create_task(
+            function_id=function_id,
+            function_arguments={
+                "key": DataToBase64(key),
+                "nonce": DataToBase64(nonce),
+                "encrypted_data":
+                "CaZd8qSMMlBp8SjSXj2I4dQIuC9KkZ5DI/ATo1sWJw==",
+                "algorithm": algorithm
+            },
+            executor="builtin")
+
+        print("[+] invoking task")
+        client.invoke_task(task_id)
+
+        print("[+] getting result")
+        result = client.get_task_result(task_id)
+        print("[+] done")
+
+        return bytes(result)
+
+
+def DataToBase64(data):

Review comment:
       Function in Python should be in camelCase.
   
   `DataToBase64` => `dataToBase64`

##########
File path: function/src/online_decrypt.rs
##########
@@ -0,0 +1,159 @@
+// 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.
+
+#[cfg(feature = "mesalock_sgx")]
+use std::prelude::v1::*;
+extern crate base64;
+use anyhow::{anyhow, Result};
+use ring::aead::*;
+use std::convert::TryFrom;
+use std::str;
+use teaclave_types::{FunctionArguments, FunctionRuntime};
+
+#[derive(Default)]
+pub struct OnlineDecrypt;
+
+#[derive(serde::Deserialize)]
+struct OnlineDecryptArguments {
+    key: String,
+    nonce: String,
+    encrypted_data: String,
+    algorithm: String,
+}
+
+enum Error {
+    CryptoError,
+}
+
+impl From<ring::error::Unspecified> for Error {
+    fn from(_: ring::error::Unspecified) -> Self {
+        Error::CryptoError
+    }
+}
+
+impl TryFrom<FunctionArguments> for OnlineDecryptArguments {
+    type Error = anyhow::Error;
+
+    fn try_from(arguments: FunctionArguments) -> Result<Self, Self::Error> {
+        use anyhow::Context;
+        serde_json::from_str(&arguments.into_string()).context("Cannot deserialize arguments")
+    }
+}
+
+fn decrypt(
+    key: &[u8],
+    nonce_data: &[u8],
+    data: &mut Vec<u8>,
+    alg: &'static ring::aead::Algorithm,
+) -> anyhow::Result<()> {
+    let key =
+        LessSafeKey::new(UnboundKey::new(&alg, &key).map_err(|_| anyhow!("decryption error"))?);
+    let nonce = Nonce::try_assume_unique_for_key(&nonce_data[0..12])
+        .map_err(|_| anyhow!("decryption error"))?;
+    key.open_in_place(nonce, Aad::empty(), data)
+        .map_err(|_| anyhow!("decryption error"))?;
+    data.truncate(data.len() - alg.tag_len());
+    Ok(())
+}
+
+fn decrypt_string_base64(
+    key: &str,
+    nonce_str: &str,
+    encrypted: &str,
+    alg: &'static ring::aead::Algorithm,
+) -> anyhow::Result<String> {
+    let decoded_key = base64::decode(&key)?;
+    let nonce = base64::decode(&nonce_str)?;
+    let mut data_vec = base64::decode(&encrypted)?;
+
+    let _result = decrypt(&decoded_key, &nonce, &mut data_vec, &alg)

Review comment:
       `     let _result = decrypt(&decoded_key, &nonce, &mut data_vec, &alg) ` => `decrypt(&decoded_key, &nonce, &mut data_vec, &alg) `
   
   No need to get the `()` return.

##########
File path: executor/Cargo.toml
##########
@@ -30,13 +30,16 @@ full_builtin_function = [
   "builtin_gbdt_predict",
   "builtin_gbdt_train",
   "builtin_logistic_regression_predict",
-  "builtin_logistic_regression_train"
+  "builtin_logistic_regression_train",
+  "builtin-online-decrypt",
 ]
+
 builtin_echo = []
 builtin_gbdt_predict = []
 builtin_gbdt_train = []
 builtin_logistic_regression_predict = []
 builtin_logistic_regression_train = []
+builtin-online-decrypt = []

Review comment:
       Use `_` instead of `-` for consistency.

##########
File path: executor/Cargo.toml
##########
@@ -30,13 +30,16 @@ full_builtin_function = [
   "builtin_gbdt_predict",
   "builtin_gbdt_train",
   "builtin_logistic_regression_predict",
-  "builtin_logistic_regression_train"
+  "builtin_logistic_regression_train",
+  "builtin-online-decrypt",

Review comment:
       Use `_` instead of `-` for consistency.

##########
File path: function/src/online_decrypt.rs
##########
@@ -0,0 +1,159 @@
+// 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.
+
+#[cfg(feature = "mesalock_sgx")]
+use std::prelude::v1::*;
+extern crate base64;
+use anyhow::{anyhow, Result};
+use ring::aead::*;
+use std::convert::TryFrom;
+use std::str;
+use teaclave_types::{FunctionArguments, FunctionRuntime};
+
+#[derive(Default)]
+pub struct OnlineDecrypt;
+
+#[derive(serde::Deserialize)]
+struct OnlineDecryptArguments {
+    key: String,
+    nonce: String,
+    encrypted_data: String,
+    algorithm: String,
+}
+
+enum Error {
+    CryptoError,
+}
+
+impl From<ring::error::Unspecified> for Error {
+    fn from(_: ring::error::Unspecified) -> Self {
+        Error::CryptoError
+    }
+}
+
+impl TryFrom<FunctionArguments> for OnlineDecryptArguments {
+    type Error = anyhow::Error;
+
+    fn try_from(arguments: FunctionArguments) -> Result<Self, Self::Error> {
+        use anyhow::Context;
+        serde_json::from_str(&arguments.into_string()).context("Cannot deserialize arguments")
+    }
+}
+
+fn decrypt(
+    key: &[u8],
+    nonce_data: &[u8],
+    data: &mut Vec<u8>,
+    alg: &'static ring::aead::Algorithm,
+) -> anyhow::Result<()> {
+    let key =
+        LessSafeKey::new(UnboundKey::new(&alg, &key).map_err(|_| anyhow!("decryption error"))?);
+    let nonce = Nonce::try_assume_unique_for_key(&nonce_data[0..12])
+        .map_err(|_| anyhow!("decryption error"))?;
+    key.open_in_place(nonce, Aad::empty(), data)
+        .map_err(|_| anyhow!("decryption error"))?;
+    data.truncate(data.len() - alg.tag_len());
+    Ok(())
+}
+
+fn decrypt_string_base64(
+    key: &str,
+    nonce_str: &str,
+    encrypted: &str,
+    alg: &'static ring::aead::Algorithm,
+) -> anyhow::Result<String> {
+    let decoded_key = base64::decode(&key)?;
+    let nonce = base64::decode(&nonce_str)?;
+    let mut data_vec = base64::decode(&encrypted)?;
+
+    let _result = decrypt(&decoded_key, &nonce, &mut data_vec, &alg)
+        .map_err(|_| anyhow!("decryption error"))?;
+    let string = str::from_utf8(&data_vec).map_err(|_| anyhow!("base64 decoded error"))?;
+
+    Ok(string.to_string())
+}
+
+impl OnlineDecrypt {
+    pub const NAME: &'static str = "builtin-online-decrypt";
+
+    pub fn new() -> Self {
+        Default::default()
+    }
+
+    pub fn run(
+        &self,
+        arguments: FunctionArguments,
+        _runtime: FunctionRuntime,
+    ) -> anyhow::Result<String> {
+        let args = OnlineDecryptArguments::try_from(arguments)?;
+        let key = args.key;
+        let nonce = args.nonce;
+        let encrypted_data = args.encrypted_data;
+        let algorithm = &args.algorithm[..];
+
+        let alg = match algorithm {
+            "aes128gcm" => &AES_128_GCM,
+            "aes256gcm" => &AES_256_GCM,
+            _ => return Err(anyhow!("Invalid algorithm")),

Review comment:
       `return Err(anyhow!("Invalid algorithm"))` == `bail!("Invalid algorithm")`

##########
File path: examples/python/builtin_online_decrypt.py
##########
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+
+import sys
+import base64
+
+from teaclave import (AuthenticationService, FrontendService,
+                      AuthenticationClient, FrontendClient)
+from utils import (AUTHENTICATION_SERVICE_ADDRESS, FRONTEND_SERVICE_ADDRESS,
+                   AS_ROOT_CA_CERT_PATH, ENCLAVE_INFO_PATH, USER_ID,
+                   USER_PASSWORD)
+
+
+class BuiltinOnlineDecryptExample:
+    def __init__(self, user_id, user_password):
+        self.user_id = user_id
+        self.user_password = user_password
+
+    def decrypt(self, key, nonce, encrypted_data, algorithm):
+        channel = AuthenticationService(AUTHENTICATION_SERVICE_ADDRESS,
+                                        AS_ROOT_CA_CERT_PATH,
+                                        ENCLAVE_INFO_PATH).connect()
+        client = AuthenticationClient(channel)
+
+        print("[+] registering user")
+        client.user_register(self.user_id, self.user_password)
+
+        print("[+] login")
+        token = client.user_login(self.user_id, self.user_password)
+
+        channel = FrontendService(FRONTEND_SERVICE_ADDRESS,
+                                  AS_ROOT_CA_CERT_PATH,
+                                  ENCLAVE_INFO_PATH).connect()
+        metadata = {"id": self.user_id, "token": token}
+        client = FrontendClient(channel, metadata)
+
+        print("[+] registering function")
+        function_id = client.register_function(
+            name="builtin-online-decrypt",
+            description="Native Echo Function",
+            executor_type="builtin",
+            arguments=["key", "nonce", "encrypted_data", "algorithm"])
+
+        print("[+] creating task")
+        task_id = client.create_task(
+            function_id=function_id,
+            function_arguments={
+                "key": DataToBase64(key),
+                "nonce": DataToBase64(nonce),
+                "encrypted_data":
+                "CaZd8qSMMlBp8SjSXj2I4dQIuC9KkZ5DI/ATo1sWJw==",
+                "algorithm": algorithm
+            },
+            executor="builtin")
+
+        print("[+] invoking task")
+        client.invoke_task(task_id)
+
+        print("[+] getting result")
+        result = client.get_task_result(task_id)
+        print("[+] done")
+
+        return bytes(result)
+
+
+def DataToBase64(data):
+    return base64.standard_b64encode(bytes(data)).decode("utf-8")
+
+
+def main():
+    example = BuiltinOnlineDecryptExample(USER_ID, USER_PASSWORD)
+    key = [
+        106, 165, 29, 129, 157, 37, 38, 123, 179, 247, 40, 143, 146, 128, 241,
+        51, 166, 92, 77, 197, 85, 165, 222, 10, 40, 186, 179, 108, 112, 252,
+        240, 184
+    ]
+    nonce = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
+    encrypted_data = "CaZd8qSMMlBp8SjSXj2I4dQIuC9KkZ5DI/ATo1sWJw=="
+    algorithm = "aes256gcm" #Alogorithm can be "aes256gcm" or "aes128gcm"

Review comment:
       The comment sign `#` comes with a space like this:
   
   `#Alogorithm can be "aes256gcm" or "aes128gcm"` => `# Alogorithm can be "aes256gcm" or "aes128gcm"`




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@teaclave.apache.org
For additional commands, e-mail: notifications-help@teaclave.apache.org