diff --git a/enclave/qtsm-sdk-c/include/kms.h b/enclave/qtsm-sdk-c/include/kms.h index 1a0fa47e4bbaaa38eb8168432ce9ac7ce0ccbdce..40f1110bec380b0cfbc5e4fce0d2c74ac1adac3f 100644 --- a/enclave/qtsm-sdk-c/include/kms.h +++ b/enclave/qtsm-sdk-c/include/kms.h @@ -109,7 +109,7 @@ unsigned int extract_data_from_envelop(unsigned char *ciphertext, This function blocks and waits for the reply. * @sig_params (input) : The parameters to use for calling the API. * @handle (input) : The alias of KMS CMK used to encrypt the data key. - * @datakey_len (input) : The spec of key to generate. + * @datakey_len (input) : The bit length of the data encryption key (e.g., 128, 256). * @datakey (output) : The keyid/plaintext/ciphertext_blob output of the call. * * Context: process context diff --git a/enclave/qtsm-sdk-c/qtsm_sdk_c.spec b/enclave/qtsm-sdk-c/qtsm_sdk_c.spec index bf446d6f91495c46bce51b8f7ede4dd57ed7cc34..88d79c3c958241c55765cf4cf1e30e88f65f99f8 100644 --- a/enclave/qtsm-sdk-c/qtsm_sdk_c.spec +++ b/enclave/qtsm-sdk-c/qtsm_sdk_c.spec @@ -3,7 +3,7 @@ Summary : The SDK-C used to communicate with Huawei KMS service. Name : qtsm-sdk-c Version : 1.0.0 -Release : 9 +Release : 10 License : GPLv2 and BSD and MIT and CC-BY Source0 : %{name}-%{version}.tar.xz BuildArch : x86_64 aarch64 @@ -46,6 +46,8 @@ qtsm_sdk_sample_build() { qtsm_sdk_sample_build %changelog +* Wed May 21 2025 HUAWEI - 1.0.0-10 + rebase the newest codes * Fri Feb 02 2024 HUAWEI - 1.0.0-9 rebase the newest codes * Wed Jan 19 2022 HUAWEI diff --git a/enclave/qtsm-sdk-c/samples/Dockerfile.sdk b/enclave/qtsm-sdk-c/samples/Dockerfile.sdk index f788da8516551f9db6d764e3f883a8e458df3f9a..470d5eca137d34d9ae4dec00378e36f9bc6ee79f 100644 --- a/enclave/qtsm-sdk-c/samples/Dockerfile.sdk +++ b/enclave/qtsm-sdk-c/samples/Dockerfile.sdk @@ -1,59 +1,42 @@ -# Copyright (c) Huawei Technologies Co., Ltd. 2022. All Rights Reserved. -# SPDX-License-Identifier: Apache-2.0. - -FROM ubuntu:16.04 AS base-img - -RUN cp -a /etc/apt/sources.list /etc/apt/sources.list.bak - -RUN cat /dev/null > /etc/apt/sources.list - -WORKDIR /root/builder - -COPY qtsm-sdk-c/samples/scripts/env_cfg.sh script/ -RUN chmod +x script/env_cfg.sh && \ - /bin/sh -c script/env_cfg.sh - -RUN echo "124.70.125.167 mirrors.tools.huawei.com" >> /etc/hosts -# install relative dependencies -RUN rm -rf /var/lib/apt/lists/* && \ - apt-get update --fix-missing -o Acquire::http::No-Cache=True && \ - apt-get install -y gcc && \ - apt-get install -y make && \ - apt-get install -y tar && \ - apt-get install -y alien && \ - apt-get install -y libssl-dev && \ - apt-get install -y libtirpc-dev && \ - apt-get install -y libkeyutils-dev && \ - apt-get install -y libglib2.0-dev && \ - apt-get install -y curl && \ - apt-get install -y libcurl4-openssl-dev && \ - apt-get install -y libcbor-dev && \ - apt-get install -y libjson-c-dev && \ - apt-get install -y git && \ - apt-get install -y cmake && \ - apt-get install -y wget && \ - apt-get install -y unzip - -COPY qtsm-sdk-c qtsm-sdk-c -COPY rpm /root/builder/rpm -RUN cd /root/builder/rpm && \ - alien --scripts *.rpm && \ - dpkg -i *.deb - -ENV LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/root/builder/qtsm-sdk-c/samples/lib -RUN tar -zxvf huaweicloud-sdk-c-obs-3.21.8.tar.gz && \ - cd huaweicloud-sdk-c-obs-3.21.8/platform/huaweisecurec/src && \ - make clean && \ +FROM ubuntu:22.04 + +# You can get huawei-qingtian from https://gitee.com/HuaweiCloudDeveloper/huawei-qingtian +COPY huawei-qingtian /home/huawei-qingtian + +RUN apt-get update -y && \ + apt-get install libglib2.0-dev libcurl4-openssl-dev curl make gcc wget tar iproute2 libssl-dev libjson-c-dev libcbor-dev -y + +RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && \ + bash -c "source $HOME/.cargo/env" +ENV PATH="/root/.cargo/bin:${PATH}" + +WORKDIR /home/huawei-qingtian/qingtian-tools/qproxy +RUN cargo build --release && \ + mkdir -p /home/test && \ + cp target/release/qproxy /home/test/qproxy + +WORKDIR /home/test +RUN wget https://obs-community-intl.obs.ap-southeast-1.myhuaweicloud.com/obsutil/current/obsutil_linux_amd64.tar.gz && \ + tar zxf obsutil_linux_amd64.tar.gz --wildcards --no-anchored '*/obsutil' --strip-components=1 + +WORKDIR /home/huawei-qingtian/enclave/qtsm-sdk-c/samples +RUN cp scripts/config.toml /home/test/config.toml + +WORKDIR /home/huawei-qingtian/enclave/qtsm/lib +RUN mkdir -p ../output && \ make && \ - cp ../lib/libsecurec.so /usr/local/lib/libsecurec.so && \ - cd /root/builder/huaweicloud-sdk-c-obs-3.21.8/source/eSDK_OBS_API/eSDK_OBS_API_C++ && \ - sed -i '403i #define CURL_SOCKET_PATH "/var/run/enclave_proxy.socket"' src/request.c && \ - sed -i '419i curl_easy_setopt_safe(CURLOPT_UNIX_SOCKET_PATH, CURL_SOCKET_PATH);' src/request.c && \ - sh build.sh && \ - mkdir -p /root/builder/qtsm-sdk-c/samples/lib && \ - cp lib/* /root/builder/qtsm-sdk-c/samples/lib -RUN echo "/usr/lib64" >> /etc/ld.so.conf && \ - ldconfig -WORKDIR /root/builder/qtsm-sdk-c/samples/ + cp libqtsm.so /usr/lib64/ && \ + echo "/usr/lib64" >> /etc/ld.so.conf && \ + ldconfig && \ + cp ../include/qtsm_lib.h /usr/include/ && \ + cp ../include/qtsm_lib_comm.h /usr/include/ + +WORKDIR /home/huawei-qingtian/enclave/qtsm-sdk-c/samples RUN make -CMD ["python3", "/root/builder/qtsm-sdk-c/samples/src/test.py"] \ No newline at end of file + +WORKDIR /home/huawei-qingtian/enclave/qtsm-sdk-c/tests/vsock_shell +RUN gcc vsock_shell.c -o directShell && \ + chmod +x directShell && \ + cp directShell /home/test/directShell + +CMD /home/test/directShell diff --git a/enclave/qtsm-sdk-c/samples/Makefile b/enclave/qtsm-sdk-c/samples/Makefile index 74a5dfca88a242f2d9dc9c4df62edb3b68dcebad..ec4705a70c03118a5d204399b6ebe62719e4dec7 100644 --- a/enclave/qtsm-sdk-c/samples/Makefile +++ b/enclave/qtsm-sdk-c/samples/Makefile @@ -27,8 +27,6 @@ LIB += -ljson-c LIB += -lqtsm LIB += -lpthread LIB += -lglib-2.0 -LIB += -lsecurec -LIB += -leSDKOBS QTSM_LIB_PATH += -L $(CURRENT_DIR)/lib QTSM_LIB_PATH += -L /usr/bin @@ -39,7 +37,9 @@ ifeq (,$(CC)) CC := gcc endif -GCC_CHOOSE := -W -Os -g -DSDK_DEBUG +# If you want to open the debug option, please open it. +#GCC_CHOOSE := -W -Os -g -DSDK_DEBUG +GCC_CHOOSE := -W -Os -g GCC_CHOOSE += -Wl,-z,relro,-z,now GCC_CHOOSE += -Wl,-z,noexecstack GCC_CHOOSE += -fstack-protector-strong diff --git a/enclave/qtsm-sdk-c/samples/README.md b/enclave/qtsm-sdk-c/samples/README.md index 52a688b5f49012197e8bc2aefe0ee7f8e841623e..057f45c221c583cca640d04d30d37d2c6cbed03f 100644 --- a/enclave/qtsm-sdk-c/samples/README.md +++ b/enclave/qtsm-sdk-c/samples/README.md @@ -1,10 +1,10 @@ # QTSM-SDK-C Sample This sample describes a workflow about the enclave usage. -1. A trusted operator encrypts a plaintext (e.g. bank account and PIN) via the Huawei KMS serive and puts the ciphertext into a bucket in Huawei cloud OBS service. +1. A trusted operator encrypts a plaintext (e.g. bank account and PIN) via the Huawei KMS service and puts the ciphertext into a bucket in Huawei cloud OBS service. 2. Secondly, he creates an IAM account for an untrusted SRE. 3. After filling with the `config.json`, he generates an enclave eif image with `PCR0` and `PCR8` for this untrusted SRE. The SRE is allowed to get the ciphertext from OBS bucket, decrypt the ciphertext via KMS decryption API, and put plaintext into the OBS bucket. -4. This right policy is specified by the trusted operator in the IAM serice provided by Huawei cloud with `PCR0` amd `PCR8`. +4. This right policy is specified by the trusted operator in the IAM service provided by Huawei cloud with `PCR0` amd `PCR8`. ## Prerequests @@ -15,11 +15,6 @@ pip3 install --trusted-host mirrors.tools.huawei.com -i https://mirrors.tools.hu pip3 install --trusted-host mirrors.tools.huawei.com -i https://mirrors.tools.huawei.com/pypi/simple huaweicloudsdkkms ``` -Please compiling the `libqtsm` firstly. -| name | link | -|------------------------------------------------------------|------------------------------------------------------------------| -| libqtsm | https://github.com/huaweicloud/qingtian_enclave/enclave/qtsm | - ## Preparation - Build up a project and then you can get a `${ProjectID}` @@ -28,10 +23,11 @@ Please compiling the `libqtsm` firstly. - Create a IAM account for the SRE operator and generate the SRE operator's `${SREAK}` and `${SRESK}` - Grant the KMS decryption right to the SRE operator - Create a master key represented by a key id (`${KeyID}`) in Huawei KMS service +- Create a OBS bucket named `${OBSBucket}`, and create `${PlaintextKey}` and `${CiphertextKey}` -## Generate the ciphertex via the Huawei KMS service +## Generate the ciphertext via the Huawei KMS service -You can use the `scripts/encryptAndDecrypt.py` to encrypt one plaintext and put the ciphertext into a bucket in the Huawei OBS serice. +You can use the `scripts/encryptAndDecrypt.py` to encrypt one plaintext and put the ciphertext into a bucket in the Huawei OBS service. - Encrypt one plaintext `python3 script/encryptAndDecrypt.py encrypt -a ${SecureAK} -s ${SecureSK} -e ${KMSEndpoint} -p ${Plaintext} -w ${ProjectID} -k ${KeyID}` @@ -50,33 +46,38 @@ You need to specify contents in the `src/config.json`. "KeyId" : "${KeyID}", "ProjectId" : "${ProjectID}" }, - "FileName":{ - "Ciphertext": "${CiphertextKey}", - "Plaintext" : "${PlaintextKey}", - "OBSBucket" : "${OBSBucket}" - }, "Endpoint": { "KMSEndpoint" : "${KMSEndpoint}", "OBSEndpoint" : "${OBSEndpoint}" }, "VsockSetting":{ "VsockPort": "${VosckPort}" + }, + "FileKeys":{ + "Ciphertext": "${CiphertextKey}", + "Plaintext" : "${PlaintextKey}", + "BucketName" : "${OBSBucket}" } } ``` +## Configure resources for enclave and apply resource isolation +run `vim /etc/qingtian/enclave/qt-enclave-env.conf` and set `memory_mib` to 8192, set `cpu_count` to 2 +run `systemctl restart qt-enclave-env` to configure resources for enclave -## Generate the EIF image - -- Make a docker image -- Generate the EIF image using `qt cli` +## Generate the EIF image and launch an Enclave +You can enter the `enclave\qtsm-sdk-c\samples\scripts` directory, and run the script (`sh build_img.sh`) to make a EIF image file (`sdkdecrypt.eif`), and launch the enclave -You can run the script (`scripts/build_img.sh`) and then a EIF image file (`sdkdecrypt.eif`)is created. -Node: -In order to communicate with the qt-proxy, which will redirect network packages to huaweicloud obs service, we need to modify the huaweicloud-obs-c source codes (`huaweicloud-sdk-c-obs-3.21.8/source/eSDK_OBS_API/eSDK_OBS_API_C++/src/request.c`). +## Logining into the Enclave for debuging +In this sample, we compile and deploy a vsock server(`directShell`) in the Enclave, which is listening in the 9999 port. And this vsock server is only used for debuging. In our `scripts/build_img.sh`, We also get and compile a vsock client (`nc-vsock`) in the working directory. +After launching the Enclave, you can use following command to login into the Enclave: +`${WORKDIR}/nc-vsock/nc-vsock 4 9999` -## Lauch an enclave +And you can run the test in the enclave via: +`python3 /home/huawei-qingtian/enclave/qtsm-sdk-c/samples/src/test.py` -This EIF image file will be delivered to the SRE, who is allowed to launch an enclave to decrypt the ciphertext and put the plaintext back to the OBS bucket. -`qt enclave start --cpus 2 --mem 8192 --eif sdkdecrypt.eif` +### Startup the qproxy to redirect the obsutil network packages +In this sample, we redirect the obs network packages by the `qingtian-tools/qproxy` tool. Therefore, after running the test in the encalve, you need to start up the `qproxy` in the primary VM: +`${WORKDIR}/huawei-qingtian/qingtian-tools/qproxy/target/release/qproxy host --config ${WORKDIR}/huawei-qingtian/enclave/qtsm-sdk-c/samples/scripts/config.toml 4 &` -## Check the plaintext in the OBS bucket \ No newline at end of file +## Check the plaintext in the OBS bucket +You can login in your huawei cloud website, and check whether the plaintext is put into the obs bucket. \ No newline at end of file diff --git a/enclave/qtsm-sdk-c/samples/scripts/build_img.sh b/enclave/qtsm-sdk-c/samples/scripts/build_img.sh index 94cbc0f80860ac2b2dab440e7e90daa50ff9b7c6..affad40f240135a772ddb82d0b57329cd20ee478 100644 --- a/enclave/qtsm-sdk-c/samples/scripts/build_img.sh +++ b/enclave/qtsm-sdk-c/samples/scripts/build_img.sh @@ -1,24 +1,39 @@ #!/bin/bash - +set -e CUR_DIR=$(pwd) -QT_DIR=${CUR_DIR}/../../.. - -pushd ${QT_DIR} > /dev/null +TOP_DIR=${CUR_DIR}/../../../../.. +pushd ${TOP_DIR} > /dev/null -cp ${QT_DIR}/qtsm-sdk-c/samples/Dockerfile.sdk . -mkdir -p rpm && cd rpm -wget https://repo.huaweicloud.com/hce/2.0/updates/x86_64/Packages/libcbor-0.10.2-0.hce2.x86_64.rpm -wget https://repo.huaweicloud.com/hce/2.0/os/x86_64/Packages/cjson-1.7.15-1.hce2.x86_64.rpm -wget https://repo.huaweicloud.com/hce/2.0/os/x86_64/Packages/cjson-devel-1.7.15-1.hce2.x86_64.rpm -wget https://repo.huaweicloud.com/hce/2.0/debuginfo/x86_64/Packages/libcbor-devel-0.10.2-0.hce2.x86_64.rpm -wget https://repo.huaweicloud.com/hce/2.0/debuginfo/x86_64/Packages/libqtsm-devel-1.0.0-3.hce2.x86_64.rpm -wget https://repo.huaweicloud.com/euler/2.9/os/x86_64/updates/json-c-0.13.1-7.h3.eulerosv2r9.x86_64.rpm -wget https://repo.huaweicloud.com/euler/2.9/os/x86_64/updates/json-c-devel-0.13.1-7.h3.eulerosv2r9.x86_64.rpm -cd .. -wget https://github.com/huaweicloud/huaweicloud-sdk-c-obs/archive/refs/tags/v3.21.8.tar.gz +cp ${TOP_DIR}/huawei-qingtian/enclave/qtsm-sdk-c/samples/Dockerfile.sdk . docker build -f Dockerfile.sdk -t ubuntusdk . -rm ./Dockerfile.sdk -rm -rf huaweicloud-sdk-c-obs-3.21.8.tar.gz -qt enclave make-img --docker-uri ubuntusdk --eif ${CUR_DIR}/sdkdecrypt.eif -rm -rf ./rpm +qt enclave make-img --docker-uri ubuntusdk --eif ${TOP_DIR}/sdkdecrypt.eif + +cd ${TOP_DIR} +# get vsock client to login into the enclave for debuging +git clone https://github.com/stefanha/nc-vsock.git +cd nc-vsock && make + +# buildup the qproxy to redirect the network packages from the enclave's obsutil +cd ${TOP_DIR}/huawei-qingtian/qingtian-tools/qproxy +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y +source $HOME/.cargo/env +cargo build --release + +# install jq to get the obs endpoint +yum install jq -y +OBSEndpoint=$(jq -r '.Endpoint.OBSEndpoint' ${TOP_DIR}/huawei-qingtian/enclave/qtsm-sdk-c/samples/src/config.json) +echo ${OBSEndpoint} +sed -i "5s/.*/hostname = \"${OBSEndpoint}\"/" ${TOP_DIR}/huawei-qingtian/enclave/qtsm-sdk-c/samples/scripts/config.toml + +# launch the enclave +qt enclave start --cpus 2 --mem 8192 --eif ${TOP_DIR}/sdkdecrypt.eif --cid 4 +# launch the qt-proxy for redirecting the kms-api network packages +VsockPort=$(jq -r '.VsockSetting.VsockPort' ${TOP_DIR}/huawei-qingtian/enclave/qtsm-sdk-c/samples/src/config.json) +KmsEndpoint=$(jq -r '.Endpoint.KMSEndpoint' ${TOP_DIR}/huawei-qingtian/enclave/qtsm-sdk-c/samples/src/config.json) +/usr/local/bin/qingtian/enclave/qt_proxy -l ${VsockPort} -a ${KmsEndpoint} -p 443 & + +# launch the qproxy host +# sleep(100) +# ${TOP_DIR}/huawei-qingtian/qingtian-tools/qproxy/target/release/qproxy host --config ${TOP_DIR}/huawei-qingtian/enclave/qtsm-sdk-c/samples/src/config.toml 4 & + popd > /dev/null \ No newline at end of file diff --git a/enclave/qtsm-sdk-c/samples/scripts/config.toml b/enclave/qtsm-sdk-c/samples/scripts/config.toml new file mode 100644 index 0000000000000000000000000000000000000000..7d3e7fd5a59da5dc73bd23ef73e1d4e0b922482b --- /dev/null +++ b/enclave/qtsm-sdk-c/samples/scripts/config.toml @@ -0,0 +1,23 @@ +[[outbound_connections]] +# The hostname to forward traffic to +# +# Can also be an IP address +hostname = "obs.xxxxxx.myhuaweicloud.com" +# The port inside the enclave to use +# +# Must be unique and not conflict with qproxy ports (9999 and 9966 by default) +vsock_port = 6666 +# The port of the server to forward traffic to (connections will be made to +# hostname:port) +# +# The same port will be exposed inside the enclave +# +# Must not conflict with qproxy ports (8080 by default) +tcp_port = 443 + +[log_location] +host_log = "host.log" # qproxy host log name, e.g./var/log/qproxy/host.log +enclave_log = "enclave.log" # qproxy enclave log name, e.g./var/log/qproxy/enclave.log +log_level = "debug" # qproxy logger level, e.g. "off", "info", "warn", "error", "debug", "trace" +host_log_dir = "/var/log/qproxy" # qproxy host log dir, and its default value is "/var/log/qproxy" +enclave_log_dir = "/var/log/qproxy" # qproxy enclave log dir, and its default value is "/var/log/qproxy" diff --git a/enclave/qtsm-sdk-c/samples/src/config.json b/enclave/qtsm-sdk-c/samples/src/config.json index 954148a62768424a5f3afdc4ec2218d2ba84a3c4..b1f9d81606771ea78c6f1ad00583f40e47888d11 100644 --- a/enclave/qtsm-sdk-c/samples/src/config.json +++ b/enclave/qtsm-sdk-c/samples/src/config.json @@ -1,20 +1,20 @@ { "IAM":{ - "AK":"FAHWEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", - "SK":"7RqQV7kXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", - "KeyId" : "dd0b5b30-XXXXXXXXXXXXXXXXXXXXXXXXXXX", - "ProjectId" : "06057XXXXXXXXXXXXXXXXXXXXXXXXXXX" - }, - "FileName":{ - "Ciphertext": "ciphertext", - "Plaintext" : "plaintext", - "OBSBucket" : "bank-password" + "AK":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "SK":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "KeyId" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "ProjectId" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, "Endpoint": { - "KMSEndpoint" : "kms.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", - "OBSEndpoint" : "obs.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + "KMSEndpoint" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "OBSEndpoint" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, "VsockSetting":{ - "VsockPort": "8000" + "VsockPort": "8000" + }, + "FileKeys":{ + "Ciphertext": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "Plaintext" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "BucketName" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } -} +} \ No newline at end of file diff --git a/enclave/qtsm-sdk-c/samples/src/enclave.c b/enclave/qtsm-sdk-c/samples/src/enclave.c index 1aa248d109deecfbaa58b589b7fb981cfc4aa9c0..dadd7e689f322d35e12d45757da76afd4375d85b 100644 --- a/enclave/qtsm-sdk-c/samples/src/enclave.c +++ b/enclave/qtsm-sdk-c/samples/src/enclave.c @@ -31,326 +31,176 @@ #include "getopt.h" #endif -#include "eSDKOBS.h" -#include "obs_demo_common.h" -#include "securec.h" -#include "enclave_proxy.h" - #include "kms.h" #include "qtsm_lib.h" #include "attestation.h" -#define CIPHERTEXT_FILE "/root/text" -#define PLAINTEXT_LENGTH 1000 +#include "enclave_proxy.h" +#define CIPHERTEXT_FILE "/home/test/ciphertext" +#define PLAINTEXT_FILE "/home/test/plaintext" #define PARENT_CID 3 #define ENCLAVE_DEMO_BIN "enclave_demo_bin" -#define OBS_MAX_COUNT 10 #define ARGS_NUM 11 #define VSOCK_PORT_SHIFT 2 #define PLAINTEXT_KEY_LENGTH 128 +#define CIPHERTEXT_LEN 1024 +#define PLAINTEXT_LEN 1024 +#define MAX_SOCKET_PATH_LEN 128 static int vsock_port; -static char plaintext_key[PLAINTEXT_KEY_LENGTH]; - -struct ObsObject { - char *key; - unsigned char *buffer; - unsigned int buffer_size; - int is_get; - int vsock_cid; - int vsock_port; -}; - -struct ProcessedData { - char *data; - int data_len; -}; - -struct KmsInfo { - int vsock_cid; - int vsock_port; - char *endpoint; - char *project_id; - char *key_id; -}; - -static int test_get_object(char *key) +static sig_str_t global_ak; +static sig_str_t global_sk; +static sig_str_t global_endpoint; +static sig_str_t global_uri_prefix; +static sig_str_t global_key_id; +static sig_str_t global_socket_path; +static sig_params_t global_params; +keyid_handle_t global_handle; + +static int get_ciphertext(char *buffer, size_t buf_size, const char *filepath) { - obs_object_info object_info; - obs_options option; - get_object_callback_data data; - obs_get_conditions getcondition; - int rc = 0; - - init_obs_options(&option); - - memset_s(&getcondition, sizeof(getcondition), 0, sizeof(obs_get_conditions)); - init_get_properties(&getcondition); - - option.bucket_options.host_name = HOST_NAME; - option.bucket_options.bucket_name = BUCKET_NAME; - option.bucket_options.access_key = ACCESS_KEY_ID; - option.bucket_options.secret_access_key = SECRET_ACCESS_KEY; - - memset_s(&object_info, sizeof(object_info), 0, sizeof(obs_object_info)); - object_info.key = key; - - data.ret_status = OBS_STATUS_BUTT; - data.outfile = write_to_file(CIPHERTEXT_FILE); - - // The starting position of the reading - getcondition.start_byte = 0; - // Read length, default is 0: read to the end of the object - obs_get_object_handler get_object_handler = { - {&get_properties_callback, &get_object_complete_callback}, - &get_object_data_callback - }; - - get_object(&option, &object_info, &getcondition, 0, &get_object_handler, &data); - if (OBS_STATUS_OK == data.ret_status) { - printf("get %s object successfully.\n", key); - rc = 0; - } else { - printf("get %s object faied(%s).\n", key, obs_get_status_name(data.ret_status)); - rc = -1; + if (!buffer || buf_size == 0 || !filepath) { + fprintf(stderr, "Invalid parameters\n"); + return -1; } - fclose(data.outfile); - return rc; -} -static int test_put_object_from_buffer(struct ObsObject *obs_object) -{ - obs_options option; - obs_put_properties put_properties; - put_buffer_object_callback_data data; - int rc = 0; - // Initialize option - init_obs_options(&option); - // Initialize upload object properties - init_put_properties(&put_properties); - option.bucket_options.host_name = HOST_NAME; - option.bucket_options.bucket_name = BUCKET_NAME; - option.bucket_options.access_key = ACCESS_KEY_ID; - option.bucket_options.secret_access_key = SECRET_ACCESS_KEY; + FILE *fp = fopen(filepath, "rb"); + if (!fp) { + fprintf(stderr, "Failed to open file\n"); + return -1; + } - // Initialize the structure that stores the uploaded data - memset_s(&data, sizeof(data), 0, sizeof(put_buffer_object_callback_data)); - // Assign buffer to the uploaded data structure - data.put_buffer = obs_object->buffer; - // set buffersize - data.buffer_size = obs_object->buffer_size; + fseek(fp, 0, SEEK_END); + long file_size = ftell(fp); + rewind(fp); - // Set callback function - obs_put_object_handler putobjectHandler = { - { &response_properties_callback, &put_buffer_complete_callback}, - &put_buffer_data_callback - }; + if (file_size > (long)buf_size - 1) { + fprintf(stderr, "Buffer too small (need %ld bytes)\n", file_size); + fclose(fp); + return -1; + } - put_object(&option, obs_object->key, obs_object->buffer_size, &put_properties, 0, &putobjectHandler, &data); - if (OBS_STATUS_OK == data.ret_status) { - printf("put object %s from buffer successfully.\n", obs_object->key); - rc = 0; - } else { - printf("put object %s from buffer failed(%s).\n", obs_object->key, obs_get_status_name(data.ret_status)); - rc = -1; + size_t read_size = fread(buffer, 1, buf_size - 1, fp); + if (ferror(fp)) { + fprintf(stderr, "Read error\n"); + fclose(fp); + return -1; } - return rc; + + buffer[read_size] = '\0'; + fclose(fp); + return (int)read_size; } -static int test_interact_with_obs(struct ObsObject *obs_object) +static int setup_qt_proxy(struct connect_info *conn, int vsock_cid, int vsock_proxy_port) { - struct connect_info conn = {0}; int rc; - memset_s(&conn, sizeof(conn), 0, sizeof(struct connect_info)); - /*------ obs init------*/ - obs_initialize(OBS_INIT_ALL); - set_online_request_max_count(OBS_MAX_COUNT); - /* setup proxy */ - rc = setup_proxy(&conn, obs_object->vsock_cid, obs_object->vsock_port); + rc = setup_proxy(conn, vsock_cid, vsock_proxy_port); if (rc != PX_NO_ERROR) { - printf("setup_proxy obs error. rc is %d\n", rc); - goto err_conn; - } - - if (obs_object->is_get & 1) { - rc = test_get_object(obs_object->key); - } else { - rc = test_put_object_from_buffer(obs_object); + fprintf(stderr, "setup_proxy in kms decryption error\n"); + return -1; } - - close_proxy(&conn); -err_conn: - obs_deinitialize(); - return rc; + return 0; } -static int read_ciphertext_from_file(struct ProcessedData *ciphertext_data) +static int write_string_to_file(const char *buff, const char *filepath) { - FILE *fp; - int rc; - int len; - - fp = fopen(CIPHERTEXT_FILE, "r"); - if (fp == NULL) { - printf("fopen ciphertext err"); + size_t data_size; + size_t written; + if (!buff || !filepath) { + fprintf(stderr, "Invalid parameters\n"); return -1; } - fseek(fp, 0, SEEK_END); - len = ftell(fp); - if (len < 0 || len > INT_MAX) { - printf("invalid ciphertext"); - rc = -1; - goto fclose_fp; - } - ciphertext_data->data_len = len; - rewind(fp); - ciphertext_data->data = (char *)malloc((ciphertext_data->data_len + 1) * sizeof(char)); - if (!ciphertext_data->data) { - printf("malloc ciphertext_data error\n"); - rc = -1; - goto fclose_fp; - } - memset_s(ciphertext_data->data, (ciphertext_data->data_len + 1) * sizeof(char), 0, - (ciphertext_data->data_len + 1) * sizeof(char)); - rc = fread(ciphertext_data->data, 1, ciphertext_data->data_len * sizeof(char), fp); - if (rc != len) { - printf("fread ciphertext from ciphertext error\n"); - goto free_ciphertext_data_data; + data_size = strlen(buff); + + FILE *fp = fopen(filepath, "wb"); + if (!fp) { + fprintf(stderr, "Failed to open file\n"); + return -1; } - printf("%s\n", ciphertext_data->data); + + written = fwrite(buff, 1, data_size, fp); fclose(fp); - return 0; -free_ciphertext_data_data: - if (ciphertext_data->data) { - free(ciphertext_data->data); - ciphertext_data->data = NULL; + + if (written != data_size) { + fprintf(stderr, "Write incomplete\n"); + return -1; } -fclose_fp: - fclose(fp); - return rc; + + return (int)written; } -static unsigned long test_kms_decrypt_data(sig_params_t params, keyid_handle_t handle, - const struct ProcessedData *ciphertext, struct ProcessedData *plaintext) +static unsigned long test_kms_decrypt_data() { plain_cipher_buff_t data_buffer = {0}; unsigned long status; - unsigned int i; - data_buffer.data_in = ciphertext->data; - data_buffer.data_in_len = ciphertext->data_len; - data_buffer.data_out = plaintext->data; - data_buffer.data_out_len = &(plaintext->data_len); - - printf("\n***********kms input **************\n"); - printf("data_in: %s \n data_in_len : %d\n data_out: %s\n data_out_len:%d\n", - data_buffer.data_in, data_buffer.data_in_len, data_buffer.data_out, data_buffer.data_out_len); - printf("************kms input end ************\n"); - /* call kms_decrypt_data api */ - status = kms_decrypt_data_blocking(¶ms, &handle, &data_buffer); - if (status == KMS_SUCCESS) { - printf("plain_data_len is %u\n", *(data_buffer.data_out_len)); - for (i = 0; i < *(data_buffer.data_out_len); i++) - printf("%c", data_buffer.data_out[i]); - printf("\n"); - } - return status; -} - -static int test_kms_decrypt(struct KmsInfo *kms_info, struct ProcessedData *plaintext_data) -{ int rc; - struct connect_info conn; - sig_params_t params; - keyid_handle_t handle; - unsigned long status; - struct ProcessedData *ciphertext_data; + size_t data_len = PLAINTEXT_LEN; + size_t tmp_data_len; + struct connect_info conn = {0}; + char ciphertextdata[CIPHERTEXT_LEN] = {0}; + char plaintextdata[PLAINTEXT_LEN] = {0}; - /* get ciphertext from text file */ - ciphertext_data = malloc(sizeof(struct ProcessedData)); - if (!ciphertext_data) { - printf("alloc memory for ciphertext_data error. \n"); + /* Step1: setup qt_proxy */ + if ((rc = setup_qt_proxy(&conn, PARENT_CID, vsock_port)) != 0) return -1; - } - rc = read_ciphertext_from_file(ciphertext_data); - if (rc < 0) { - printf("read ciphertext from file error in test_kms_decrpyt. \n"); - goto free_ciphertext_data; - } - /* decrypt the ciphertext invoking kms decrypt api */ - rc = NO_ERROR; - sig_params_init(¶ms); - sig_str_t ak = sig_str(ACCESS_KEY_ID); - sig_str_t sk = sig_str(SECRET_ACCESS_KEY); - sig_str_t host = sig_str(kms_info->endpoint); - sig_str_t uri_prefix = sig_str(kms_info->project_id); - /* Set sign params */ - params.key = ak; - params.secret = sk; - params.host = host; - params.uri_prefix = uri_prefix; - /* Set key_id */ - handle.key_id = kms_info->key_id; - handle.len = strlen(kms_info->key_id); - - /* setup proxy */ - memset_s(&conn, sizeof(conn), 0, sizeof(struct connect_info)); - rc = setup_proxy(&conn, kms_info->vsock_cid, kms_info->vsock_port); - if (rc != PX_NO_ERROR) { - printf("setup_proxy in kms decryption error.\n"); + /* Step2: read ciphertext */ + tmp_data_len = get_ciphertext(ciphertextdata, CIPHERTEXT_LEN, CIPHERTEXT_FILE); + if (tmp_data_len < 0) { + fprintf(stderr, "read ciphertext from file error in test_kms_decrpyt.\n"); rc = -1; - goto free_ciphertext_data; + goto close_proxy; } - - /* test decrypt data api */ - status = test_kms_decrypt_data(params, handle, ciphertext_data, plaintext_data); - if (status != KMS_SUCCESS) { - printf("invoking kms decrypt api err: %ld.\n", status); + + data_buffer.data_in = ciphertextdata; + data_buffer.data_in_len = strlen(ciphertextdata); + data_buffer.data_out = plaintextdata; + data_buffer.data_out_len = &data_len; + + fprintf(stdout, "\n***********kms input **************\n"); + fprintf(stdout, "data_in: %s \n data_in_len : %d\n data_out: %s\n data_out_len:%u\n", + data_buffer.data_in, data_buffer.data_in_len, data_buffer.data_out, *(data_buffer.data_out_len)); + fprintf(stdout, "************kms input end ************\n"); + /* Step3: decrypt ciphertext */ + status = kms_decrypt_data_blocking(&global_params, &global_handle, &data_buffer); + if (status == KMS_SUCCESS) { + fprintf(stdout, "plain_data_len is %u\n", *(data_buffer.data_out_len)); + for (unsigned int i = 0; i < *(data_buffer.data_out_len); i++) + fprintf(stdout, "%c", data_buffer.data_out[i]); + fprintf(stdout, "\n"); + } else { + rc = -1; + fprintf(stderr, "invoking kms decrypt api err: %ld.\n", status); + goto close_proxy; + } + tmp_data_len = write_string_to_file(plaintextdata, PLAINTEXT_FILE); + if (tmp_data_len < 0) { + fprintf(stderr, "read ciphertext from file error in test_kms_decrpyt. \n"); rc = -1; + goto close_proxy; } -close_conn: + +close_proxy: close_proxy(&conn); -free_ciphertext_data: - free(ciphertext_data); return rc; } static void help() { - printf("%s [-p vsock_port] [-a ak] [-s sk] \n " \ - "[-c ciphertext_key] [-l plaintext_key] [-b bucket_name] \n" \ - "[-k key_id] [-m kms_endpoint] [-o obs_endpoint] [-j project_id] \n", ENCLAVE_DEMO_BIN); + fprintf(stdout, "%s [-p vsock_port] [-a ak] [-s sk] \n " \ + "[-k key_id] [-m kms_endpoint] [-j project_id] \n", ENCLAVE_DEMO_BIN); } -static int get_ciphertext(struct ObsObject *obs_object) -{ - int rc; - - obs_object->is_get = 1; - obs_object->vsock_cid = PARENT_CID; - obs_object->vsock_port = vsock_port; - rc = test_interact_with_obs(obs_object); - if (rc < 0) { - printf("get ciphertext from obs error\n"); - } - return rc; -} -static int invoke_kms_decryption(struct KmsInfo *kms_info, struct ProcessedData *plaintext_data) +static void convert_sig_str(char *data, sig_str_t *pa) { - int rc; - - kms_info->vsock_cid = PARENT_CID; - kms_info->vsock_port = vsock_port + 1; - rc = test_kms_decrypt(kms_info, plaintext_data); - if (rc < 0) { - printf("kms_decrpt error\n"); - } - return rc; + pa->data = data; + pa->len = strlen(data); } -static int process_input(int argc, char **argv, struct KmsInfo *kms_info, struct ObsObject *obs_object) +static int process_input(int argc, char **argv, sig_params_t *params, keyid_handle_t *handle) { int rc = 0; int c; @@ -359,17 +209,13 @@ static int process_input(int argc, char **argv, struct KmsInfo *kms_info, struct {"vsock_port", required_argument, 0, 'p'}, {"ak", required_argument, 0, 'a'}, {"sk", required_argument, 0, 's'}, - {"ciphertext_key", required_argument, 0, 'c'}, - {"plaintext_key", required_argument, 0, 'l'}, - {"bucket_name", required_argument, 0, 'b'}, {"key_id", required_argument, 0, 'k'}, {"kms_endpoint", required_argument, 0, 'm'}, - {"obs_endpoint", required_argument, 0, 'o'}, {"project_id", required_argument, 0, 'j'}, {0, 0, 0, 0} }; - while ((c = getopt_long(argc, argv, "hc:p:a:s:c:l:b:k:m:o:j:", options, NULL)) != -1) { + while ((c = getopt_long(argc, argv, "hc:p:a:s:k:m:j:", options, NULL)) != -1) { switch (c) { case 'h': case '?': @@ -379,94 +225,55 @@ static int process_input(int argc, char **argv, struct KmsInfo *kms_info, struct vsock_port = atoll(optarg); break; case 'a': - rc = strcpy_s(ACCESS_KEY_ID, sizeof(ACCESS_KEY_ID), optarg); + convert_sig_str(optarg, &global_ak); + params->key = global_ak; break; case 's': - rc = strcpy_s(SECRET_ACCESS_KEY, sizeof(SECRET_ACCESS_KEY), optarg); - break; - case 'c': - obs_object->key = optarg; - break; - case 'l': - rc = strcpy_s(plaintext_key, sizeof(plaintext_key), optarg); - break; - case 'b': - rc = strcpy_s(BUCKET_NAME, sizeof(BUCKET_NAME), optarg); + convert_sig_str(optarg, &global_sk); + params->secret = global_sk; break; case 'k': - kms_info->key_id = optarg; + handle->key_id = optarg; + handle->len = strlen(handle->key_id); break; case 'm': - kms_info->endpoint = optarg; - break; - case 'o': - rc = strcpy_s(HOST_NAME, sizeof(HOST_NAME), optarg); + convert_sig_str(optarg, &global_endpoint); + params->host = global_endpoint; break; case 'j': - kms_info->project_id = optarg; + convert_sig_str(optarg, &global_uri_prefix); + params->uri_prefix = global_uri_prefix; break; default: - printf("unsupport option %c\n", c); + fprintf(stdout, "unsupport option %c\n", c); break; } if (rc < 0) { - printf("get parameters fails\n"); + fprintf(stdout, "get parameters fails\n"); return rc; } } return rc; } -static int put_data_to_obs(struct ObsObject *obs_object, struct ProcessedData *plaintext_data) -{ - int rc; - - obs_object->key = plaintext_key; - obs_object->is_get = 0; - obs_object->buffer_size = plaintext_data->data_len; - obs_object->buffer = plaintext_data->data; - obs_object->vsock_port = vsock_port + VSOCK_PORT_SHIFT; - rc = test_interact_with_obs(obs_object); - if (rc < 0) - printf("put data to obs err\n"); - return rc; -} - int main(int argc, char **argv) { - struct ObsObject obs_object = {0}; int rc; - struct KmsInfo kms_info = {0}; - struct ProcessedData plaintext_data = {0}; + char socket_path[MAX_SOCKET_PATH_LEN] = {0}; /*---------process input-------*/ - rc = process_input(argc, argv, &kms_info, &obs_object); + rc = process_input(argc, argv, &global_params, &global_handle); if (rc < 0) return -1; - - /*--------get ciphertext----*/ - rc = get_ciphertext(&obs_object); + /*---------init socket path----*/ + rc = snprintf(socket_path, sizeof(socket_path), CURL_SOCKET_PATH, vsock_port); if (rc < 0) return -1; - - /*---- invoke kms decryption api -----*/ - plaintext_data.data_len = PLAINTEXT_LENGTH; - plaintext_data.data = (char *)malloc(plaintext_data.data_len * sizeof(char)); - memset_s(plaintext_data.data, plaintext_data.data_len * sizeof(char), - 0, plaintext_data.data_len * sizeof(char)); - rc = invoke_kms_decryption(&kms_info, &plaintext_data); - if (rc < 0) - goto free_plaintext_data; - - /*------ put plaintext to obs------*/ - rc = put_data_to_obs(&obs_object, &plaintext_data); + convert_sig_str(socket_path, &global_socket_path); + global_params.socket_path = global_socket_path; + /* test decrypt api */ + rc = test_kms_decrypt_data(); if (rc < 0) - printf("put plaintext to obs error\n"); - -free_plaintext_data: - if (plaintext_data.data_len != 0) { - free(plaintext_data.data); - plaintext_data.data = NULL; - } + return -1; return rc; } \ No newline at end of file diff --git a/enclave/qtsm-sdk-c/samples/src/obs_demo_common.c b/enclave/qtsm-sdk-c/samples/src/obs_demo_common.c deleted file mode 100644 index d9576e258a3de345f638eb5d2e441aaa9ee0bd1c..0000000000000000000000000000000000000000 --- a/enclave/qtsm-sdk-c/samples/src/obs_demo_common.c +++ /dev/null @@ -1,239 +0,0 @@ -/********************************************************************************* -* Copyright 2019 Huawei Technologies Co.,Ltd. -* Licensed 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. -********************************************************************************** -*/ -#include -#include -#include -#include -#include -#include - -#if defined __GNUC__ || defined LINUX -#include -#include -#include -#include -#include -#else -#include "getopt.h" -#endif - -#include "eSDKOBS.h" -#include "obs_demo_common.h" -#include "securec.h" - -#define DATA_BUF_OFFSET 100 -#define ARRAY_LENGTH_1024 1024 -#define ARRAY_LENGTH_2048 2048 -int showResponsePropertiesG = 1; -char locationconstraint[ARRAY_LENGTH_2048] = {0}; -char ACCESS_KEY_ID[ARRAY_LENGTH_2048] = {0}; -char SECRET_ACCESS_KEY[ARRAY_LENGTH_2048] = {0}; -char HOST_NAME[ARRAY_LENGTH_2048] = {0}; -char BUCKET_NAME[ARRAY_LENGTH_2048] = {0}; -obs_canned_acl canned_acl = OBS_CANNED_ACL_BUCKET_OWNER_FULL_CONTROL; -char *CA_FILE = "./client.pem"; -char UPLOAD_ID[ARRAY_LENGTH_2048] = {0}; - -int get_certificate_info(char *buffer, int buffer_length) -{ - int content_length = 0; - FILE *fp = fopen(CA_FILE, "r"); - if (fp) { - while (1) { - int rc = fread(buffer, sizeof(char), buffer_length, fp); - if (rc <= 0) - break; - content_length += rc; - } - fclose(fp); - } - return content_length; -} - -FILE *write_to_file(char *localfile) -{ - FILE *outfile = 0; - if (localfile) { - struct stat buf; - if (stat(localfile, &buf) == -1) { - outfile = fopen(localfile, "wb"); - } else { - outfile = fopen(localfile, "a"); - } - - if (!outfile) { - fprintf(stderr, "\nERROR: Failed to open output file %s: ", - localfile); - perror(0); - return -1; - } - } else if (showResponsePropertiesG) { - fprintf(stderr, "\nERROR: get -s requires a file_name parameter\n"); - } else { - outfile = stdout; - } - return outfile; -} - -obs_status response_properties_callback(const obs_response_properties *properties, void *callback_data) -{ - (void) callback_data; - - if (!showResponsePropertiesG) - return OBS_STATUS_OK; - -#define print_nonnull(name, field) \ - do { \ - if (properties->field) { \ - printf("%s: %s\n", name, properties->field); \ - } \ - } while (0) - - print_nonnull("ETag", etag); - print_nonnull("expiration", expiration); - print_nonnull("website_redirect_location", website_redirect_location); - print_nonnull("version_id", version_id); - if (properties->last_modified > 0) { - char timebuf[256] = {0}; - time_t t = (time_t) properties->last_modified; - strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ", gmtime(&t)); - printf("Last-Modified: %s\n", timebuf); - } - int i; - for (i = 0; i < properties->meta_data_count; i++) { - printf("x-amz-meta-%s: %s\n", properties->meta_data[i].name, - properties->meta_data[i].value); - } - return OBS_STATUS_OK; -} - -void put_buffer_complete_callback(obs_status status, - const obs_error_details *error, - void *callback_data) -{ - put_buffer_object_callback_data *data = (put_buffer_object_callback_data *)callback_data; - data->ret_status = status; -} - -int put_buffer_data_callback(int buffer_size, char *buffer, void *callback_data) -{ - put_buffer_object_callback_data *data = (put_buffer_object_callback_data *) callback_data; - - int toRead = 0; - if (data->buffer_size) { - toRead = ((data->buffer_size > (unsigned) buffer_size) ? - (unsigned) buffer_size : data->buffer_size); - memcpy_s(buffer, buffer_size, data->put_buffer + data->cur_offset, toRead); - } - - uint64_t originalContentLength = data->buffer_size; - data->buffer_size -= toRead; - data->cur_offset += toRead; - if (data->buffer_size) { - printf("%llu bytes remaining ", (unsigned long long)data->buffer_size); - printf("(%d%% complete) ...\n", - (int)(((originalContentLength - data->buffer_size) * DATA_BUF_OFFSET) / originalContentLength)); - } - - return toRead; -} - -obs_status get_properties_callback(const obs_response_properties *properties, void *callback_data) -{ - if (properties->request_id) - printf(" request id: %s \n", properties->request_id); - if (properties->request_id2) - printf(" request id 2: %s \n", properties->request_id2); - if (properties->version_id) - printf(" version id: %s \n", properties->version_id); - if (properties->storage_class) - printf(" storage class: %s \n", properties->storage_class); - if (properties->bucket_location) - printf("bucket location: %s \n", properties->bucket_location); - if (properties->obs_version) - printf(" obs version: %s \n", properties->obs_version); - if (properties->restore) - printf(" restore: %s \n", properties->restore); - if (properties->obs_object_type) - printf(" object type: %s \n", properties->obs_object_type); - if (properties->obs_next_append_position) - printf("append position: %s \n", properties->obs_next_append_position); -} - -int TOKEN_BUCKET = 0; -time_t PRODUCE_TIME = 0; - -uint64_t LIMIT_FLOW_MAX_SPEED = 0; -pthread_mutex_t G_MUTEXTHREADGETTOKEN; // G_MUTEXTHREADGETTOKEN - -void preduce_token() -{ - if (TOKEN_BUCKET == LIMIT_FLOW_MAX_SPEED) - return; - - int times = 0; - - if (PRODUCE_TIME == 0) { - PRODUCE_TIME = time(0); - times = 1; - } else { - time_t cur_time = time(0); - times = (cur_time - PRODUCE_TIME); - if (times > 0) { - PRODUCE_TIME = cur_time; - } - } - - if (times > 0) - TOKEN_BUCKET = LIMIT_FLOW_MAX_SPEED; -} - -int get_token(int buffer_size) -{ - if (0 == LIMIT_FLOW_MAX_SPEED) - return 1; - preduce_token(); - - if (TOKEN_BUCKET < buffer_size) { - printf("has token %d need token %d.\n", TOKEN_BUCKET, buffer_size); - return 0; - } - - TOKEN_BUCKET -= buffer_size; - return 1; -} - -obs_status get_object_data_callback(int buffer_size, const char *buffer, - void *callback_data) -{ - pthread_mutex_lock(&G_MUTEXTHREADGETTOKEN); - while (0 == get_token(buffer_size)) - sleep(1); - - pthread_mutex_unlock(&G_MUTEXTHREADGETTOKEN); - - get_object_callback_data *data = (get_object_callback_data *) callback_data; - size_t wrote = fwrite(buffer, 1, buffer_size, data->outfile); - return ((wrote < (size_t) buffer_size) ? - OBS_STATUS_AbortedByCallback : OBS_STATUS_OK); -} - -void get_object_complete_callback(obs_status status, - const obs_error_details *error, - void *callback_data) -{ - get_object_callback_data *data = (get_object_callback_data *) callback_data; - data->ret_status = status; -} \ No newline at end of file diff --git a/enclave/qtsm-sdk-c/samples/src/test.py b/enclave/qtsm-sdk-c/samples/src/test.py index f5621010a5d0f5bff637b464a7893b517c5a13d5..da9b4dd65135010bd4a0a08b1f1e8271923b2604 100644 --- a/enclave/qtsm-sdk-c/samples/src/test.py +++ b/enclave/qtsm-sdk-c/samples/src/test.py @@ -2,9 +2,13 @@ import json import subprocess +import os +import time +import re + def get_config(): - with open("/root/builder/qtsm-sdk-c/samples/src/config.json") as f: + with open("/home/huawei-qingtian/enclave/qtsm-sdk-c/samples/src/config.json") as f: Config = json.load(f) IAM = Config['IAM'] AK = IAM['AK'] @@ -12,18 +16,86 @@ def get_config(): KeyId = IAM['KeyId'] ProjectId = IAM['ProjectId'] allProjectId = "/v1.0/" + ProjectId + "/kms/" - FileName = Config['FileName'] - Ciphertext = FileName['Ciphertext'] - Plaintext = FileName['Plaintext'] - OBSBucket = FileName['OBSBucket'] Endpoint = Config['Endpoint'] - OBSEndpoint = Endpoint['OBSEndpoint'] KMSEndpoint = Endpoint['KMSEndpoint'] + OBSEndpoint = Endpoint['OBSEndpoint'] VsockSetting = Config['VsockSetting'] VsockPort = VsockSetting['VsockPort'] - return [AK, SK, VsockPort, Ciphertext, Plaintext, OBSBucket, KeyId, KMSEndpoint, OBSEndpoint, allProjectId] + FileKeys = Config['FileKeys'] + CiphertextFile = FileKeys['Ciphertext'] + PlaintextFile = FileKeys['Plaintext'] + BucketName = FileKeys['BucketName'] + return [AK, SK, VsockPort, KeyId, KMSEndpoint, OBSEndpoint, allProjectId, CiphertextFile, PlaintextFile, BucketName] + +Qproxy = "/home/test/qproxy" +QproxyConfig = "/home/test/config.toml" +Obsutil = "/home/test/obsutil" +Cipherpwd = "/home/test/ciphertext" +Plainpwd = "/home/test/plaintext" + + +def wait_for_log_pattern(log_file, pattern, poll_interval=2): + """ + :param log_file + :param pattern + :param poll_interval + """ + time.sleep(poll_interval) + with open(log_file, 'r') as f: + f.seek(0, 2) + while True: + line = f.readline() + if not line: + time.sleep(poll_interval) + continue + if re.search(pattern, line): + print(f"found the pattern: {pattern}") + return res = get_config() -command="/root/builder/qtsm-sdk-c/samples/enclave_demo_bin -a {0} -s {1} -p {2} -c {3} -l {4} -b {5} -k {6} -m {7} -o {8} -j {9}" - .format(res[0], res[1], res[2], res[3], res[4], res[5], res[6], res[7], res[8], res[9]) + +# Pre1: setup the /etc/hosts +command = 'ip link set lo up' +subprocess.call(command, shell=True) +command = 'echo "127.0.0.1 {0}" >> /etc/hosts'.format(res[5]) subprocess.call(command, shell=True) +command = 'echo "127.0.0.1 {0}.{1}" >> /etc/hosts'.format(res[9], res[5]) +subprocess.call(command, shell=True) + +# Pre2: lauch the qproxy enclave +obsendpoint = 'hostname= "{0}"'.format(res[5]) +subprocess.call(f"sed -i '5s/.*/{obsendpoint}/' {QproxyConfig}", shell=True) +process = subprocess.Popen( + ["/home/test/qproxy", "enclave", "--config", QproxyConfig], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + preexec_fn=os.setsid, + shell=False +) + +print(f"qproxy 已启动,PID: {process.pid}") +# 使用示例 +wait_for_log_pattern( + "/var/log/qproxy/enclave.log", + r"Starting outbound proxy connection to.*" +) +print("继续执行后续代码...") + +# Step1: init obsutil config" +command = "{0} config -i={1} -k={2} -e={3}".format(Obsutil, res[0], res[1], res[5]) +subprocess.call(command, shell=True) + +# Step2: get ciphertext from obs +cipher = "obs://{0}/{1}".format(res[9], res[7]) +command = "{0} cp {1} {2}".format(Obsutil, cipher, Cipherpwd) +subprocess.call(command, shell=True) + +# Step3: call kms decryption api +command="/home/huawei-qingtian/enclave/qtsm-sdk-c/samples/enclave_demo_bin -a {0} -s {1} -p {2} -k {3} -m {4} -j {5}".format(res[0], res[1], res[2], res[3], res[4], res[6]) +subprocess.call(command, shell=True) + + +# Step4: put ciphertext to obs +plain = "obs://{0}/{1}".format(res[9], res[8]) +command = "{0} cp {1} {2}".format(Obsutil, Plainpwd, plain) +subprocess.call(command, shell=True) \ No newline at end of file diff --git a/enclave/qtsm-sdk-c/source/kms.c b/enclave/qtsm-sdk-c/source/kms.c index 4c3b1c81c1eed28a49c4f52767e6cc65fec4f383..5e7a43ef48d14100203d562a8310b1d9413cbbc2 100644 --- a/enclave/qtsm-sdk-c/source/kms.c +++ b/enclave/qtsm-sdk-c/source/kms.c @@ -21,6 +21,7 @@ #include "qtsm_lib.h" #define RESERVED_SIZE 2 +#define BITS_SHIFT 8 static const func_API_name_t func_API_info = { .generate_data_key = {CREATE_DATAKEY, POST}, @@ -818,6 +819,15 @@ unsigned long kms_gen_random_blocking_with_proxy(const sig_params_t *sig_params, /* call kms_gen_random api */ status = kms_gen_random_blocking(sig_params, random_len, random); +#ifdef SDK_DEBUG + if (status == KMS_SUCCESS) { + fprintf(stdout, "len of rnd_data is %u\n", *(random->random_len)); + fprintf(stdout, "random data is:\n"); + for (int i = 0; i < *(random->random_len); i++) + fprintf(stdout, "%02x ", random->random[i]); + fprintf(stdout, "\n"); + } +#endif /* close proxy */ close_proxy(&conn); @@ -846,7 +856,14 @@ unsigned long kms_decrypt_data_blocking_with_proxy(const sig_params_t *sig_param /* call kms_decrypt_data api */ status = kms_decrypt_data_blocking(sig_params, handle, data); - +#ifdef SDK_DEBUG + if (status == KMS_SUCCESS) { + printf("plain_data_len is %u\n", *(data->data_out_len)); + for (int i = 0; i < *(data->data_out_len); i++) + printf("%c", data->data_out[i]); + printf("\n"); + } +#endif /* close proxy */ close_proxy(&conn); return status; @@ -861,6 +878,7 @@ unsigned long kms_generate_datakey_blocking_with_proxy(const sig_params_t *sig_p { struct connect_info conn; unsigned long status; + int i; int rc; memset(&conn, 0, sizeof(struct connect_info)); @@ -875,7 +893,26 @@ unsigned long kms_generate_datakey_blocking_with_proxy(const sig_params_t *sig_p /* call kms generate datakey */ status = kms_generate_datakey_blocking(sig_params, handle, datakey_len, datakey); +#ifdef SDK_DEBUG + if (status == KMS_SUCCESS) { + fprintf(stdout, "key_id is:\n"); + for (i = 0; i < *(datakey->key_id_len); i++) + fprintf(stdout, "%c", datakey->key_id[i]); + fprintf(stdout, "\n"); + + fprintf(stdout, "len of plain_datakey is %u\n", *(datakey->plain_key_len)); + fprintf(stdout, "plain_datakey is:\n"); + for (i = 0; i < datakey_len / BITS_SHIFT; i++) + fprintf(stdout, "%02x", datakey->plain_key[i]); + fprintf(stdout, "\n"); + fprintf(stdout, "len of cipher_datakey is %u\n", *(datakey->cipher_key_len)); + fprintf(stdout, "cipher_datakey is:\n"); + for (i = 0; i < *(datakey->cipher_key_len); i++) + fprintf(stdout, "%02x", datakey->cipher_key[i]); + fprintf(stdout, "\n"); + } +#endif /* close proxy */ close_proxy(&conn); return status; diff --git a/enclave/qtsm-sdk-c/tests/vsock_shell/README.md b/enclave/qtsm-sdk-c/tests/vsock_shell/README.md index ebaef34006cf6a48fd4b71478ec511aab2bd0c62..82ff8a585157b65249723e593225176669e0f1d4 100644 --- a/enclave/qtsm-sdk-c/tests/vsock_shell/README.md +++ b/enclave/qtsm-sdk-c/tests/vsock_shell/README.md @@ -23,8 +23,8 @@ Compile the vsock_shell file into an executable file. 2. build nc-vsock After downloading the nc-vsock source code, run the `make` command in the ./nc-vsock directory. -`git clone https://github.com/stefanha/nc-vsock/tree/master` -`make` +`git clone https://github.com/stefanha/nc-vsock.git` +`cd nc-vsock && make` 3. connect to the enclave `./nc-vsock 4 9999` diff --git a/enclave/qtsm-sdk-go/godemo/Dockerfile.go b/enclave/qtsm-sdk-go/godemo/Dockerfile.go deleted file mode 100644 index c36ac5fdd665cdbb94bcbde393f126965e8f3665..0000000000000000000000000000000000000000 --- a/enclave/qtsm-sdk-go/godemo/Dockerfile.go +++ /dev/null @@ -1,57 +0,0 @@ -FROM ubuntu:20.04 - -ENV DEBIAN_FRONTEND=noninteractive - -RUN cp -a /etc/apt/sources.list /etc/apt/sources.list.bak && \ - sed -i "s@http://.*archive.ubuntu.com@http://mirrors.huaweicloud.com@g" /etc/apt/sources.list && \ - sed -i "s@http://.*security.ubuntu.com@http://mirrors.huaweicloud.com@g" /etc/apt/sources.list - -RUN apt-get update -y && \ - apt-get upgrade -y && \ - apt-get install wget vim gcc git make alien libssl-dev libglib2.0-dev curl libjson-c-dev libcurl4-openssl-dev -y - -COPY ./godemo /root/ - -# install golang v1.19 -RUN wget https://golang.google.cn/dl/go1.21.3.linux-amd64.tar.gz && \ - cp go1.21.3.linux-amd64.tar.gz /usr/local/ && \ - cd /usr/local/ && \ - tar xvf go1.21.3.linux-amd64.tar.gz - -ENV GOROOT "/usr/local/go" -ENV GOPATH "/root/.go" -ENV PATH "$PATH:$GOROOT/bin:$GOPATH/bin" - -# install qtsm-lib -RUN mkdir -p rpm && \ - cd rpm && \ - wget http://repo.huaweicloud.com/hce/2.0/debuginfo/x86_64/Packages/libqtsm-devel-1.0.0-3.hce2.x86_64.rpm && \ - wget http://repo.huaweicloud.com/hce/2.0/debuginfo/x86_64/Packages/libcbor-devel-0.9.0-0.hce2.x86_64.rpm && \ - wget http://repo.huaweicloud.com/hce/2.0/updates/x86_64/Packages/libcbor-0.9.0-0.hce2.x86_64.rpm && \ - alien --scripts *.rpm && \ - dpkg -i *.deb && \ - echo "/usr/lib64" >> /etc/ld.so.conf && \ - ldconfig - -# generate qtsm-sdk-c.so -RUN mkdir -p /root/qt && \ - cd /root/qt && \ - git clone https://gitee.com/HuaweiCloudDeveloper/huawei-qingtian.git - -COPY ./Makefile /root/qt/huawei-qingtian/enclave/qtsm-sdk-c/ - -RUN cd /root/qt/huawei-qingtian/enclave/qtsm-sdk-c && \ - sed -i 's/static int kms_attestation_doc_to_json/int kms_attestation_doc_to_json' /root/qt/huawei-qingtian/enclave/qtsm-sdk-c/source/kms.c && \ - sed -i '153i int kms_attestation_doc_to_json(struct stream_buf *att_doc, struct rsa_keypair **user_pubkey, char **att_enbase64, unsigned int *att_enbase64_len);' /root/qt/huawei-qingtian/enclave/qtsm-sdk-c/include/kms.h && \ - make && \ - cp lib/libqtsmsdkc.so /usr/lib64/libqtsmsdkc.so && \ - cp -rf include /usr/include/qtsmsdkc && \ - echo "/usr/lib64" >> /etc/ld.so.conf && \ - ldconfig - -COPY ./directShell /root/ - -RUN cd /root/godemo && \ - go build -o main main.go - -CMD ["/root/directShell"] diff --git a/enclave/qtsm-sdk-go/godemo/Makefile b/enclave/qtsm-sdk-go/godemo/Makefile deleted file mode 100644 index 80c2dd932947c32b34c55455cb3fb3a46bba0330..0000000000000000000000000000000000000000 --- a/enclave/qtsm-sdk-go/godemo/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -#!/bin/bash - -ifeq (,$(TOP_DIR)) -TOP_DIR := $(shell pwd)/.. -CURRENT_DIR := $(shell pwd) -else -CURRENT_DIR := $(TOP_DIR)/qtsm-sdk-c -endif - -#########################COM LIB################################# -COM_LIBS += -lssl -lcrypto -COM_LIBS += -lglib-2.0 -COM_LIBS += -lcurl -COM_LIBS += -ljson-c -COM_LIBS += -lqtsm -COM_LIBS += -lpthread -COM_LIBS += -lcbor - -######################### COM INCLUDE ################################# -COM_INCLUDE_PATH := -I $(CURRENT_DIR)/include/ -COM_INCLUDE_PATH += -I /usr/include/ -COM_INCLUDE_PATH += -I /usr/include/glib-2.0/ -COM_INCLUDE_PATH += -I /usr/lib/x86_64-linux-gnu/glib-2.0/include -COM_INCLUDE_PATH += -I /usr/lib64/glib-2.0/include -COM_INCLUDE_PATH += -I /usr/local/include/cjson -COM_INCLUDE_PATH += -I /usr/include/cbor - -###########################QTSM_SAM############################### -QTSM_SDK_SRC := $(shell find $(CURRENT_DIR)/source -name '*.c') -QTSM_SDK_OBJ = $(shell find $(CURRENT_DIR) -name '*.o') - -QTSM_LIB_PATH += -L $(TOP_DIR)/qtsm/lib -QTSM_LIB_PATH += -L /usr/bin -QTSM_LIB_PATH += -L /usr/lib64 -QTSM_INCLUDE_PATH := -I $(TOP_DIR)/qtsm/include - -ifeq (,$(CC)) -CC := gcc -endif - -GCC_CHOOSE := -W -Os -g -GCC_CHOOSE += -Wl,-z,relro,-z,now -GCC_CHOOSE += -Wl,-z,noexecstack -GCC_CHOOSE += -fstack-protector-strong -shared -fPIC -g -DSDK_DEBUG - -lib_dir := $(CURRENT_DIR)/lib -$(shell if [ ! -d $(lib_dir) ];then mkdir -p $(lib_dir); fi) - -target = ${CURRENT_DIR}/lib/libqtsmsdkc.so - -all: ${QTSM_SDK_SRC} - $(CC) $(GCC_CHOOSE) $(COM_INCLUDE_PATH) $(QTSM_INCLUDE_PATH) $(QTSM_SDK_SRC) $(COM_LIBS) -o $(target) - -clean: - rm -rf $(target) diff --git a/enclave/qtsm-sdk-go/godemo/README.md b/enclave/qtsm-sdk-go/godemo/README.md deleted file mode 100644 index a0054de7de1226c776f8e107026c748460e6a740..0000000000000000000000000000000000000000 --- a/enclave/qtsm-sdk-go/godemo/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# Cgo demo - -This demo is developed based on the requirements of the cgo project to run in enclave, and mainly tests the interface of fetching attesationdoc, GenerateDataKey, encryption and decryption, and generating random numbers in the container. - -# Dockerfile.sdk -Before using this Dockerfile, copy the Makefile file to the same directory as the godemo project. -Then build this file to make the docker image needed for qingtian eif. - -# Makefile -This file is used to compile the c code in enclave required by the cgo project. The compilation process is already done in the Dockerfile, you just need to place it in the horizontal directory of godemo. - -# nc-vsock -This tool gives you a way to log in to the enclave vm, you can use the `./nc-vsock [-l [-t ] | ]` in the father vm to log in. -You can get the tool source code at the following link: -https://github.com/stefanha/nc-vsock/tree/master - -# directShell -The directShell code file modified based on vsock connection adaptation exists in the /enclave/qtsm-sdk-c/test/vsock_shell/. You can use the source code for compilation. diff --git a/enclave/qtsm-sdk-go/godemo/go.mod b/enclave/qtsm-sdk-go/godemo/go.mod deleted file mode 100644 index bd0d8a9a61ddcf9908d625068643eebe80101f38..0000000000000000000000000000000000000000 --- a/enclave/qtsm-sdk-go/godemo/go.mod +++ /dev/null @@ -1 +0,0 @@ -module godemo \ No newline at end of file diff --git a/enclave/qtsm-sdk-go/godemo/main.go b/enclave/qtsm-sdk-go/godemo/main.go deleted file mode 100644 index 054e15c87c43c1af71ab918496c219bbdb7886d9..0000000000000000000000000000000000000000 --- a/enclave/qtsm-sdk-go/godemo/main.go +++ /dev/null @@ -1,79 +0,0 @@ -/* - * The Entrance of godemo - * - * Copyright (c) Huawei Technologies Co., Ltd. 2023. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ -package main - -import ( - "godemo/utils" - "log" -) - -var DataKey map[string][]byte - -func main() { - log.Printf("Hello tss ego demo!") - - // test ego enclave - inEnclave() - // test ego encrypt - decrypt() - // test get random - genRandom() - - log.Printf("Exit tss ego demo!") -} - -func inEnclave() { - report, err := utils.GetSelfReport() - if err != nil { - log.Printf("Not in enclave: %v", err) - return - } - log.Printf("The tss ego demo is running in the Enclave, attestation doc len : %d\n", len(report)) - return -} - -func enDecryptWithProductKey(msg []byte) { - productKey, ok := DataKey["ProductKey"] - if !ok { - productKey, _ = utils.InitDataKey("ProductKey") - if productKey == nil { - log.Printf("init productkey err\n") - return - } - } - DataKey["ProductKey"] = productKey - cipher, err := utils.Encryptdata(msg, productKey) - if err != nil { - log.Printf("cannot encrypt the message") - return - } - plain, err := utils.Decryptdata(cipher, DataKey["ProductKey"]) - if err != nil { - log.Printf("cannot decrypt data") - return - } - log.Printf("after encrypt and decrypt, message: %s\n", plain) -} - -func decrypt() { - log.Printf("Test ego product encrypt!") - msg := []byte("hello cobo and qingtian tss demo") - log.Printf("msg:len %d\n", len(msg)) - DataKey = make(map[string][]byte) - enDecryptWithProductKey(msg) -} - -func genRandom() { - log.Printf("Test get random!") - report, err := utils.TestGenRandom() - if err != nil { - log.Printf("Not in enclave: %v\n", err) - return - } - log.Printf("Get random success : %s\n", report) - return -} diff --git a/enclave/qtsm-sdk-go/godemo/test-main.go b/enclave/qtsm-sdk-go/godemo/test-main.go deleted file mode 100644 index 86c83e74b141580993051276c5fa2b1fe5c1bee5..0000000000000000000000000000000000000000 --- a/enclave/qtsm-sdk-go/godemo/test-main.go +++ /dev/null @@ -1,25 +0,0 @@ -/* - * test main demo - * - * Copyright (c) Huawei Technologies Co., Ltd. 2023. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ -package main - -import ( - "godemo/utils" - "fmt" -) - -var DataKey map[string][]byte - -func main() { - DataKey = make(map[string][]byte) - tmpkey, err := utils.InitDataKey("ProductKey") - if err != nil { - fmt.Printf("main.go init err") - return - } - DataKey["ProductKey"] = tmpkey - fmt.Println("ProductKey:", DataKey["ProductKey"]) -} diff --git a/enclave/qtsm-sdk-go/godemo/utils/attestation/attestation.go b/enclave/qtsm-sdk-go/godemo/utils/attestation/attestation.go deleted file mode 100644 index 312b72fa8fdcda0c3f91383d2774cccc7413b5a6..0000000000000000000000000000000000000000 --- a/enclave/qtsm-sdk-go/godemo/utils/attestation/attestation.go +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file implements the get_attestation_doc interface that calls C code in the go function, - * which facilitates the transmission of go input data to the corresponding C interface, - * and the transmission of the data returned by the C interface back to go. - * - * Copyright (c) Huawei Technologies Co., Ltd. 2023. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ -package attestation - -/* -#cgo CFLAGS:-I/usr/include/qtsmsdkc -#cgo LDFLAGS:-L/usr/lib64 -lqtsmsdkc -#include "attestation.h" -#include "cms_comm.h" -#include "kms.h" -#include -#include - -char *test_get_att() { - char *att_enbase64 = NULL; - unsigned int att_enbased64_len = NULL; - struct rsa_keypair *user_pubkey = NULL; - struct stream_buf att_doc = {0}; - int rc = 0; - - rc = kms_attestation_doc_to_json(&att_doc, &user_pubkey, &att_enbase64, &att_enbased64_len); - if (rc != 0) { - printf("get attestation doc err: %d \n", rc); - if (att_enbase64) { - free(att_enbase64); - } - return NULL; - } - printf("get attestation:\n"); - printf("%s\n", att_enbase64); - printf("csdk len : %d\n\n", att_enbased64_len); - fflush(stdout); - - char *restr = malloc(att_enbased64_len + 1); - strcpy(restr, att_enbase64); - free(att_enbase64); - - return restr; -} - -*/ -import "C" -import ( - "unsafe" - "fmt" - "errors" -) - -func G_qtsm_get_attesationdoc() ([]byte, error) { - fmt.Println("starts to get qtsm attestation doc") - cStr := C.test_get_att(); - if cStr != nil { - Goatt := C.GoString(cStr) - fmt.Println(len(Goatt)) - re := make([]byte, len(Goatt)) - fmt.Println("attestation doc in golang") - for i:= 0; i < len(Goatt); i++ { - fmt.Printf("%c", Goatt[i]) - re[i] = Goatt[i] - } - fmt.Println("\n") - C.free(unsafe.Pointer(cStr)) - return re, nil - } - - return nil, errors.New("get attestation doc error") -} diff --git a/enclave/qtsm-sdk-go/godemo/utils/encrypt/encrypt.go b/enclave/qtsm-sdk-go/godemo/utils/encrypt/encrypt.go deleted file mode 100644 index 1bfddc5aea1f578c98b4737be401a26bad7b5d7a..0000000000000000000000000000000000000000 --- a/enclave/qtsm-sdk-go/godemo/utils/encrypt/encrypt.go +++ /dev/null @@ -1,292 +0,0 @@ -/* - * This file implements the generate_datakey interface and gen_random interface that calls C code in the go function, - * which facilitates the transmission of go input data to the corresponding C interface, - * and the transmission of the data returned by the C interface back to go. - * - * Copyright (c) Huawei Technologies Co., Ltd. 2023. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ -package encrypt - -/* -#cgo CFLAGS:-I/usr/include/qtsmsdkc -#cgo LDFLAGS:-L/usr/lib64 -lqtsmsdkc -#include "kms.h" -#include "cms_comm.h" -#include "enclave_proxy.h" -#include -#include - -char *test_seal_with_key(char* ak, char* sk, char* host, - char* uri_prefix, char* keyid, int vsock_cid, int vsock_port) -{ - datakey_t res_datakey = {0}; - unsigned long status; - unsigned int res_plain_key_len = 32 * 8; - unsigned int res_cipher_key_len = 1000; - unsigned int res_key_id_len = 40; - char res_key_id[res_key_id_len]; - unsigned char res_plain_key[res_plain_key_len]; - unsigned char res_cipher_key[res_cipher_key_len]; - - memset(res_key_id, 0, sizeof(res_key_id)); - memset(res_plain_key, 0, sizeof(res_plain_key)); - memset(res_cipher_key, 0, sizeof(res_cipher_key)); - res_datakey.key_id = res_key_id; - res_datakey.key_id_len = &res_key_id_len; - res_datakey.plain_key = res_plain_key; - res_datakey.plain_key_len = &res_plain_key_len; - res_datakey.cipher_key = res_cipher_key; - res_datakey.cipher_key_len = &res_cipher_key_len; - - sig_params_t params; - keyid_handle_t handle; - int rc = 0; - struct connect_info conn; - memset(&conn, 0, sizeof(struct connect_info)); - sig_params_init(¶ms); - - sig_str_t ak_s = sig_str(ak); - sig_str_t sk_s = sig_str(sk); - sig_str_t host_s = sig_str(host); - sig_str_t uri_prefix_s = sig_str(uri_prefix); - - params.key = ak_s; - params.secret = sk_s; - params.host = host_s; - params.uri_prefix = uri_prefix_s; - - handle.key_id = keyid; - handle.len = strlen(keyid); - - rc = setup_proxy(&conn, vsock_cid, vsock_port); - if (rc != 0) { - printf("setup_proxy error.\n"); - fflush(stdout); - close_proxy(&conn); - return NULL; - } - - status = kms_generate_datakey_blocking(¶ms, &handle, res_plain_key_len, &res_datakey); - if (status != 0) { - printf("kms gen datakey api failed.\n"); - fflush(stdout); - close_proxy(&conn); - return NULL; - } - - char *res_p = NULL; - res_p = malloc((*(res_datakey.plain_key_len) + 1) * sizeof(char) / 8); - memset(res_p, (*(res_datakey.plain_key_len) + 1) * sizeof(char) / 8, 0); - int i = 0; - for (i = 0; i < *(res_datakey.plain_key_len) / 8; i++) { - printf("%02x", res_datakey.plain_key[i]); - res_p[i] = res_datakey.plain_key[i]; - } - res_p[i] = 0; - close_proxy(&conn); - return res_p; -} - -char *test_gen_random(char* ak, char* sk, char* host, - char* uri_prefix, char* keyid, int vsock_cid, int vsock_port) -{ - unsigned long status; - random_data_t rnd_data; - unsigned int random_len = 256 >> 3; - unsigned char random[random_len]; - unsigned int i; - - memset(random, 0, sizeof(random)); - rnd_data.random = random; - rnd_data.random_len = &random_len; - - sig_params_t params; - int rc = 0; - struct connect_info conn; - memset(&conn, 0, sizeof(struct connect_info)); - sig_params_init(¶ms); - - sig_str_t ak_s = sig_str(ak); - sig_str_t sk_s = sig_str(sk); - sig_str_t host_s = sig_str(host); - sig_str_t uri_prefix_s = sig_str(uri_prefix); - - params.key = ak_s; - params.secret = sk_s; - params.host = host_s; - params.uri_prefix = uri_prefix_s; - - rc = setup_proxy(&conn, vsock_cid, vsock_port); - if (rc != 0) { - printf("setup_proxy error.\n"); - fflush(stdout); - close_proxy(&conn); - return NULL; - } - - status = kms_gen_random_blocking(¶ms, random_len, &rnd_data); - if (status != 0) { - printf("kms gen random api failed.\n"); - fflush(stdout); - close_proxy(&conn); - return NULL; - } - - char *res_p = NULL; - res_p = malloc((*(rnd_data.random_len) + 1) * sizeof(char) / 8); - memset(res_p, (*(rnd_data.random_len) + 1) * sizeof(char) / 8, 0); - for (i = 0; i < *(rnd_data.random_len) / 8; i++) { - printf("%02x", rnd_data.random[i]); - res_p[i] = rnd_data.random[i]; - fflush(stdout); - } - res_p[i] = 0; - close_proxy(&conn); - return res_p; -} - -*/ -import "C" -import ( - "os" - "bytes" - "crypto/rand" - "unsafe" - "fmt" - "errors" - "crypto/aes" - "crypto/cipher" - "encoding/base64" -) - -func Get_datakey() ([]byte, error){ - ak := os.Getenv("HUAWEICLOUD_SDK_AK") - sk := os.Getenv("HUAWEICLOUD_SDK_SK") - host := os.Getenv("HUAWEICLOUD_SDK_HOST") - uri_prefix := os.Getenv("HUAWEICLOUD_SDK_URI") - keyid := os.Getenv("HUAWEICLOUD_SDK_KEY") - vsock_cid := C.int(3) - vsock_port := C.int(8000) - datakey := C.test_seal_with_key(ak, sk, host, uri_prefix, keyid, vsock_cid, vsock_port) - if datakey == nil { - fmt.Println("get seal_with_key err") - return nil, errors.New("seal_with_key err") - } - length := C.strlen(datakey) - goByteskey := (*[1 << 30]byte)(unsafe.Pointer(datakey))[:length:length] - fmt.Println("\ngetting data key from kms:") - for i := 0; i < int(length); i++ { - fmt.Printf("%02x", goByteskey[i]) - } - fmt.Printf("\n") - C.free(unsafe.Pointer(datakey)) - - return goByteskey, nil -} - -func EncryptWithKey(plaintext []byte, key []byte) ([]byte, error) { - fmt.Println("key_len: %d", len(key)) - ciphertext, err := AesEncrypt(plaintext, key) - if err != nil { - fmt.Println(err) - return nil, err - } - fmt.Println("encry_key: %s", key) - fmt.Println(base64.StdEncoding.EncodeToString(ciphertext)) - - return ciphertext, nil -} - -func AesEncrypt(plaintext []byte, key []byte) ([]byte, error) { - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - - // PKCS7 populate - padding := aes.BlockSize - len(plaintext)%aes.BlockSize - padtext := append(plaintext, bytes.Repeat([]byte{byte(padding)}, padding)...) - - ciphertext := make([]byte, aes.BlockSize+len(padtext)) - iv := ciphertext[:aes.BlockSize] - if _, err := rand.Read(iv); err != nil { - return nil, err - } - - mode := cipher.NewCBCEncrypter(block, iv) - mode.CryptBlocks(ciphertext[aes.BlockSize:], padtext) - - return ciphertext, nil -} - -func DecryptWithKey(key []byte, ciphertext []byte) ([]byte, error) { - fmt.Println("decry_key: %s", key) - plaintext, err := AesDecrypt(ciphertext, key) - if err != nil { - fmt.Println(err) - return nil, err - } - fmt.Println(string(plaintext)) - - return plaintext, nil -} - -func AesDecrypt(ciphertext []byte, key []byte) ([]byte, error) { - if len(key) != 32 { - key = key[:32] - } - - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - - if len(ciphertext) < aes.BlockSize { - return nil, errors.New("ciphertext too short") - } - - iv := ciphertext[:aes.BlockSize] - ciphertext = ciphertext[aes.BlockSize:] - - if len(ciphertext)%aes.BlockSize != 0 { - return nil, errors.New("ciphertext is not a multiple of the block size") - } - - mode := cipher.NewCBCDecrypter(block, iv) - - // encrypt - plaintext := make([]byte, len(ciphertext)) - mode.CryptBlocks(plaintext, ciphertext) - - // PKCS7 unpopulate - padding := int(plaintext[len(plaintext)-1]) - - return plaintext[:len(plaintext)-padding], nil -} - -func G_gen_random() ([]byte, error) { - fmt.Println("starts to get random") - ak := os.Getenv("HUAWEICLOUD_SDK_AK") - sk := os.Getenv("HUAWEICLOUD_SDK_SK") - host := os.Getenv("HUAWEICLOUD_SDK_HOST") - uri_prefix := os.Getenv("HUAWEICLOUD_SDK_URI") - keyid := os.Getenv("HUAWEICLOUD_SDK_KEY") - vsock_cid := C.int(3) - vsock_port := C.int(8000) - cStr := C.test_gen_random(ak, sk, host, uri_prefix, keyid, vsock_cid, vsock_port) - if cStr == nil { - fmt.Println("gen random err") - return nil, errors.New("gen random err") - } - length := C.strlen(cStr) - goRan := (*[1 << 30]byte)(unsafe.Pointer(cStr))[:length:length] - fmt.Println("\ngetting random from kms:") - for i := 0; i < int(length); i++ { - fmt.Printf("%02x", goRan[i]) - } - fmt.Printf("\n") - C.free(unsafe.Pointer(cStr)) - - return goRan, nil -} diff --git a/enclave/qtsm-sdk-go/godemo/utils/utils.go b/enclave/qtsm-sdk-go/godemo/utils/utils.go deleted file mode 100644 index 9309399b03a2e5fc9e3b7cdccac78374a0ece5e0..0000000000000000000000000000000000000000 --- a/enclave/qtsm-sdk-go/godemo/utils/utils.go +++ /dev/null @@ -1,67 +0,0 @@ -/* - * - * Copyright (c) Huawei Technologies Co., Ltd. 2023. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ -package utils - - -import "C" -import ( - "errors" - "godemo/utils/attestation" - "godemo/utils/encrypt" - "log" -) - - -func GetSelfReport() ([]byte, error) { - att_doc, err := attestation.G_qtsm_get_attesationdoc() - if err != nil { - return nil, errors.New("get attestation doc error") - } - log.Printf("GetSelfReport successfully") - return att_doc, nil -} - -func GenerateDataKey() ([]byte, error) { - datakey, err := encrypt.Get_datakey() - if err != nil { - return nil, errors.New("genereate datakey error") - } - log.Printf("GenerateDataKey successfully") - return datakey, nil -} - -func InitDataKey(keyId string) ([]byte, error) { - if len(keyId) == 0 { - log.Printf("invalid keyId") - return nil, errors.New("Invalid keyId") - } - return encrypt.Get_datakey() -} - -func Encryptdata(plaintext []byte, key []byte) ([]byte, error){ - if len(plaintext) == 0 || len(key) == 0 { - log.Printf("invalid parameters") - return nil, errors.New("invalid parameters") - } - return encrypt.EncryptWithKey(plaintext, key) -} - -func Decryptdata(ciphertext []byte, key []byte) ([]byte, error) { - if len(ciphertext) == 0 || len(key) == 0 { - log.Printf("invalid parameters") - return nil, errors.New("invalid parameters") - } - return encrypt.DecryptWithKey(key, ciphertext) -} - -func TestGenRandom() ([]byte, error) { - random, err := encrypt.G_gen_random() - if err != nil { - return nil, errors.New("get random error") - } - log.Printf("GetRandom successfully") - return random, nil -} diff --git a/enclave/qtsm-sdk-java/kms-cms-java/Dockerfile.kms b/enclave/qtsm-sdk-java/kms-cms-java/Dockerfile.kms index edb11f2d8f0cf19f02eb142677060dbabb98bee9..961ba8163fb6c147fe251f0e85e0564f55bb2ce3 100644 --- a/enclave/qtsm-sdk-java/kms-cms-java/Dockerfile.kms +++ b/enclave/qtsm-sdk-java/kms-cms-java/Dockerfile.kms @@ -1,22 +1,25 @@ -FROM ubuntu:16.04 AS base-img -RUN cp -a /etc/apt/sources.list /etc/apt/sources.list.bak -# -RUN cat /dev/null > /etc/apt/sources.list -# +FROM ubuntu:22.04 AS base-img + +# If u use it in Chinese mainland, u can remove sources.list firstly, +# and use the local apt source +# RUN cp -a /etc/apt/sources.list /etc/apt/sources.list.bak +# RUN cat /dev/null > /etc/apt/sources.list + WORKDIR /home/builder -# COPY ./ /home/builder/ COPY ./enclave/qtsm-sdk-java/kms-cms-java/scripts/build_kms_demo.sh /home/builder/scripts/ -COPY ./enclave/qtsm-sdk-c/samples/scripts/env_cfg.sh ./ -RUN chmod +x ./env_cfg.sh && \ - /bin/sh -c ./env_cfg.sh +# The local apt source to speedup installing packages +#COPY ./enclave/qtsm-sdk-c/samples/scripts/env_cfg.sh ./ +#RUN chmod +x ./env_cfg.sh && \ +# /bin/sh -c ./env_cfg.sh + +#RUN echo "7.223.217.116 cmc-cd-mirror.rnd.huawei.com" >> /etc/hosts && \ +# echo "7.223.217.116 mirrors.tools.huawei.com" >> /etc/hosts && \ +# rm -rf /var/lib/apt/lists/* -RUN echo "7.223.217.116 cmc-cd-mirror.rnd.huawei.com" >> /etc/hosts && \ - echo "7.223.217.116 mirrors.tools.huawei.com" >> /etc/hosts && \ - rm -rf /var/lib/apt/lists/* && \ - apt-get update --fix-missing -o Acquire::http::No-Cache=True && \ +RUN apt-get update --fix-missing -o Acquire::http::No-Cache=True && \ apt-get install -y gcc && \ apt-get install -y make && \ apt-get install -y tar && \ @@ -36,7 +39,35 @@ RUN echo "7.223.217.116 cmc-cd-mirror.rnd.huawei.com" >> /etc/hosts && \ apt-get install -y unzip ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64 ENV PATH $PATH:$JAVA_HOME/bin -RUN echo $JAVA_HOME -RUN chmod +x scripts/build_kms_demo.sh && \ - /bin/sh -c scripts/build_kms_demo.sh +# compile and add the vsock-server for debuging +RUN cd /home/builder/enclave/qtsm-sdk-c/tests/vsock_shell && \ + gcc vsock_shell.c -o directShell && \ + cp /home/builder/enclave/qtsm-sdk-c/tests/vsock_shell/directShell /root/directShell && \ + chmod +x /root/directShell + +# compile qtsm-lib +RUN cd /home/builder/enclave/qtsm/lib && \ + make clean && \ + mkdir /home/builder/enclave/qtsm/lib/../output/ && \ + make + +# compile kms-cms-java +RUN cd /home/builder/enclave/qtsm-sdk-java/kms-cms-java && \ + make + +# compile java-kms-test +RUN cd /home/builder/enclave/qtsm-sdk-java/kms-cms-java && \ + javac -encoding UTF-8 -classpath ./lib/lombok-1.18.26.jar:./lib/junit-4.13.1.jar ./com/huawei/src/model/*.java ./com/huawei/src/kms/*.java ./com/huawei/src/test/*.java -d ./target && \ + cp -r META-INF/ target/ + +RUN cd /home/builder/scripts/ && \ + chmod +x build_kms_demo.sh + +ENV HUAWEICLOUD_SDK_AK $HUAWEICLOUD_SDK_AK +ENV HUAWEICLOUD_SDK_SK $HUAWEICLOUD_SDK_SK + +# u can perform it directly; +# Or u can launch vsock-server in the enclave firstly, and performs the real binary manually +# CMD /bin/sh -c /home/builder/scripts/build_kms_demo.sh +CMD /root/directShell \ No newline at end of file diff --git a/enclave/qtsm-sdk-java/kms-cms-java/README.md b/enclave/qtsm-sdk-java/kms-cms-java/README.md index 784206eefb4ea33e74503785de96ae896ed0bfd8..8952ba71f48ab9d85f9f1a6674670e133e8feb7e 100644 --- a/enclave/qtsm-sdk-java/kms-cms-java/README.md +++ b/enclave/qtsm-sdk-java/kms-cms-java/README.md @@ -8,7 +8,7 @@ There is three interfaces in Qingtian Enclaves SDK for Java, and Java interfaces Java SDK is developed by JNI, it calls C SDK. so before invoking a Java interface, it is necessary to install the required dependencies for the corresponding C interface. -please put `lombok-1.18.26.jar` into `kms-cms-java/src/lib` directory. +please put `lombok-1.18.26.jar` `junit-4.13.1.jar` into `kms-cms-java/lib` directory. ## Prerequests: @@ -18,6 +18,8 @@ please put `lombok-1.18.26.jar` into `kms-cms-java/src/lib` directory. 3. You need to install the necessary software, including `gcc`, `glib2-devel`, `json-c-devel`, ` openssl-devel`, `libcurl-devel`, `libcbor-devel`, `make`, `virtio-qtbox`. 4. At the same time, it is necessary to install Qingtian Enclave related software, containing `qt-enclave-bootstrap` and `qingtian-tools` in this virtual machine. 5. Costomize isolated resource for Qingtian Enclave in `/etc/qingtian/enclave/qt-enclave-env.conf` and start the resource isolation service using the commad: `systemctl start qt-enclave-env.service && systemctl enable qt-enclave-env.service` +6. You need to get your account's `$AK` and `$SK` to replace the `$HUAWEICLOUD_SDK_AK` and `$HUAWEICLOUD_SDK_SK` in the`Dockerfile.kms`. +7. You also need to get KMS endpoint in your region to replace the `host` variable in the `kms-cms-java/com/huawei/src/test/TestKmsCmsProxy.java`. And you also need to use the real `$projectID` in the `uriPrefix` variable. The variable `keyid` is also needed to replaced by the real keyID from your KMS service. ## Quick Start @@ -26,9 +28,17 @@ please put `lombok-1.18.26.jar` into `kms-cms-java/src/lib` directory. ```sh build_img.sh``` 3. we can get kms-demo.eif in qtsm-sdk-java/kms-cms-java/scripts 4. make sure qt-enclave-env.service is running -5. Launch a Qingtian Enclave: +5. You need to lauch the proxy in the primary VM firstly: +`/usr/local/bin/qingtian/enclave/qt_proxy -l 8000 -a ${kms endpoint} -p 443 &` +Please make sure that the kms endpoint is valid for you. Maybe you can check it in this website: +`https://developer.huaweicloud.com/intl/zh-cnendpoint` +6. Launch a Qingtian Enclave: `qt enclave start --cpus {CPU number} --mem {memory} --eif ${CUR_DIR}/kms-demo.eif --cid 4` -6. run ```qt enclave query --enclave-id 0``` +7. run ```qt enclave query --enclave-id 0``` +8. If you have launched `directShell` in the enclave for debuging, you can use `nc-vsock` to login into the enclave to perform commands manually. And we have compiled the `nc-vsock` in the `scripts\build_image.sh`. You can connect to the enclave following: +`${Workplace}/huawei-qingtian/nc-vsock/nc-vsock 4 9999` +9. After logining into the enclave, you can perform this test manually: +`/home/builder/scripts/build_kms_demo.sh` ### Linux: diff --git a/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/kms/LibCmsKmsProxyNative.java b/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/kms/LibCmsKmsProxyNative.java index 7422d758ab2c4c5bba73b98cae8e2cc23f90de53..efdb03ffaa5318a0b8a2c68321b1cf8b102090bb 100644 --- a/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/kms/LibCmsKmsProxyNative.java +++ b/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/kms/LibCmsKmsProxyNative.java @@ -43,10 +43,11 @@ public class LibCmsKmsProxyNative { * @param input The ciphertext to decrypt * @param vsockCid vsock * @param vsockPort port + * @param data_out_len plaintext data length * @return the plaintext output as the call and The status of the operation. * @throws * @author zou wei * @date 2023/07/11 20:14 */ - public static native ReturnChars kmsDecryptDataBlockingWithProxy(SigParams sigParams, KeyIdHandle keyIdHandle, String input, int vsockCid, int vsockPort); + public static native ReturnChars kmsDecryptDataBlockingWithProxy(SigParams sigParams, KeyIdHandle keyIdHandle, String input, int vsockCid, int vsockPort, int data_out_cap); } \ No newline at end of file diff --git a/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/model/DataKey.java b/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/model/DataKey.java index 73181bb28147495f6e8620f1004f8f815eae1a7c..0834c399d50a2e7b3b1abf04f4ba26303fcddf84 100644 --- a/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/model/DataKey.java +++ b/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/model/DataKey.java @@ -10,4 +10,23 @@ public class DataKey { private int plainKeyLen; private byte[] cipherKey; private int cipherKeyLen; + + + static String bytesToHexPretty(byte[] bytes) { + StringBuilder sb = new StringBuilder(); + for (byte b : bytes) { + sb.append(String.format("%02x", b)); + } + return sb.toString().trim(); + } + + public void printPlainKey() { + String plainkey = bytesToHexPretty(this.plainKey); + System.out.println(plainkey); + } + + public void printCipherKey() { + String cipherKey = bytesToHexPretty(this.cipherKey); + System.out.println(cipherKey); + } } \ No newline at end of file diff --git a/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/model/ReturnChars.java b/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/model/ReturnChars.java index 2f6c1caa3dab684b29e8e8ea151469c839c3d66c..d575c701ca0e4568056b210b7b00bf68c67cd5b4 100644 --- a/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/model/ReturnChars.java +++ b/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/model/ReturnChars.java @@ -1,5 +1,5 @@ package com.huawei.src.model; - +import java.util.Arrays; import lombok.Data; @Data @@ -8,10 +8,7 @@ public class ReturnChars { public int rc; public void printDecryptData(){ - StringBuilder sb = new StringBuilder(); - for (char c : this.returnInfo) { - sb.append(String.format("%02x", (int) c)); - } - System.out.println(sb.toString()); + String str = new String(this.returnInfo); + System.out.println(str); } } \ No newline at end of file diff --git a/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/model/ReturnRandomDatas.java b/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/model/ReturnRandomDatas.java index eb372e27310ba4ad2313b236d5841def91895ed2..7dfccb94690d1c669904bb2b8702f7ec5c2b8fe5 100644 --- a/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/model/ReturnRandomDatas.java +++ b/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/model/ReturnRandomDatas.java @@ -6,4 +6,17 @@ import lombok.Data; public class ReturnRandomDatas { private byte[] returnInfo; private int rc; + + static String bytesToHexPretty(byte[] bytes) { + StringBuilder sb = new StringBuilder(); + for (byte b : bytes) { + sb.append(String.format("%02x", b)); + } + return sb.toString().trim(); + } + + public void printReturnInfo() { + String returnInfo = bytesToHexPretty(this.returnInfo); + System.out.println(returnInfo); + } } \ No newline at end of file diff --git a/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/test/TestKmsCmsProxy.java b/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/test/TestKmsCmsProxy.java index 3591892a16d7e744e324c179c2d58016d9694c66..5ab9217fa9ebf8c9339da1f6a7eaf2d8bb66331c 100644 --- a/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/test/TestKmsCmsProxy.java +++ b/enclave/qtsm-sdk-java/kms-cms-java/com/huawei/src/test/TestKmsCmsProxy.java @@ -22,12 +22,14 @@ public class TestKmsCmsProxy { String ak = System.getenv("HUAWEICLOUD_SDK_AK"); String sk = System.getenv("HUAWEICLOUD_SDK_SK"); /* KMS tenant-side domain name */ - String host = System.getenv("HUAWEICLOUD_SDK_HOST"); + // String host = System.getenv("HUAWEICLOUD_SDK_HOST"); + String host = "kms.xxx.myhuaweicloud.com"; /* The security officer needs to purchase an elastic cloud server with the enclave service. * The security officer needs to go to the unified identity authentication service center of Huawei Cloud * to create a new project.,to get project ID, then uriPrefix is /v1.0/{project ID}/kms/ */ - String uriPrefix = System.getenv("HUAWEICLOUD_SDK_URI"); + // String uriPrefix = System.getenv("HUAWEICLOUD_SDK_URI"); + String uriPrefix = "/v1.0/{project ID}/kms/"; try { if (ak == null || ak.isEmpty()) { throw new RuntimeException("Failed to get HUAWEICLOUD_SDK_AK environment variable."); @@ -44,11 +46,14 @@ public class TestKmsCmsProxy { } SigParams params = new SigParams(ak, sk, host, uriPrefix); /* Create a new key in the kms service for data encryption and obtain the key ID */ - String keyid = System.getenv("HUAWEICLOUD_SDK_KEY"); + // String keyid = System.getenv("HUAWEICLOUD_SDK_KEY"); + String keyid = "xxxxxx-xxxxxx-xxxxx-xxxxx"; KeyIdHandle keyIdHandle = new KeyIdHandle(keyid, keyid.length()); int rndLen = 256; + /* plainkey_len = 512 / 8 */ int datakey_length = 512; int data_out_length = 1000; + /* cipher key arrays caps */ int res_cipher_key_len = 1000; int res_key_id_len = 40; testKmsGenRandomWithProxy(params, rndLen, vsockCid, vsockPort); @@ -68,7 +73,7 @@ public class TestKmsCmsProxy { } System.out.println(funTAG + "the length of random data is " + returnRandomDatas.getReturnInfo().length); System.out.println(funTAG + "the randomData is:"); - System.out.println(funTAG + Arrays.toString(returnRandomDatas.getReturnInfo())); + returnRandomDatas.printReturnInfo(); } catch (Exception e) { System.out.println(e.getMessage()); } @@ -84,8 +89,12 @@ public class TestKmsCmsProxy { } assertNotNull(dataKey.getKeyId()); System.out.println(funTAG + " keyId is " + new String(dataKey.getKeyId())); - System.out.println(funTAG + " plainDatakey is: " + Arrays.toString(dataKey.getPlainKey())); - System.out.println(TAG + funTAG + " cipherDatakey is: " + Arrays.toString(dataKey.getCipherKey())); + System.out.println(funTAG + " plainDatakey length is: " + dataKey.getPlainKeyLen()); + System.out.println(funTAG + " plainDatakey is: "); + dataKey.printPlainKey(); + System.out.println(funTAG + "cipherDatakey length is: " + dataKey.getCipherKeyLen()); + System.out.println(TAG + funTAG + " cipherDatakey is: "); + dataKey.printCipherKey(); } catch (Exception e) { System.out.println(e.getMessage()); } @@ -93,6 +102,10 @@ public class TestKmsCmsProxy { private static void testKmsDecryptDataWithProxy(SigParams params, KeyIdHandle keyIdHandle, int data_out_len, int vsockCid, int vsockPort) { String funTAG = TAG + " [testKmsDecryptData] "; + /** + * u need use your keyid to encrypt 'hello world' firstly, + * and put the ciphertext into dataInputStr + */ String dataInputStr = "AgB4AKTnZ65GOa++oGmcbPUsFDv6zte5W7" + "uJVX8nuolXzcNBW8IrKHu1/+fktAVEhfcv" + "zkUUes53yUsJSxdXmE/CQ9YzubwciuYojo" + @@ -102,7 +115,7 @@ public class TestKmsCmsProxy { "mfBk"; /* hello world! */ try { /* call kms_decrypt_data api */ - ReturnChars plaintext = LibCmsKmsProxyNative.kmsDecryptDataBlockingWithProxy(params, keyIdHandle, dataInputStr, vsockCid, vsockPort); + ReturnChars plaintext = LibCmsKmsProxyNative.kmsDecryptDataBlockingWithProxy(params, keyIdHandle, dataInputStr, vsockCid, vsockPort, data_out_len); if (plaintext.getRc() != KMS_SUCCESS.getValue()) { System.out.println(funTAG + "DecryptData fail error code is " + plaintext.getRc()); return; diff --git a/enclave/qtsm-sdk-java/kms-cms-java/jni/com_huawei_src_kms_LibCmsKmsProxyNative.c b/enclave/qtsm-sdk-java/kms-cms-java/jni/com_huawei_src_kms_LibCmsKmsProxyNative.c index ae3d19a370cb1afa35a28f71a32e1641c40a32a4..c5da4305ee737af6b557d1f6a72b4862f08746ab 100644 --- a/enclave/qtsm-sdk-java/kms-cms-java/jni/com_huawei_src_kms_LibCmsKmsProxyNative.c +++ b/enclave/qtsm-sdk-java/kms-cms-java/jni/com_huawei_src_kms_LibCmsKmsProxyNative.c @@ -28,13 +28,17 @@ #include "transfer.h" #include "qtsm_lib.h" +#define MAX_SOCKET_PATH_LENGTH 108 +#define BITS_LENGHT_SHIFT 8 + JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsGenRandomBlockingWithProxy(JNIEnv *env, jclass cls, jobject sigParams, jint randomLen, jint vsockCid, jint vsockPort) { int status_mem; + char socket_path[MAX_SOCKET_PATH_LENGTH]; if (env == NULL) { - log_err("env is null"); + fprintf(stdout, "env is null\n"); return NULL; } @@ -55,11 +59,16 @@ JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsGenRan const char *c_host = (*env)->GetStringUTFChars(env, host, NULL); sig_params_t params; sig_params_init(¶ms); + if (snprintf(socket_path, sizeof(socket_path), CURL_SOCKET_PATH, vsockPort) < 0) { + fprintf(stdout, "set socket path failed\n"); + return NULL; + } /* Set sign params */ params.key = (sig_str_t)sig_str(c_key); params.secret = (sig_str_t)sig_str(c_secret); params.host = (sig_str_t)sig_str(c_host); params.uri_prefix = (sig_str_t)sig_str(c_uriPrefix); + params.socket_path = (sig_str_t)sig_str(socket_path); random_data_t rnd_data; unsigned long status; @@ -67,34 +76,30 @@ JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsGenRan unsigned char random[random_len]; jobject returnObject = NULL; - status_mem = memset(random, 0, sizeof(random)); - if (status_mem < 0) { - log_err("memset failed"); - return NULL; - } + memset(random, 0, sizeof(random)); rnd_data.random = random; rnd_data.random_len = &random_len; - jbyteArray returnInfoArray = (*env)->NewByteArray(env, *rnd_data.random_len); status = kms_gen_random_blocking_with_proxy(¶ms, randomLen, &rnd_data, vsockCid, vsockPort); + jclass returnT = (*env)->FindClass(env, "com/huawei/src/model/ReturnRandomDatas"); if (returnT == NULL) { - log_err("there is no com/huawei/src/model/ReturnRandomDatas class"); + fprintf(stdout, "there is no com/huawei/src/model/ReturnRandomDatas class\n"); jclass exceptionClass = (*env)->FindClass(env, "java/lang/ClassNotFoundException"); (*env)->ThrowNew(env, exceptionClass, "Failed to find class com/huawei/src/model/ReturnRandomDatas"); goto free; } + jbyteArray returnInfoArray = (*env)->NewByteArray(env, *rnd_data.random_len); jmethodID controcId = (*env)->GetMethodID(env, returnT, "", "()V"); returnObject = (*env)->NewObject(env, returnT, controcId); jfieldID rcField = (*env)->GetFieldID(env, returnT, "rc", "I"); jfieldID returnInfoField = (*env)->GetFieldID(env, returnT, "returnInfo", "[B"); - + (*env)->SetByteArrayRegion(env, returnInfoArray, 0, *rnd_data.random_len, (jbyte*)rnd_data.random); if (status != KMS_SUCCESS) { (*env)->SetIntField(env, returnObject, rcField, status); (*env)->SetObjectField(env, returnObject, returnInfoField, returnInfoArray); goto free; } - (*env)->SetByteArrayRegion(env, returnInfoArray, 0, *rnd_data.random_len, rnd_data.random); (*env)->SetIntField(env, returnObject, rcField, status); (*env)->SetObjectField(env, returnObject, returnInfoField, returnInfoArray); @@ -111,9 +116,10 @@ JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsGenera jint res_cipher_key_len, jint res_key_id_len, jint vsockCid, jint vsockPort) { int status_mem; + char socket_path[MAX_SOCKET_PATH_LENGTH]; if (env == NULL) { - log_err("env is null"); + fprintf(stdout, "env is null\n"); return NULL; } @@ -132,15 +138,19 @@ JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsGenera const char *c_uriPrefix = (*env)->GetStringUTFChars(env, uriPrefix, NULL); const char *c_host = (*env)->GetStringUTFChars(env, host, NULL); - log_info("from java the value of params is c_key: %s , c_secret :%s, c_uriPrefix: %s, c_host:%s", - c_key, c_secret, c_uriPrefix, c_host); + fprintf(stdout, "from java the value of params is c_key: %s , c_secret :%s, c_uriPrefix: %s, c_host:%s\n", + c_key, c_secret, c_uriPrefix, c_host); sig_params_t params; sig_params_init(¶ms); - + if (snprintf(socket_path, sizeof(socket_path), CURL_SOCKET_PATH, vsockPort) < 0) { + fprintf(stdout, "set socket path failed\n"); + return NULL; + } params.key = (sig_str_t)sig_str(c_key); params.secret = (sig_str_t)sig_str(c_secret); params.host = (sig_str_t)sig_str(c_host); params.uri_prefix = (sig_str_t)sig_str(c_uriPrefix); + params.socket_path = (sig_str_t)sig_str(socket_path); jclass keyIdHandleCls = (*env)->FindClass(env, "com/huawei/src/model/KeyIdHandle"); jfieldID keyIdHandleField = (*env)->GetFieldID(env, keyIdHandleCls, "keyId", "Ljava/lang/String;"); jfieldID lenField = (*env)->GetFieldID(env, keyIdHandleCls, "len", "I"); @@ -158,24 +168,13 @@ JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsGenera char res_key_id[res_key_id_len]; unsigned char res_plain_key[res_plain_key_len]; unsigned char res_cipher_key[res_cipher_key_len]; + unsigned int res_plain_key_hex_len = res_plain_key_len / BITS_LENGHT_SHIFT; jobject dataKeyObject = NULL; /* reset datakey memory */ - status_mem = memset(res_key_id, 0, sizeof(res_key_id)); - if (status_mem < 0) { - log_err("memset failed"); - goto free; - } - status_mem = memset(res_plain_key, 0, sizeof(res_plain_key)); - if (status_mem < 0) { - log_err("memset failed"); - goto free; - } - status_mem = memset(res_cipher_key, 0, sizeof(res_cipher_key_len)); - if (status_mem < 0) { - log_err("memset failed"); - goto free; - } + memset(res_key_id, 0, sizeof(res_key_id)); + memset(res_cipher_key, 0, sizeof(res_cipher_key)); + memset(res_plain_key, 0, sizeof(res_plain_key)); res_datakey.key_id = res_key_id; res_datakey.key_id_len = &res_key_id_len; res_datakey.plain_key = res_plain_key; @@ -187,14 +186,14 @@ JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsGenera status = kms_generate_datakey_blocking_with_proxy(¶ms, &handle_struct, datakeyLen, &res_datakey, vsockCid, vsockPort); if (status != KMS_SUCCESS) { - log_err("kms_generate_datakey_blocking_with_proxy error is %d\n", status); + fprintf(stdout, "kms_generate_datakey_blocking_with_proxy error is %d\n", status); goto free; } /* if response is 200 then go put struct res_data */ jclass dataKeyCls = (*env)->FindClass(env, "com/huawei/src/model/DataKey"); if (dataKeyCls == NULL) { - log_err("there is no com/huawei/src/model/DataKey class"); + fprintf(stdout, "there is no com/huawei/src/model/DataKey class\n"); jclass exceptionClass = (*env)->FindClass(env, "java/lang/ClassNotFoundException"); (*env)->ThrowNew(env, exceptionClass, "Failed to find class com/huawei/src/model/DataKey"); goto free; @@ -215,19 +214,18 @@ JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsGenera /* change char* to byte array */ (*env)->SetCharArrayRegion(env, keyIdCharArray, 0, strlen(res_datakey.key_id), (jchar*) res_datakey.key_id); jint keyIdLen = (*env)->GetIntField(env, dataKeyObject, keyIdLenField); - jbyteArray plainKeyArray = (*env)->NewByteArray(env, *res_datakey.plain_key_len); + + jbyteArray plainKeyArray = (*env)->NewByteArray(env, res_plain_key_hex_len); - (*env)->SetByteArrayRegion(env, plainKeyArray, 0, *res_datakey.plain_key_len, res_datakey.plain_key); - jint plainKeyLen = (*env)->GetIntField(env, dataKeyObject, plainKeyLenField); + (*env)->SetByteArrayRegion(env, plainKeyArray, 0, res_plain_key_hex_len, (jbyte*)res_datakey.plain_key); jbyteArray cipherKeyArray = (*env)->NewByteArray(env, *res_datakey.cipher_key_len); - - (*env)->SetByteArrayRegion(env, cipherKeyArray, 0, *res_datakey.cipher_key_len, res_datakey.cipher_key); - jint cipherKeyLen = (*env)->GetIntField(env, dataKeyObject, cipherKeyLenField); + jint cipherKeyLen = (jint)(*res_datakey.cipher_key_len); + (*env)->SetByteArrayRegion(env, cipherKeyArray, 0, *res_datakey.cipher_key_len, (jbyte*)res_datakey.cipher_key); (*env)->SetObjectField(env, dataKeyObject, keyIdField, keyIdCharArray); (*env)->SetIntField(env, dataKeyObject, keyIdLenField, keyIdLen); (*env)->SetObjectField(env, dataKeyObject, plainKeyField, plainKeyArray); - (*env)->SetIntField(env, dataKeyObject, plainKeyLenField, plainKeyLen); + (*env)->SetIntField(env, dataKeyObject, plainKeyLenField, res_plain_key_hex_len); (*env)->SetObjectField(env, dataKeyObject, cipherKeyField, cipherKeyArray); (*env)->SetIntField(env, dataKeyObject, cipherKeyLenField, cipherKeyLen); @@ -240,8 +238,9 @@ free: } JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsDecryptDataBlockingWithProxy(JNIEnv *env, - jclass cls, jobject sigParams, jobject handle, jstring datainput, jint vsockCid, jint vsockPort) + jclass cls, jobject sigParams, jobject handle, jstring datainput, jint vsockCid, jint vsockPort, jint dataOutCap) { + char socket_path[MAX_SOCKET_PATH_LENGTH]; if (env == NULL) { log_err("env is null"); return NULL; @@ -266,11 +265,16 @@ JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsDecryp sig_params_t params; sig_params_init(¶ms); + if (snprintf(socket_path, sizeof(socket_path), CURL_SOCKET_PATH, vsockPort) < 0) { + log_err("set socket path failed"); + return NULL; + } /* Set sign params */ params.key = (sig_str_t)sig_str(c_key); params.secret = (sig_str_t)sig_str(c_secret); params.host = (sig_str_t)sig_str(c_host); params.uri_prefix = (sig_str_t)sig_str(c_uriPrefix); + params.socket_path = (sig_str_t)sig_str(socket_path); jclass keyIdHandleCls = (*env)->FindClass(env, "com/huawei/src/model/KeyIdHandle"); jfieldID keyIdHandleField = (*env)->GetFieldID(env, keyIdHandleCls, "keyId", "Ljava/lang/String;"); @@ -291,9 +295,10 @@ JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsDecryp const unsigned char *data_in = (*env)->GetStringUTFChars(env, datainput, NULL); unsigned int data_in_len = strlen(data_in); - unsigned int data_out_len = 1000; + unsigned int data_out_len = dataOutCap; unsigned char data_out[data_out_len]; + memset(data_out, 0, sizeof(data_out)); data_buffer.data_in = data_in; data_buffer.data_in_len = data_in_len; data_buffer.data_out = data_out; @@ -323,15 +328,27 @@ JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsDecryp returnObject = (*env)->NewObject(env, returnT, controcId); jfieldID rcField = (*env)->GetFieldID(env, returnT, "rc", "I"); jfieldID returnInfoField = (*env)->GetFieldID(env, returnT, "returnInfo", "[C"); - jcharArray returnInfoArray = (*env)->NewCharArray(env, *data_buffer.data_out_len); - (*env)->SetCharArrayRegion(env, returnInfoArray, 0, *data_buffer.data_out_len, data_buffer.data_out); + + jsize javalen = strlen(data_buffer.data_out); + jcharArray returnInfoArray = (*env)->NewCharArray(env, javalen); + + jchar* java_data_buffer = (jchar*)malloc(javalen * sizeof(jchar)); + if (java_data_buffer == NULL) { + fprintf(stdout, "malloc for java_data_buffer error\n"); + goto free; + } + for (jsize i = 0; i < javalen; i++) { + java_data_buffer[i] = (jchar)data_buffer.data_out[i]; + } + + (*env)->SetCharArrayRegion(env, returnInfoArray, 0, javalen, java_data_buffer); jsize lendata = (*env)->GetArrayLength(env, returnInfoArray); jchar* data = (*env)->GetCharArrayElements(env, returnInfoArray, NULL); - (*env)->ReleaseCharArrayElements(env, returnInfoArray, data, 0); (*env)->SetIntField(env, returnObject, rcField, status); (*env)->SetObjectField(env, returnObject, returnInfoField, returnInfoArray); - + (*env)->ReleaseCharArrayElements(env, returnInfoArray, data, 0); + free(java_data_buffer); free: (*env)->ReleaseStringUTFChars(env, key, c_key); (*env)->ReleaseStringUTFChars(env, secret, c_secret); @@ -339,3 +356,4 @@ free: (*env)->ReleaseStringUTFChars(env, host, c_host); return returnObject; } + diff --git a/enclave/qtsm-sdk-java/kms-cms-java/jni/com_huawei_src_kms_LibCmsKmsProxyNative.h b/enclave/qtsm-sdk-java/kms-cms-java/jni/com_huawei_src_kms_LibCmsKmsProxyNative.h index a4a7b77ddf07cf94637b750f06775c9c77bf76af..53731f4044d2315c5aa3e99cd314061ec3293f27 100644 --- a/enclave/qtsm-sdk-java/kms-cms-java/jni/com_huawei_src_kms_LibCmsKmsProxyNative.h +++ b/enclave/qtsm-sdk-java/kms-cms-java/jni/com_huawei_src_kms_LibCmsKmsProxyNative.h @@ -29,8 +29,7 @@ JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsGenera * Ljava/lang/String;II)Lcom/huawei/src/model/ReturnChars; */ JNIEXPORT jobject JNICALL Java_com_huawei_src_kms_LibCmsKmsProxyNative_kmsDecryptDataBlockingWithProxy - (JNIEnv *, jclass, jobject, jobject, jstring, jint, jint); - + (JNIEnv *, jclass, jobject, jobject, jstring, jint, jint, jint); #ifdef __cplusplus } #endif diff --git a/enclave/qtsm-sdk-java/kms-cms-java/scripts/build_image.sh b/enclave/qtsm-sdk-java/kms-cms-java/scripts/build_image.sh index 6763de5a04c08757aea9529f2d8baff3e75ed76c..1c86d23455e3568f633a740dab010b382dbf3843 100644 --- a/enclave/qtsm-sdk-java/kms-cms-java/scripts/build_image.sh +++ b/enclave/qtsm-sdk-java/kms-cms-java/scripts/build_image.sh @@ -1,10 +1,19 @@ #!/bin/bash +set -e CUR_DIR=$(pwd) QT_DIR=${CUR_DIR}/../../../.. +mkdir -p ${CUR_DIR}/../lib +cd ../lib +wget https://repo1.maven.org/maven2/junit/junit/4.13.1/junit-4.13.1.jar +wget https://repo1.maven.org/maven2/org/projectlombok/lombok/1.18.26/lombok-1.18.26.jar +cd ${CUR_DIR} pushd ${QT_DIR} > /dev/null cp ${QT_DIR}/enclave/qtsm-sdk-java/kms-cms-java/Dockerfile.kms . docker build -f Dockerfile.kms -t kms-demo . rm ./Dockerfile.kms qt enclave make-img --docker-uri kms-demo --eif ${CUR_DIR}/kms-demo.eif -popd > /dev/null \ No newline at end of file +git clone https://github.com/stefanha/nc-vsock.git +cd nc-vsock +make +popd > /dev/null \ No newline at end of file diff --git a/enclave/qtsm-sdk-java/kms-cms-java/scripts/build_kms_demo.sh b/enclave/qtsm-sdk-java/kms-cms-java/scripts/build_kms_demo.sh index ccfb5515b473277072d085bc65cf381c34310745..d5a85c7853a2cc2fd610e3206cf1cfcc111820fe 100644 --- a/enclave/qtsm-sdk-java/kms-cms-java/scripts/build_kms_demo.sh +++ b/enclave/qtsm-sdk-java/kms-cms-java/scripts/build_kms_demo.sh @@ -1,11 +1,4 @@ -cd /home/builder/enclave/qtsm/lib -make clean -mkdir /home/builder/enclave/qtsm/lib/../output/ -make -cd /home/builder/enclave/qtsm-sdk-java/kms-cms-java -make -javac -encoding UTF-8 -classpath ./lib/lombok-1.18.26.jar:./lib/junit-4.13.1.jar ./com/huawei/src/model/*.java ./com/huawei/src/kms/*.java ./com/huawei/src/test/*.java -d ./target - -cp -r META-INF/ target/ -cd target +#!/bin/bash +cd /home/builder/enclave/qtsm-sdk-java/kms-cms-java/target +# We can perform it manually java -cp .:../lib/lombok-1.18.26.jar:../lib/junit-4.13.1.jar -Djava.library.path=./lib com.huawei.src.test.TestKmsCmsProxy \ No newline at end of file diff --git a/qingtian-tools/Makefile b/qingtian-tools/Makefile index b1b857eafffa510c61e24f19b8b21bf2110fcc9e..742249de26ecc8dac7bae738086bf749dead9560 100644 --- a/qingtian-tools/Makefile +++ b/qingtian-tools/Makefile @@ -8,7 +8,7 @@ LDFLAGS += `pkg-config --cflags --libs glib-2.0` VPATH = src:include CC := gcc -LIBS := -lgnutls -lnettle -lcjson +LIBS := -lgnutls -lnettle -lcjson -lglib-2.0 INC := -I./include OBJS := qt-enclave objects = util.o image.o enclave.o cli.o logger.o diff --git a/qingtian-tools/qingtian_tool.spec b/qingtian-tools/qingtian_tool.spec index b956dbe954d2ef20edde483c9b0579ca157bd139..70cf97dce3b91fdd8d840ef73cc3cd7e688be1ae 100644 --- a/qingtian-tools/qingtian_tool.spec +++ b/qingtian-tools/qingtian_tool.spec @@ -3,7 +3,7 @@ Name : qingtian-tool Summary : qingtian enclave manage tool Version : 1.0 -Release : 54 +Release : 55 Group : UVP/enclave License : GPL V2 BuildRoot : %{_tmppath}/%{name}-%{version}-build @@ -48,7 +48,7 @@ install -d -m 755 $RPM_BUILD_ROOT/etc/rsyslog.d/ install -m 755 %{_builddir}/%{name}-%{version}/qt-enclave $RPM_BUILD_ROOT/usr/local/bin/qingtian/qt-enclave install -m 755 %{_builddir}/%{name}-%{version}/scripts/qt $RPM_BUILD_ROOT/usr/local/bin/qt install -m 755 %{_builddir}/%{name}-%{version}/scripts/qt_enclave_env $RPM_BUILD_ROOT/usr/local/bin/qingtian/enclave/qt-enclave-env -install -m 755 %{_builddir}/%{name}-%{version}/conf/qt_enclave_env.conf $RPM_BUILD_ROOT/etc/qingtian/enclave/qt-enclave-env.conf +install -m 644 %{_builddir}/%{name}-%{version}/conf/qt_enclave_env.conf $RPM_BUILD_ROOT/etc/qingtian/enclave/qt-enclave-env.conf install -m 755 %{_builddir}/%{name}-%{version}/conf/qt_enclave_env.service $RPM_BUILD_ROOT/usr/lib/systemd/system/qt-enclave-env.service %ifarch aarch64 install -m 755 %{_builddir}/%{name}-%{version}/platform/linuxkit/linuxkit-linux-arm64 $RPM_BUILD_ROOT/usr/local/share/qingtian/enclave/linuxkit-linux-arm64 @@ -56,11 +56,11 @@ install -m 755 %{_builddir}/%{name}-%{version}/platform/linuxkit/linuxkit-linux- install -m 755 %{_builddir}/%{name}-%{version}/platform/linuxkit/linuxkit-linux-amd64 $RPM_BUILD_ROOT/usr/local/share/qingtian/enclave/linuxkit-linux-amd64 %endif -install -m 666 %{_builddir}/%{name}-%{version}/qt-proxy/conf/qt_proxy_rsyslog.conf %{buildroot}/etc/rsyslog.d/qt_proxy.conf -install -m 666 %{_builddir}/%{name}-%{version}/qt-proxy/conf/qt_proxy.logrotate.in %{buildroot}/etc/logrotate.d/qt_proxy +install -m 644 %{_builddir}/%{name}-%{version}/qt-proxy/conf/qt_proxy_rsyslog.conf %{buildroot}/etc/rsyslog.d/qt_proxy.conf +install -m 644 %{_builddir}/%{name}-%{version}/qt-proxy/conf/qt_proxy.logrotate.in %{buildroot}/etc/logrotate.d/qt_proxy install -m 755 %{_builddir}/%{name}-%{version}/qt-proxy/qt_proxy %{buildroot}/usr/local/bin/qingtian/enclave/qt_proxy install -m 755 %{_builddir}/%{name}-%{version}/qt-proxy/scripts/qt-proxy %{buildroot}/etc/qingtian/enclave/qt-proxy -install -m 755 %{_builddir}/%{name}-%{version}/qt-proxy/conf/qt-proxy.conf %{buildroot}/etc/qingtian/enclave/qt-proxy.conf +install -m 644 %{_builddir}/%{name}-%{version}/qt-proxy/conf/qt-proxy.conf %{buildroot}/etc/qingtian/enclave/qt-proxy.conf install -m 755 %{_builddir}/%{name}-%{version}/qt-proxy/conf/qt-proxy.service %{buildroot}/usr/lib/systemd/system/qt-proxy.service @@ -81,6 +81,8 @@ install -m 755 %{_builddir}/%{name}-%{version}/qt-proxy/conf/qt-proxy.service %{ %changelog +* Wed May 21 2025 huawei - 1.0-55 + rebase the newest codes * Wed Nov 06 2024 huawei - 1.0-54 rebase the newest codes * Fri May 10 2024 huawei - 1.0-49 diff --git a/qingtian-tools/qt-proxy/Makefile b/qingtian-tools/qt-proxy/Makefile index 2cd49ac2cda332c65bb4b7fde33c08674927cb45..5314db5eabe81881f139eb66397ad55afd0c18bf 100644 --- a/qingtian-tools/qt-proxy/Makefile +++ b/qingtian-tools/qt-proxy/Makefile @@ -1,9 +1,10 @@ CFLAGS := -O2 -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Wmissing-declarations -fno-strict-aliasing CFLAGS += -Werror -Wformat -Wformat-security -D_GNU_SOURCE -fPIC -fstack-protector-strong -fno-common -CFLAGS += `pkg-config --cflags glib-2.0` +CFLAGS += `pkg-config --cflags --libs glib-2.0` LDFLAGS := -fPIE -pie -Wl,-z,relro,-z,now -Wl,-z,noexecstack,-s -LDFLAGS += `pkg-config --libs glib-2.0` +LDFLAGS += `pkg-config --cflags --libs glib-2.0` +LIBS := -lglib-2.0 CC := gcc @@ -19,7 +20,7 @@ objects := $(SRCS:.c=.o) $(CC) $(CFLAGS) $(INC) -o $@ -c $< $(OBJS): $(objects) - $(CC) $(LDFLAGS) -o $@ $^ + $(CC) $(LDFLAGS) -o $@ $(objects) $(LIBS) CLEANFILES := $(objects) $(OBJS) @@ -27,5 +28,12 @@ CLEANFILES := $(objects) $(OBJS) all: $(OBJS) +install: + install -D -m 644 conf/qt_proxy_rsyslog.conf /etc/rsyslog.d/qt_proxy.conf + install -D -m 644 conf/qt_proxy.logrotate.in /etc/logrotate.d/qt_proxy + install -D -m 755 qt_proxy /usr/local/bin/qingtian/enclave/qt_proxy + install -D -m 755 scripts/qt-proxy etc/qingtian/enclave/qt-proxy + install -D -m 644 conf/qt-proxy.conf /etc/qingtian/enclave/qt-proxy.conf + clean: rm -f ${CLEANFILES} diff --git a/virtio-qtbox/Makefile b/virtio-qtbox/Makefile index 6e95b54b16e80b4f429d47b4cd7073de951b314e..e76c98347801299cf322021dee9ee73882e3d68a 100644 --- a/virtio-qtbox/Makefile +++ b/virtio-qtbox/Makefile @@ -16,5 +16,11 @@ PWD := $(shell pwd) all: $(MAKE) -C $(KDIR) M=$(PWD) +install: + install -D -m 644 virtio-qtbox.ko /opt/qingtian/enclave/virtio-qtbox.ko + +uninstall: + rm -f /opt/qingtian/enclave/virtio-qtbox.ko + clean: $(MAKE) -C $(KDIR) M=$(PWD) clean