diff --git a/.gitignore b/.gitignore index ef9c841ac34f9e4f826fd23c2eeaf03d960f5c1e..d1ee1b3c3c3361e46c6478c0587738681af3dafb 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ cmake-build-debug *.patch @ohos.net.connection.d.ts -basic.d.ts \ No newline at end of file +basic.d.ts +.vscode diff --git a/bundle.json b/bundle.json index a7bb58493adcf20482b420fd4acd12c7aef2c845..9088998b8c67305f0bf6e9add1000bc1844b0b1e 100644 --- a/bundle.json +++ b/bundle.json @@ -43,12 +43,15 @@ "build": { "group_type": { "base_group": [ - "//foundation/communication/netstack/frameworks/js/napi:http", - "//foundation/communication/netstack/frameworks/js/napi:socket", - "//foundation/communication/netstack/frameworks/js/napi:websocket", - "//foundation/communication/netstack/frameworks/js/napi:fetch" + "//foundation/communication/netstack/frameworks/js/napi/http:http", + "//foundation/communication/netstack/frameworks/js/napi/socket:socket", + "//foundation/communication/netstack/frameworks/js/napi/websocket:websocket", + "//foundation/communication/netstack/frameworks/js/napi/fetch:fetch", + "//foundation/communication/netstack/utils:common_utils" ], "fwk_group": [ + "//foundation/communication/netstack/frameworks/native/tls_socket:tls_socket", + "//foundation/communication/netstack/frameworks/js/napi/tls:tlssocket" ], "service_group": [ ] @@ -56,7 +59,8 @@ "inner_kits": [], "test": [ "//foundation/communication/netstack/test/napi/socket:fuzztest", - "//foundation/communication/netstack/test/unittest/http/cache:unittest" + "//foundation/communication/netstack/test/unittest/http/cache:unittest", + "//foundation/communication/netstack/test/unittest/tlssocket:unittest" ] } } diff --git a/frameworks/js/napi/BUILD.gn b/frameworks/js/napi/BUILD.gn deleted file mode 100644 index 06891429575cffb5c7ede8ee33de0ee2c8879b02..0000000000000000000000000000000000000000 --- a/frameworks/js/napi/BUILD.gn +++ /dev/null @@ -1,235 +0,0 @@ -# Copyright (c) 2021-2022 Huawei Device 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. - -import("//build/ohos.gni") - -SUBSYSTEM_DIR = "//foundation/communication" -NETSTACK_NAPI_ROOT = "$SUBSYSTEM_DIR/netstack/frameworks/js/napi/" - -utils_source = [ - "$SUBSYSTEM_DIR/netstack/utils/base_context/src/netstack_base_context.cpp", - "$SUBSYSTEM_DIR/netstack/utils/common_utils/src/netstack_common_utils.cpp", - "$SUBSYSTEM_DIR/netstack/utils/event_manager/src/netstack_event_listener.cpp", - "$SUBSYSTEM_DIR/netstack/utils/event_manager/src/netstack_event_manager.cpp", - "$SUBSYSTEM_DIR/netstack/utils/module_template/src/netstack_module_template.cpp", - "$SUBSYSTEM_DIR/netstack/utils/napi_utils/src/netstack_napi_utils.cpp", -] - -utils_include = [ - "$SUBSYSTEM_DIR/netstack/utils/base_async_work/include", - "$SUBSYSTEM_DIR/netstack/utils/base_context/include", - "$SUBSYSTEM_DIR/netstack/utils/common_utils/include", - "$SUBSYSTEM_DIR/netstack/utils/event_manager/include", - "$SUBSYSTEM_DIR/netstack/utils/log/include", - "$SUBSYSTEM_DIR/netstack/utils/module_template/include", - "$SUBSYSTEM_DIR/netstack/utils/napi_utils/include", -] - -common_include = [ - "//foundation/arkui/ace_engine/frameworks/base/utils", - "//foundation/arkui/napi/interfaces/kits", - "//foundation/arkui/napi", - "//third_party/node/src", -] - -common_deps = [ "//foundation/arkui/napi/:ace_napi" ] - -common_external_deps = [ - "c_utils:utils", - "hiviewdfx_hilog_native:libhilog", -] - -common_relative_install_dir = "module/net" -common_part_name = "netstack" -common_subsystem_name = "communication" - -ohos_shared_library("http") { - include_dirs = [ - "$NETSTACK_NAPI_ROOT/http/async_context/include", - "$NETSTACK_NAPI_ROOT/http/async_work/include", - "$NETSTACK_NAPI_ROOT/http/cache/base64/include", - "$NETSTACK_NAPI_ROOT/http/cache/cache_constant/include", - "$NETSTACK_NAPI_ROOT/http/cache/cache_proxy/include", - "$NETSTACK_NAPI_ROOT/http/cache/cache_strategy/include", - "$NETSTACK_NAPI_ROOT/http/cache/lru_cache/include", - "$NETSTACK_NAPI_ROOT/http/cache/md5/include", - "$NETSTACK_NAPI_ROOT/http/constant/include", - "$NETSTACK_NAPI_ROOT/http/http_exec/include", - "$NETSTACK_NAPI_ROOT/http/http_module/include", - "$NETSTACK_NAPI_ROOT/http/options/include", - ] - include_dirs += utils_include - include_dirs += common_include - include_dirs += [ - "//third_party/curl/include", - "//third_party/glib/glib", - "//third_party/glib", - "//third_party/jsoncpp/include", - "//third_party/openssl/include", - ] - - sources = [ - "http/async_context/src/request_context.cpp", - "http/async_work/src/http_async_work.cpp", - "http/cache/base64/src/base64_utils.cpp", - "http/cache/cache_proxy/src/cache_proxy.cpp", - "http/cache/cache_strategy/src/http_cache_request.cpp", - "http/cache/cache_strategy/src/http_cache_response.cpp", - "http/cache/cache_strategy/src/http_cache_strategy.cpp", - "http/cache/cache_strategy/src/http_time.cpp", - "http/cache/lru_cache/src/disk_handler.cpp", - "http/cache/lru_cache/src/lru_cache.cpp", - "http/cache/lru_cache/src/lru_cache_disk_handler.cpp", - "http/cache/md5/src/calculate_md5.cpp", - "http/constant/src/constant.cpp", - "http/http_exec/src/http_exec.cpp", - "http/http_module/src/http_module.cpp", - "http/options/src/http_request_options.cpp", - "http/options/src/http_response.cpp", - ] - sources += utils_source - - deps = common_deps - deps += [ - "//third_party/curl:curl", - "//third_party/glib:glib_packages", - "//third_party/jsoncpp:jsoncpp", - "//third_party/openssl:libcrypto_shared", - ] - - external_deps = common_external_deps - - relative_install_dir = common_relative_install_dir - part_name = common_part_name - subsystem_name = common_subsystem_name -} - -ohos_shared_library("socket") { - include_dirs = [ - "$NETSTACK_NAPI_ROOT/socket/async_context/include", - "$NETSTACK_NAPI_ROOT/socket/async_work/include", - "$NETSTACK_NAPI_ROOT/socket/constant/include", - "$NETSTACK_NAPI_ROOT/socket/socket_exec/include", - "$NETSTACK_NAPI_ROOT/socket/socket_module/include", - "$NETSTACK_NAPI_ROOT/socket/options/include", - "$NETSTACK_NAPI_ROOT/socket/task_queue/include", - ] - include_dirs += utils_include - include_dirs += common_include - - sources = [ - "socket/async_context/src/bind_context.cpp", - "socket/async_context/src/common_context.cpp", - "socket/async_context/src/connect_context.cpp", - "socket/async_context/src/tcp_extra_context.cpp", - "socket/async_context/src/tcp_send_context.cpp", - "socket/async_context/src/udp_extra_context.cpp", - "socket/async_context/src/udp_send_context.cpp", - "socket/async_work/src/socket_async_work.cpp", - "socket/options/src/extra_options_base.cpp", - "socket/options/src/net_address.cpp", - "socket/options/src/socket_remote_info.cpp", - "socket/options/src/socket_state_base.cpp", - "socket/options/src/tcp_connect_options.cpp", - "socket/options/src/tcp_extra_options.cpp", - "socket/options/src/tcp_send_options.cpp", - "socket/options/src/udp_extra_options.cpp", - "socket/options/src/udp_send_options.cpp", - "socket/socket_exec/src/socket_exec.cpp", - "socket/socket_module/src/socket_module.cpp", - ] - sources += utils_source - - deps = common_deps - - external_deps = common_external_deps - - relative_install_dir = common_relative_install_dir - part_name = common_part_name - subsystem_name = common_subsystem_name -} - -ohos_shared_library("websocket") { - include_dirs = [ - "websocket/async_context/include", - "websocket/async_work/include", - "websocket/constant/include", - "websocket/websocket_exec/include", - "websocket/websocket_module/include", - ] - include_dirs += utils_include - include_dirs += common_include - include_dirs += [ - "//third_party/libwebsockets/include", - "//third_party/openssl/include", - ] - - sources = [ - "websocket/async_context/src/close_context.cpp", - "websocket/async_context/src/connect_context.cpp", - "websocket/async_context/src/send_context.cpp", - "websocket/async_work/src/websocket_async_work.cpp", - "websocket/constant/src/constant.cpp", - "websocket/websocket_exec/src/websocket_exec.cpp", - "websocket/websocket_module/src/websocket_module.cpp", - ] - sources += utils_source - - deps = common_deps - deps += [ - "//third_party/libwebsockets:websockets", - "//third_party/openssl:libcrypto_static", - "//third_party/openssl:ssl_source", - "//third_party/zlib:libz", - ] - - external_deps = common_external_deps - - relative_install_dir = common_relative_install_dir - part_name = common_part_name - subsystem_name = common_subsystem_name -} - -ohos_shared_library("fetch") { - include_dirs = [ - "$NETSTACK_NAPI_ROOT/fetch/async_context/include", - "$NETSTACK_NAPI_ROOT/fetch/async_work/include", - "$NETSTACK_NAPI_ROOT/fetch/constant/include", - "$NETSTACK_NAPI_ROOT/fetch/fetch_exec/include", - "$NETSTACK_NAPI_ROOT/fetch/fetch_module/include", - "$NETSTACK_NAPI_ROOT/fetch/options/include", - ] - include_dirs += utils_include - include_dirs += common_include - include_dirs += [ "//third_party/curl/include" ] - - sources = [ - "fetch/async_context/src/fetch_context.cpp", - "fetch/async_work/src/fetch_async_work.cpp", - "fetch/constant/src/constant.cpp", - "fetch/fetch_exec/src/fetch_exec.cpp", - "fetch/fetch_module/src/fetch_module.cpp", - "fetch/options/src/fetch_request.cpp", - "fetch/options/src/fetch_response.cpp", - ] - sources += utils_source - - deps = common_deps - deps += [ "//third_party/curl:curl" ] - - external_deps = common_external_deps - - relative_install_dir = "module" - part_name = common_part_name - subsystem_name = common_subsystem_name -} diff --git a/frameworks/js/napi/fetch/BUILD.gn b/frameworks/js/napi/fetch/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e31fe70e0e0a9f1fe061e567e358684a51de9369 --- /dev/null +++ b/frameworks/js/napi/fetch/BUILD.gn @@ -0,0 +1,52 @@ +# Copyright (c) 2021-2022 Huawei Device 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. + +import("//build/ohos.gni") +import("//foundation/communication/netstack/netstack_config.gni") + +ohos_shared_library("fetch") { + include_dirs = [ + "async_context/include", + "async_work/include", + "constant/include", + "fetch_exec/include", + "fetch_module/include", + "options/include", + "//third_party/curl/include", + ] + + sources = [ + "async_context/src/fetch_context.cpp", + "async_work/src/fetch_async_work.cpp", + "constant/src/constant.cpp", + "fetch_exec/src/fetch_exec.cpp", + "fetch_module/src/fetch_module.cpp", + "options/src/fetch_request.cpp", + "options/src/fetch_response.cpp", + ] + + deps = [ + "$NETSTACK_DIR/utils/napi_utils:napi_utils", + "//third_party/curl:curl", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "napi:ace_napi", + ] + + relative_install_dir = "module" + part_name = "netstack" + subsystem_name = "communication" +} diff --git a/frameworks/js/napi/fetch/async_context/include/fetch_context.h b/frameworks/js/napi/fetch/async_context/include/fetch_context.h index f087dc1755c67856aa1044679c7b5825aa86afcc..35daee0ec8456fd9a29e9193d8ea756df9552fae 100644 --- a/frameworks/js/napi/fetch/async_context/include/fetch_context.h +++ b/frameworks/js/napi/fetch/async_context/include/fetch_context.h @@ -18,7 +18,7 @@ #include "fetch_request.h" #include "fetch_response.h" -#include "netstack_base_context.h" +#include "base_context.h" #include "nocopyable.h" namespace OHOS::NetStack { diff --git a/frameworks/js/napi/fetch/async_context/src/fetch_context.cpp b/frameworks/js/napi/fetch/async_context/src/fetch_context.cpp index 08081c6a5794788082f6879ccbda106a28a6fa95..284d087ce934332a1b54a3bc3a50e45213d2ce1c 100644 --- a/frameworks/js/napi/fetch/async_context/src/fetch_context.cpp +++ b/frameworks/js/napi/fetch/async_context/src/fetch_context.cpp @@ -19,7 +19,7 @@ #include "fetch_exec.h" #include "netstack_common_utils.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" namespace OHOS::NetStack { FetchContext::FetchContext(napi_env env, EventManager *manager) @@ -254,4 +254,4 @@ std::string FetchContext::GetResponseType() const { return responseType_; } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/fetch/async_work/src/fetch_async_work.cpp b/frameworks/js/napi/fetch/async_work/src/fetch_async_work.cpp index 93792f5461d8cc75cd3df291a447099546013263..9217a20ebff15795dfc06a6f74ad6a32dba37bfb 100644 --- a/frameworks/js/napi/fetch/async_work/src/fetch_async_work.cpp +++ b/frameworks/js/napi/fetch/async_work/src/fetch_async_work.cpp @@ -16,7 +16,7 @@ #include "fetch_async_work.h" #include "fetch_exec.h" -#include "netstack_base_async_work.h" +#include "base_async_work.h" namespace OHOS::NetStack { void FetchAsyncWork::ExecFetch(napi_env env, void *data) @@ -28,4 +28,4 @@ void FetchAsyncWork::FetchCallback(napi_env env, napi_status status, void *data) { BaseAsyncWork::AsyncWorkCallbackForSystem(env, status, data); } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/fetch/fetch_exec/src/fetch_exec.cpp b/frameworks/js/napi/fetch/fetch_exec/src/fetch_exec.cpp index 4923fdb77619ebb88ac74d627b37774f622b568c..8259305c74c932242236a088a3a8f9e619a9c9da 100644 --- a/frameworks/js/napi/fetch/fetch_exec/src/fetch_exec.cpp +++ b/frameworks/js/napi/fetch/fetch_exec/src/fetch_exec.cpp @@ -22,7 +22,7 @@ #include "constant.h" #include "netstack_common_utils.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" #include "securec.h" #define NETSTACK_CURL_EASY_SET_OPTION(handle, opt, data, asyncContext) \ @@ -346,4 +346,4 @@ bool FetchExec::IsUnReserved(unsigned char in) } return false; } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/fetch/fetch_module/include/fetch_module.h b/frameworks/js/napi/fetch/fetch_module/include/fetch_module.h index c647e1eb753f77ac1b80dff85d3b13a4a6bd74de..ae91b7c592b41b0856c46400a5c45037c152eb9b 100644 --- a/frameworks/js/napi/fetch/fetch_module/include/fetch_module.h +++ b/frameworks/js/napi/fetch/fetch_module/include/fetch_module.h @@ -16,7 +16,7 @@ #ifndef COMMUNICATIONNETSTACK_FETCH_MODULE_H #define COMMUNICATIONNETSTACK_FETCH_MODULE_H -#include "netstack_napi_utils.h" +#include "napi_utils.h" #include "nocopyable.h" namespace OHOS::NetStack { diff --git a/frameworks/js/napi/fetch/fetch_module/src/fetch_module.cpp b/frameworks/js/napi/fetch/fetch_module/src/fetch_module.cpp index 14691dbc26140a47aab1d93252ea23a364d497db..db7a0386a2c92dee834bc9b0d593ee489c1f8cf0 100644 --- a/frameworks/js/napi/fetch/fetch_module/src/fetch_module.cpp +++ b/frameworks/js/napi/fetch/fetch_module/src/fetch_module.cpp @@ -18,7 +18,7 @@ #include "fetch_async_work.h" #include "fetch_exec.h" #include "netstack_log.h" -#include "netstack_module_template.h" +#include "module_template.h" namespace OHOS::NetStack { napi_value FetchModule::InitFetchModule(napi_env env, napi_value exports) diff --git a/frameworks/js/napi/http/BUILD.gn b/frameworks/js/napi/http/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..821c28882c0beb6ee8bc1960709d52729714b490 --- /dev/null +++ b/frameworks/js/napi/http/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2021-2022 Huawei Device 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. + +import("//build/ohos.gni") +import("//foundation/communication/netstack/netstack_config.gni") + +ohos_shared_library("http") { + include_dirs = [ + "async_context/include", + "async_work/include", + "cache/base64/include", + "cache/cache_constant/include", + "cache/cache_proxy/include", + "cache/cache_strategy/include", + "cache/lru_cache/include", + "cache/md5/include", + "constant/include", + "http_exec/include", + "http_module/include", + "options/include", + "//third_party/curl/include", + "//third_party/glib/glib", + "//third_party/glib", + "$SUBSYSTEM_DIR/netstack/utils/common_utils/include", + ] + + sources = [ + "async_context/src/request_context.cpp", + "async_work/src/http_async_work.cpp", + "cache/base64/src/base64_utils.cpp", + "cache/cache_proxy/src/cache_proxy.cpp", + "cache/cache_strategy/src/http_cache_request.cpp", + "cache/cache_strategy/src/http_cache_response.cpp", + "cache/cache_strategy/src/http_cache_strategy.cpp", + "cache/cache_strategy/src/http_time.cpp", + "cache/lru_cache/src/disk_handler.cpp", + "cache/lru_cache/src/lru_cache.cpp", + "cache/lru_cache/src/lru_cache_disk_handler.cpp", + "cache/md5/src/calculate_md5.cpp", + "constant/src/constant.cpp", + "http_exec/src/http_exec.cpp", + "http_module/src/http_module.cpp", + "options/src/http_request_options.cpp", + "options/src/http_response.cpp", + ] + + deps = [ + "$NETSTACK_DIR/utils/napi_utils:napi_utils", + "//third_party/curl:curl", + "//third_party/glib:glib_packages", + "//third_party/jsoncpp:jsoncpp", + "//third_party/openssl:libcrypto_shared", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "napi:ace_napi", + ] + + relative_install_dir = "module/net" + part_name = "netstack" + subsystem_name = "communication" +} diff --git a/frameworks/js/napi/http/async_context/include/request_context.h b/frameworks/js/napi/http/async_context/include/request_context.h index ac9ccec4a29e97b35f76796b54ef039d56ccf553..37316cd3b96140df6e1e11e48a7a57d7f719f618 100644 --- a/frameworks/js/napi/http/async_context/include/request_context.h +++ b/frameworks/js/napi/http/async_context/include/request_context.h @@ -18,7 +18,7 @@ #include "http_request_options.h" #include "http_response.h" -#include "netstack_base_context.h" +#include "base_context.h" #include "nocopyable.h" namespace OHOS::NetStack { diff --git a/frameworks/js/napi/http/async_context/src/request_context.cpp b/frameworks/js/napi/http/async_context/src/request_context.cpp index 42a050e29818f675c94f62a8bcd77413a746873f..a356c4fcd4ee00b780bc0503757aac36a86c683f 100644 --- a/frameworks/js/napi/http/async_context/src/request_context.cpp +++ b/frameworks/js/napi/http/async_context/src/request_context.cpp @@ -21,7 +21,7 @@ #include "http_exec.h" #include "netstack_common_utils.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" static constexpr const int PARAM_JUST_URL = 1; @@ -266,4 +266,4 @@ bool RequestContext::IsUsingCache() const { return usingCache_; } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/http/async_work/src/http_async_work.cpp b/frameworks/js/napi/http/async_work/src/http_async_work.cpp index e89df42c9de44ea05839fd57f495bc322d47b0eb..008ae976478e03114ae6771d62d23c1735ff4531 100644 --- a/frameworks/js/napi/http/async_work/src/http_async_work.cpp +++ b/frameworks/js/napi/http/async_work/src/http_async_work.cpp @@ -16,8 +16,8 @@ #include "http_async_work.h" #include "http_exec.h" -#include "netstack_base_async_work.h" -#include "netstack_napi_utils.h" +#include "base_async_work.h" +#include "napi_utils.h" namespace OHOS::NetStack { void HttpAsyncWork::ExecRequest(napi_env env, void *data) @@ -49,4 +49,4 @@ void HttpAsyncWork::DeleteCallback(napi_env env, napi_status status, void *data) { BaseAsyncWork::AsyncWorkCallback(env, status, data); } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/http/http_exec/src/http_exec.cpp b/frameworks/js/napi/http/http_exec/src/http_exec.cpp index d8a3266025a978cb6788528f1d49f743931917b0..d63a95e0590dffcdb5c0fc31a2713df4572e64e5 100644 --- a/frameworks/js/napi/http/http_exec/src/http_exec.cpp +++ b/frameworks/js/napi/http/http_exec/src/http_exec.cpp @@ -25,7 +25,7 @@ #include "http_time.h" #include "netstack_common_utils.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" #include "securec.h" #include "http_exec.h" diff --git a/frameworks/js/napi/http/http_module/src/http_module.cpp b/frameworks/js/napi/http/http_module/src/http_module.cpp index 6b3dfd06048bdf15a2b0c99a19b25abcc4694693..f5d8c71b3daf1ad6e332dd56322765c708ef686b 100644 --- a/frameworks/js/napi/http/http_module/src/http_module.cpp +++ b/frameworks/js/napi/http/http_module/src/http_module.cpp @@ -21,7 +21,7 @@ #include "http_async_work.h" #include "http_exec.h" #include "netstack_log.h" -#include "netstack_module_template.h" +#include "module_template.h" #define DECLARE_RESPONSE_CODE(code) \ DECLARE_NAPI_STATIC_PROPERTY(#code, NapiUtils::CreateUint32(env, static_cast(ResponseCode::code))) diff --git a/frameworks/js/napi/socket/BUILD.gn b/frameworks/js/napi/socket/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..32956cbbc78dd470e1b890d81c8219a52930a2fe --- /dev/null +++ b/frameworks/js/napi/socket/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2021-2022 Huawei Device 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. + +import("//build/ohos.gni") +import("//foundation/communication/netstack/netstack_config.gni") + +ohos_shared_library("socket") { + include_dirs = [ + "async_context/include", + "async_work/include", + "constant/include", + "socket_exec/include", + "socket_module/include", + "options/include", + "task_queue/include", + ] + + sources = [ + "async_context/src/bind_context.cpp", + "async_context/src/common_context.cpp", + "async_context/src/connect_context.cpp", + "async_context/src/tcp_extra_context.cpp", + "async_context/src/tcp_send_context.cpp", + "async_context/src/udp_extra_context.cpp", + "async_context/src/udp_send_context.cpp", + "async_work/src/socket_async_work.cpp", + "options/src/extra_options_base.cpp", + "options/src/net_address.cpp", + "options/src/socket_remote_info.cpp", + "options/src/socket_state_base.cpp", + "options/src/tcp_connect_options.cpp", + "options/src/tcp_extra_options.cpp", + "options/src/tcp_send_options.cpp", + "options/src/udp_extra_options.cpp", + "options/src/udp_send_options.cpp", + "socket_exec/src/socket_exec.cpp", + "socket_module/src/socket_module.cpp", + ] + + deps = [ "$NETSTACK_DIR/utils/napi_utils:napi_utils" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "napi:ace_napi", + ] + + relative_install_dir = "module/net" + part_name = "netstack" + subsystem_name = "communication" +} diff --git a/frameworks/js/napi/socket/async_context/include/bind_context.h b/frameworks/js/napi/socket/async_context/include/bind_context.h index 4b9cdb63f0938b8aa513e3b57c245652d0d092dc..385d6e42ee80cbe97117e437c72cc293e9b453b8 100644 --- a/frameworks/js/napi/socket/async_context/include/bind_context.h +++ b/frameworks/js/napi/socket/async_context/include/bind_context.h @@ -20,7 +20,7 @@ #include "napi/native_api.h" #include "net_address.h" -#include "netstack_base_context.h" +#include "base_context.h" #include "nocopyable.h" namespace OHOS::NetStack { diff --git a/frameworks/js/napi/socket/async_context/include/common_context.h b/frameworks/js/napi/socket/async_context/include/common_context.h index 79cc3dfc9004c090bcc5d8f1b5fdf8cabb0052a6..9e79d6ecc4bab451e56a74cdb9a220f617738d78 100644 --- a/frameworks/js/napi/socket/async_context/include/common_context.h +++ b/frameworks/js/napi/socket/async_context/include/common_context.h @@ -20,7 +20,7 @@ #include "napi/native_api.h" #include "net_address.h" -#include "netstack_base_context.h" +#include "base_context.h" #include "nocopyable.h" #include "socket_remote_info.h" #include "socket_state_base.h" diff --git a/frameworks/js/napi/socket/async_context/include/connect_context.h b/frameworks/js/napi/socket/async_context/include/connect_context.h index 55d28000e55152266dbd8ba087c827051978398f..c424060153b245ab2782baaad8d0ef3ad57b4eb7 100644 --- a/frameworks/js/napi/socket/async_context/include/connect_context.h +++ b/frameworks/js/napi/socket/async_context/include/connect_context.h @@ -19,7 +19,7 @@ #include #include "napi/native_api.h" -#include "netstack_base_context.h" +#include "base_context.h" #include "nocopyable.h" #include "tcp_connect_options.h" diff --git a/frameworks/js/napi/socket/async_context/include/tcp_extra_context.h b/frameworks/js/napi/socket/async_context/include/tcp_extra_context.h index bad6257af78286dae6622f476d477de4eeb51939..47ea0fb0da6827c6864fc20203ecf26bd4ec3883 100644 --- a/frameworks/js/napi/socket/async_context/include/tcp_extra_context.h +++ b/frameworks/js/napi/socket/async_context/include/tcp_extra_context.h @@ -19,7 +19,7 @@ #include #include "napi/native_api.h" -#include "netstack_base_context.h" +#include "base_context.h" #include "nocopyable.h" #include "tcp_extra_options.h" diff --git a/frameworks/js/napi/socket/async_context/include/tcp_send_context.h b/frameworks/js/napi/socket/async_context/include/tcp_send_context.h index 4d52fc4429b7deb3d00f4bc2e535984282acbf65..e477b69421205b06f8241a396a63730bbb4f4d92 100644 --- a/frameworks/js/napi/socket/async_context/include/tcp_send_context.h +++ b/frameworks/js/napi/socket/async_context/include/tcp_send_context.h @@ -19,7 +19,7 @@ #include #include "napi/native_api.h" -#include "netstack_base_context.h" +#include "base_context.h" #include "nocopyable.h" #include "tcp_send_options.h" diff --git a/frameworks/js/napi/socket/async_context/include/udp_extra_context.h b/frameworks/js/napi/socket/async_context/include/udp_extra_context.h index cc9021dc980b1584c70a0cd2733ddd9fb3b9fbbe..c6f8dee8372fee4ac16252ca5819505197418ca0 100644 --- a/frameworks/js/napi/socket/async_context/include/udp_extra_context.h +++ b/frameworks/js/napi/socket/async_context/include/udp_extra_context.h @@ -19,7 +19,7 @@ #include #include "napi/native_api.h" -#include "netstack_base_context.h" +#include "base_context.h" #include "nocopyable.h" #include "udp_extra_options.h" diff --git a/frameworks/js/napi/socket/async_context/include/udp_send_context.h b/frameworks/js/napi/socket/async_context/include/udp_send_context.h index 45177aaf9c07858b34f0571f53c94b9877212d16..f791532c826335b5dcec5ac9470db2c264b076f4 100644 --- a/frameworks/js/napi/socket/async_context/include/udp_send_context.h +++ b/frameworks/js/napi/socket/async_context/include/udp_send_context.h @@ -19,7 +19,7 @@ #include #include "napi/native_api.h" -#include "netstack_base_context.h" +#include "base_context.h" #include "nocopyable.h" #include "udp_send_options.h" diff --git a/frameworks/js/napi/socket/async_context/src/bind_context.cpp b/frameworks/js/napi/socket/async_context/src/bind_context.cpp index eefba401863e0f466ea01999acba693f20c69261..976ebbda18b6e091d55aac28a8ab49d82bc7c6ae 100644 --- a/frameworks/js/napi/socket/async_context/src/bind_context.cpp +++ b/frameworks/js/napi/socket/async_context/src/bind_context.cpp @@ -16,9 +16,9 @@ #include "bind_context.h" #include "context_key.h" -#include "netstack_event_manager.h" +#include "event_manager.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" namespace OHOS::NetStack { BindContext::BindContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} diff --git a/frameworks/js/napi/socket/async_context/src/common_context.cpp b/frameworks/js/napi/socket/async_context/src/common_context.cpp index 0673641013a72b93fee204c2a0e58e6186eda2cd..5d4677201e103499c581ae96eefeb28945d80249 100644 --- a/frameworks/js/napi/socket/async_context/src/common_context.cpp +++ b/frameworks/js/napi/socket/async_context/src/common_context.cpp @@ -16,8 +16,8 @@ #include "common_context.h" #include "context_key.h" -#include "netstack_event_manager.h" -#include "netstack_napi_utils.h" +#include "event_manager.h" +#include "napi_utils.h" namespace OHOS::NetStack { CommonContext::CommonContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} @@ -59,4 +59,4 @@ void CloseContext::SetSocketFd(int sock) { manager_->SetData(reinterpret_cast(sock)); } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/socket/async_context/src/connect_context.cpp b/frameworks/js/napi/socket/async_context/src/connect_context.cpp index 999e21648dc4fb426512785ac892181f58df38af..c8ad5b9fbed68e7864f3a72109f09c814c7b65f1 100644 --- a/frameworks/js/napi/socket/async_context/src/connect_context.cpp +++ b/frameworks/js/napi/socket/async_context/src/connect_context.cpp @@ -17,9 +17,9 @@ #include "context_key.h" #include "net_address.h" -#include "netstack_event_manager.h" +#include "event_manager.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" namespace OHOS::NetStack { ConnectContext::ConnectContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} @@ -80,4 +80,4 @@ bool ConnectContext::CheckParamsType(napi_value *params, size_t paramsCount) } return false; } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/socket/async_context/src/tcp_extra_context.cpp b/frameworks/js/napi/socket/async_context/src/tcp_extra_context.cpp index b9e16805f8bdf4657854bba2ad5e82bf74960b08..56cc0713571fd509ee16c785346788687b461c3d 100644 --- a/frameworks/js/napi/socket/async_context/src/tcp_extra_context.cpp +++ b/frameworks/js/napi/socket/async_context/src/tcp_extra_context.cpp @@ -16,8 +16,8 @@ #include "tcp_extra_context.h" #include "context_key.h" -#include "netstack_event_manager.h" -#include "netstack_napi_utils.h" +#include "event_manager.h" +#include "napi_utils.h" namespace OHOS::NetStack { TcpSetExtraOptionsContext::TcpSetExtraOptionsContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} @@ -94,4 +94,4 @@ bool TcpSetExtraOptionsContext::CheckParamsType(napi_value *params, size_t param } return false; } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/socket/async_context/src/tcp_send_context.cpp b/frameworks/js/napi/socket/async_context/src/tcp_send_context.cpp index 90def4ba6ea7bfeb005a02b70ecbd051da7bd854..07313fd9de6d45eabd04acee94f3d646129f47ff 100644 --- a/frameworks/js/napi/socket/async_context/src/tcp_send_context.cpp +++ b/frameworks/js/napi/socket/async_context/src/tcp_send_context.cpp @@ -16,9 +16,9 @@ #include "tcp_send_context.h" #include "context_key.h" -#include "netstack_event_manager.h" +#include "event_manager.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" namespace OHOS::NetStack { TcpSendContext::TcpSendContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} @@ -88,4 +88,4 @@ bool TcpSendContext::GetData(napi_value udpSendOptions) } return false; } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/socket/async_context/src/udp_extra_context.cpp b/frameworks/js/napi/socket/async_context/src/udp_extra_context.cpp index cee7897bd232b4e02915003536077491bcf66e73..19f2ca47b300603178aca1f653601e92f356e2ca 100644 --- a/frameworks/js/napi/socket/async_context/src/udp_extra_context.cpp +++ b/frameworks/js/napi/socket/async_context/src/udp_extra_context.cpp @@ -16,8 +16,8 @@ #include "udp_extra_context.h" #include "context_key.h" -#include "netstack_event_manager.h" -#include "netstack_napi_utils.h" +#include "event_manager.h" +#include "napi_utils.h" namespace OHOS::NetStack { UdpSetExtraOptionsContext::UdpSetExtraOptionsContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} @@ -73,4 +73,4 @@ bool UdpSetExtraOptionsContext::CheckParamsType(napi_value *params, size_t param } return false; } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/socket/async_context/src/udp_send_context.cpp b/frameworks/js/napi/socket/async_context/src/udp_send_context.cpp index ae525330df6e362e2b104f7a24b138bca936cdaf..37a04ac28bad16bcf69349489031e025621de164 100644 --- a/frameworks/js/napi/socket/async_context/src/udp_send_context.cpp +++ b/frameworks/js/napi/socket/async_context/src/udp_send_context.cpp @@ -17,9 +17,9 @@ #include "context_key.h" #include "net_address.h" -#include "netstack_event_manager.h" +#include "event_manager.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" namespace OHOS::NetStack { UdpSendContext::UdpSendContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} diff --git a/frameworks/js/napi/socket/async_work/src/socket_async_work.cpp b/frameworks/js/napi/socket/async_work/src/socket_async_work.cpp index f4a75cac4c132e5438b5543c5a6de62d04e0b719..eebf822ed40aaaa99f31863bb63b8349f22292cc 100644 --- a/frameworks/js/napi/socket/async_work/src/socket_async_work.cpp +++ b/frameworks/js/napi/socket/async_work/src/socket_async_work.cpp @@ -18,7 +18,7 @@ #include "bind_context.h" #include "common_context.h" #include "connect_context.h" -#include "netstack_base_async_work.h" +#include "base_async_work.h" #include "socket_exec.h" #include "tcp_extra_context.h" #include "tcp_send_context.h" @@ -122,4 +122,4 @@ void SocketAsyncWork::UdpSetExtraOptionsCallback(napi_env env, napi_status statu BaseAsyncWork::AsyncWorkCallback(env, status, data); } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/socket/options/include/socket_remote_info.h b/frameworks/js/napi/socket/options/include/socket_remote_info.h index 6b6f11234bbbee6e879709f39455deffd19684a7..d5a5c75966338437833587385a4087a34805bcfb 100644 --- a/frameworks/js/napi/socket/options/include/socket_remote_info.h +++ b/frameworks/js/napi/socket/options/include/socket_remote_info.h @@ -19,6 +19,7 @@ #include #include #include +#include "bits/alltypes.h" #include "net_address.h" diff --git a/frameworks/js/napi/socket/socket_exec/src/socket_exec.cpp b/frameworks/js/napi/socket/socket_exec/src/socket_exec.cpp index 6758150ff70fcee9e207974061b77e56e7b6ceeb..0293372cd43d56396538df3957fdce9b3a29b7f4 100644 --- a/frameworks/js/napi/socket/socket_exec/src/socket_exec.cpp +++ b/frameworks/js/napi/socket/socket_exec/src/socket_exec.cpp @@ -28,7 +28,7 @@ #include "context_key.h" #include "event_list.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" #include "securec.h" static constexpr const int DEFAULT_BUFFER_SIZE = 8192; diff --git a/frameworks/js/napi/socket/socket_module/src/socket_module.cpp b/frameworks/js/napi/socket/socket_module/src/socket_module.cpp index 0b17376d2d0fa2e7b97aa476b4437fdbea727d20..84b9f381f03175f1a64ab3dc2a6608b3d32903d8 100644 --- a/frameworks/js/napi/socket/socket_module/src/socket_module.cpp +++ b/frameworks/js/napi/socket/socket_module/src/socket_module.cpp @@ -29,10 +29,10 @@ #include "napi/native_api.h" #include "napi/native_common.h" #include "net_address.h" -#include "netstack_event_manager.h" +#include "event_manager.h" #include "netstack_log.h" -#include "netstack_module_template.h" -#include "netstack_napi_utils.h" +#include "module_template.h" +#include "napi_utils.h" #include "node_api.h" #include "socket_async_work.h" #include "socket_exec.h" @@ -276,4 +276,4 @@ extern "C" __attribute__((constructor)) void RegisterSocketModule(void) { napi_module_register(&g_socketModule); } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/socket/task_queue/include/task_queue.h b/frameworks/js/napi/socket/task_queue/include/task_queue.h index 57a56c79abeaaca71856521b6bc25e2d81111d3c..efa3b2b9f80afdb47195f0b1f6d0cdcc49b8bfd1 100644 --- a/frameworks/js/napi/socket/task_queue/include/task_queue.h +++ b/frameworks/js/napi/socket/task_queue/include/task_queue.h @@ -16,7 +16,7 @@ #ifndef COMMUNICATIONNETSTACK_TASK_QUEUE_H #define COMMUNICATIONNETSTACK_TASK_QUEUE_H -#include "netstack_base_context.h" +#include "base_context.h" namespace OHOS::NetStack::Task { enum class TaskPriority { diff --git a/frameworks/js/napi/tls/BUILD.gn b/frameworks/js/napi/tls/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..eb35736149055cd636dbc90bd68f44302ea32c29 --- /dev/null +++ b/frameworks/js/napi/tls/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021-2022 Huawei Device 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. + +import("//build/ohos.gni") +import("//foundation/communication/netstack/netstack_config.gni") + +config("tlssocket_config") { + visibility = [ ":tlssocket" ] + include_dirs = [ + "include", + "include/context", + "NETSTACK_INNERKITS_DIR/tls_socket/include", + ] +} + +ohos_shared_library("tlssocket") { + sources = [ + "src/context/close_context.cpp", + "src/context/connect_context.cpp", + "src/context/get_certificate_context.cpp", + "src/context/get_cipher_suites_context.cpp", + "src/context/get_protocol_context.cpp", + "src/context/get_remote_certificate_context.cpp", + "src/context/get_signature_algorithms_context.cpp", + "src/tlssocket_async_work.cpp", + "src/tlssocket_exec.cpp", + "src/tlssocket_module.cpp", + ] + + configs = [ ":tlssocket_config" ] + + deps = [ + "$NETSTACK_DIR/frameworks/native/tls_socket:tls_socket", + "$NETSTACK_DIR/utils/napi_utils:napi_utils", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "napi:ace_napi", + ] + + relative_install_dir = "module/net" + part_name = "netstack" + subsystem_name = "communication" +} diff --git a/frameworks/js/napi/tls/include/constant.h b/frameworks/js/napi/tls/include/constant.h new file mode 100644 index 0000000000000000000000000000000000000000..14b50f8caf55262b6853a06367cc029b3e2a99d0 --- /dev/null +++ b/frameworks/js/napi/tls/include/constant.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Device 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. + */ + +#ifndef TLS_CONSTANT_H +#define TLS_CONSTANT_H + +namespace OHOS { +namespace NetStack { +constexpr int PARAM_NONE = 0; +constexpr int PARAM_JUST_OPTIONS = 1; +constexpr int PARAM_JUST_CALLBACK = 1; +constexpr int PARAM_DOUBLE_OPTIONS = 2; +constexpr int PARAM_TRIPLE_OPTIONS = 3; +constexpr int PARAM_OPTIONS_AND_CALLBACK = 2; +constexpr int PARAM_DOUBLE_OPTIONS_AND_CALLBACK = 3; +constexpr int PARAM_TRIPLE_OPTIONS_AND_CALLBACK = 4; + +enum { + ARG_NUM_0, + ARG_NUM_1, + ARG_NUM_2, +}; + +enum { + ARG_INDEX_0 = 0, + ARG_INDEX_1, + ARG_INDEX_2, + ARG_INDEX_3, +}; +} // namespace NetStack +} //namespace OHOS +#endif // TLS_CONSTANT_H diff --git a/frameworks/js/napi/tls/include/context/close_context.h b/frameworks/js/napi/tls/include/context/close_context.h new file mode 100644 index 0000000000000000000000000000000000000000..9bba6a603c23b4617432f8401888d7c95014c961 --- /dev/null +++ b/frameworks/js/napi/tls/include/context/close_context.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Device 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. + */ + +#ifndef TLS_CONTEXT_CLOSE_CONTEXT_H +#define TLS_CONTEXT_CLOSE_CONTEXT_H + +#include + +#include + +#include "base_context.h" +#include "event_manager.h" +#include "nocopyable.h" + +namespace OHOS { +namespace NetStack { +class CloseContext final : public BaseContext { +public: + DISALLOW_COPY_AND_MOVE(CloseContext); + + CloseContext() = delete; + explicit CloseContext(napi_env env, EventManager *manager); + + bool ok_ = false; + + void ParseParams(napi_value *params, size_t paramsCount); + +private: + bool CheckParamsType(napi_value *params, size_t paramsCount); + +}; +} // namespace NetStack +} // namespace OHOS +#endif // TLS_CONTEXT_CLOSE_CONTEXT_H diff --git a/frameworks/js/napi/tls/include/context/connect_context.h b/frameworks/js/napi/tls/include/context/connect_context.h new file mode 100644 index 0000000000000000000000000000000000000000..d412efc7d0b1d76861d7c253d823fdd8e2234b3a --- /dev/null +++ b/frameworks/js/napi/tls/include/context/connect_context.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Device 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. + */ + +#ifndef TLS_CONTEXT_CONNECT_CONTEXT_H +#define TLS_CONTEXT_CONNECT_CONTEXT_H + +#include + +#include + +#include "base_context.h" +#include "event_manager.h" +#include "nocopyable.h" +#include "tls.h" +#include "tls_socket.h" + +namespace OHOS { +namespace NetStack { +class ConnectContext final : public BaseContext { +public: + DISALLOW_COPY_AND_MOVE(ConnectContext); + + ConnectContext() = delete; + explicit ConnectContext(napi_env env, EventManager *manager); + + TLSConnectOptions connectOptions_; + bool ok_ = false; + + void ParseParams(napi_value *params, size_t paramsCount); + +private: + bool CheckParamsType(napi_value *params, size_t paramsCount); + TLSConnectOptions ReadTlsConnectOptions(napi_env env, napi_value *params); + TLSSecureOptions ReadTlsSecureOptions(napi_env env, napi_value *params); + NetAddress ReadNetAddress(napi_env env, napi_value *params); +}; +} // namespace NetStack +} // namespace OHOS +#endif // TLS_CONTEXT_CONNECT_CONTEXT_H diff --git a/frameworks/js/napi/tls/include/context/get_certificate_context.h b/frameworks/js/napi/tls/include/context/get_certificate_context.h new file mode 100644 index 0000000000000000000000000000000000000000..6b34c767c7471649e996a12a3f231799d0cbe26c --- /dev/null +++ b/frameworks/js/napi/tls/include/context/get_certificate_context.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device 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. + */ + +#ifndef TLS_CONTEXT_GETCERTIFICATE_CONTEXT_H +#define TLS_CONTEXT_GETCERTIFICATE_CONTEXT_H + +#include +#include + +#include + +#include "base_context.h" +#include "event_manager.h" +#include "nocopyable.h" + +namespace OHOS { +namespace NetStack { +class GetCertificateContext final : public BaseContext { +public: + DISALLOW_COPY_AND_MOVE(GetCertificateContext); + + GetCertificateContext() = delete; + explicit GetCertificateContext(napi_env env, EventManager *manager); + + std::string cert_; + bool ok_ = false; + + void ParseParams(napi_value *params, size_t paramsCount); + +private: + bool CheckParamsType(napi_value *params, size_t paramsCount); + +}; +} // namespace NetStack +} // namespace OHOS +#endif // TLS_CONTEXT_GETCERTIFICATE_CONTEXT_H diff --git a/frameworks/js/napi/tls/include/context/get_cipher_suites_context.h b/frameworks/js/napi/tls/include/context/get_cipher_suites_context.h new file mode 100644 index 0000000000000000000000000000000000000000..6bd1865ebb59246700a757e241f0d6e43514aa77 --- /dev/null +++ b/frameworks/js/napi/tls/include/context/get_cipher_suites_context.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Device 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. + */ + +#ifndef TLS_CONTEXT_GETCIPHERSUITES_CONTEXT_H +#define TLS_CONTEXT_GETCIPHERSUITES_CONTEXT_H + +#include +#include +#include + +#include + +#include "base_context.h" +#include "event_manager.h" +#include "nocopyable.h" +#include "tls.h" + +namespace OHOS { +namespace NetStack { +class GetCipherSuitesContext final : public BaseContext { +public: + DISALLOW_COPY_AND_MOVE(GetCipherSuitesContext); + + GetCipherSuitesContext() = delete; + explicit GetCipherSuitesContext(napi_env env, EventManager *manager); + + std::vector cipherSuites_; + bool ok_ = false; + + void ParseParams(napi_value *params, size_t paramsCount); + +private: + bool CheckParamsType(napi_value *params, size_t paramsCount); +}; +} // namespace NetStack +} // namespace OHOS +#endif // TLS_CONTEXT_GETCIPHERSUITES_CONTEXT_H diff --git a/frameworks/js/napi/tls/include/context/get_protocol_context.h b/frameworks/js/napi/tls/include/context/get_protocol_context.h new file mode 100644 index 0000000000000000000000000000000000000000..4d799c92ac2ff5a9bffd01572c96581175a5fdad --- /dev/null +++ b/frameworks/js/napi/tls/include/context/get_protocol_context.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 Huawei Device 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. + */ + +#ifndef TLS_CONTEXT_GETPROTOCOL_CONTEXT_H +#define TLS_CONTEXT_GETPROTOCOL_CONTEXT_H + +#include +#include + +#include + +#include "base_context.h" +#include "event_manager.h" +#include "nocopyable.h" + +namespace OHOS { +namespace NetStack { +class GetProtocolContext final :public BaseContext { +public: + DISALLOW_COPY_AND_MOVE(GetProtocolContext); + + GetProtocolContext() = delete; + explicit GetProtocolContext(napi_env env, EventManager *manager); + + std::string protocol_; + bool ok_ = false; + + void ParseParams(napi_value *params, size_t paramsCount); + +private: + bool CheckParamsType(napi_value *params, size_t paramsCount); +}; +} // namespace NetStack +} // namespace OHOS +#endif // TLS_CONTEXT_GETPROTOCOL_CONTEXT_H diff --git a/frameworks/js/napi/tls/include/context/get_remote_certificate_context.h b/frameworks/js/napi/tls/include/context/get_remote_certificate_context.h new file mode 100644 index 0000000000000000000000000000000000000000..f6753bbbf2f196208a6b7265480272b543cc9b81 --- /dev/null +++ b/frameworks/js/napi/tls/include/context/get_remote_certificate_context.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device 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. + */ + +#ifndef TLS_CONTEXT_GETREMOTECERTIFICATE_CONTEXT_H +#define TLS_CONTEXT_GETREMOTECERTIFICATE_CONTEXT_H + +#include +#include + +#include + +#include "base_context.h" +#include "event_manager.h" +#include "nocopyable.h" + +namespace OHOS { +namespace NetStack { +class GetRemoteCertificateContext final : public BaseContext { +public: + DISALLOW_COPY_AND_MOVE(GetRemoteCertificateContext); + + GetRemoteCertificateContext() = delete; + explicit GetRemoteCertificateContext(napi_env env, EventManager *manager); + + bool needChain_ = false; + bool ok_ = false; + std::string remoteCert_; + + void ParseParams(napi_value *params, size_t paramsCount); + +private: + bool CheckParamsType(napi_value *params, size_t paramsCount); +}; +} // namespace NetStack +} // namespace OHOS +#endif // TLS_CONTEXT_GETREMOTECERTIFICATE_CONTEXT_H diff --git a/frameworks/js/napi/tls/include/context/get_signature_algorithms_context.h b/frameworks/js/napi/tls/include/context/get_signature_algorithms_context.h new file mode 100644 index 0000000000000000000000000000000000000000..7dbcaba8d35e631a5ce7d1b39be89014130524a6 --- /dev/null +++ b/frameworks/js/napi/tls/include/context/get_signature_algorithms_context.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device 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. + */ + +#ifndef TLS_CONTEXT_GET_SIGNATURE_ALGORITHMS_CONTEXT_H +#define TLS_CONTEXT_GET_SIGNATURE_ALGORITHMS_CONTEXT_H + +#include +#include +#include + +#include + +#include "base_context.h" +#include "event_manager.h" +#include "nocopyable.h" + +namespace OHOS { +namespace NetStack { +class GetSignatureAlgorithmsContext final : public BaseContext { +public: + DISALLOW_COPY_AND_MOVE(GetSignatureAlgorithmsContext); + + GetSignatureAlgorithmsContext() = delete; + explicit GetSignatureAlgorithmsContext(napi_env env, EventManager *manager); + + std::vector signatureAlgorithms_; + bool ok_ = false; + + void ParseParams(napi_value *params, size_t paramsCount); + +private: + bool CheckParamsType(napi_value *params, size_t paramsCount); +}; +} // namespace NetStack +} // namespace OHOS +#endif // TLS_CONTEXT_GET_SIGNATURE_ALGORITHMS_CONTEXT_H diff --git a/frameworks/js/napi/tls/include/tlssocket_async_work.h b/frameworks/js/napi/tls/include/tlssocket_async_work.h new file mode 100644 index 0000000000000000000000000000000000000000..102c921762bda522017d7a65b08f0377761733fb --- /dev/null +++ b/frameworks/js/napi/tls/include/tlssocket_async_work.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Device 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. + */ + +#ifndef TLS_TLSSOCKET_ASYNC_WORK_H +#define TLS_TLSSOCKET_ASYNC_WORK_H + +#include + +#include "nocopyable.h" + +namespace OHOS { +namespace NetStack { +class TlsSocketAsyncWork final { +public: + DISALLOW_COPY_AND_MOVE(TlsSocketAsyncWork); + TlsSocketAsyncWork() = delete; + ~TlsSocketAsyncWork() = delete; + + static void ExecGetCertificate(napi_env env, void *data); + static void ExecConnect(napi_env env, void *data); + static void ExecGetCipherSuites(napi_env env, void *data); + static void ExecGetRemoteCertificate(napi_env env, void *data); + static void ExecGetProtocol(napi_env env, void *data); + static void ExecGetSignatureAlgorithms(napi_env env, void *data); + static void ExecClose(napi_env env, void *data); + + static void GetCertificateCallback(napi_env env, napi_status status, void *data); + static void ConnectCallback(napi_env env, napi_status status, void *data); + static void GetCipherSuitesCallback(napi_env env, napi_status status, void *data); + static void GetRemoteCertificateCallback(napi_env env, napi_status status, void *data); + static void GetProtocolCallback(napi_env env, napi_status status, void *data); + static void GetSignatureAlgorithmsCallback(napi_env env, napi_status status, void *data); + static void CloseCallback(napi_env env, napi_status status, void *data); +}; +} // namespace NetStack +} // namespace OHOS +#endif // TLS_TLSSOCKET_ASYNC_WORK_H diff --git a/frameworks/js/napi/tls/include/tlssocket_exec.h b/frameworks/js/napi/tls/include/tlssocket_exec.h new file mode 100644 index 0000000000000000000000000000000000000000..f3239e9926eb2c12f3e0fbefca6d02c8d3ab1184 --- /dev/null +++ b/frameworks/js/napi/tls/include/tlssocket_exec.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Device 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. + */ + +#ifndef TLS_TLSSOCKET_EXEC_H +#define TLS_TLSSOCKET_EXEC_H + +#include + +#include "connect_context.h" +#include "close_context.h" +#include "get_certificate_context.h" +#include "get_cipher_suites_context.h" +#include "get_protocol_context.h" +#include "get_remote_certificate_context.h" +#include "get_signature_algorithms_context.h" + +namespace OHOS { +namespace NetStack { +class TlsSocketExec final { +public: + DISALLOW_COPY_AND_MOVE(TlsSocketExec); + + TlsSocketExec() = delete; + ~TlsSocketExec() = delete; + + static bool ExecGetCertificate(GetCertificateContext *context); + static bool ExecConnect(ConnectContext *context); + static bool ExecGetCipherSuites(GetCipherSuitesContext *context); + static bool ExecGetRemoteCertificate(GetRemoteCertificateContext *context); + static bool ExecGetProtocol(GetProtocolContext *context); + static bool ExecGetSignatureAlgorithms(GetSignatureAlgorithmsContext *context); + static bool ExecClose(CloseContext *context); + + static napi_value GetCertificateCallback(GetCertificateContext *context); + static napi_value ConnectCallback(ConnectContext *context); + static napi_value GetCipherSuitesCallback(GetCipherSuitesContext *context); + static napi_value GetRemoteCertificateCallback(GetRemoteCertificateContext *context); + static napi_value GetProtocolCallback(GetProtocolContext *context); + static napi_value GetSignatureAlgorithmsCallback(GetSignatureAlgorithmsContext *context); + static napi_value CloseCallback(CloseContext *context); +}; +} // namespace NetStack +} // namespace OHOS +#endif // TLS_TLSSOCKET_EXEC_H diff --git a/frameworks/js/napi/tls/include/tlssocket_module.h b/frameworks/js/napi/tls/include/tlssocket_module.h new file mode 100644 index 0000000000000000000000000000000000000000..82f1c5b9fc33a05e51d0d4fe36f3bcaa12ec0fe2 --- /dev/null +++ b/frameworks/js/napi/tls/include/tlssocket_module.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2021-2022 Huawei Device 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. + */ + +#ifndef TLS_TLSSOCKET_MODULE_H +#define TLS_TLSSOCKET_MODULE_H + +#include "napi/native_api.h" + +namespace OHOS { +namespace NetStack { +class TLSSocketModuleExports { +public: + class TLSSocket { + public: + static constexpr const char *FUNCTION_GET_CERTIFICATE = "getCertificate"; + static constexpr const char *FUNCTION_GET_REMOTE_CERTIFICATE = "getRemoteCertificate"; + static constexpr const char *FUNCTION_GET_SIGNATURE_ALGORITHMS = "getSignatureAlgorithms"; + static constexpr const char *FUNCTION_GET_PROTOCOL ="getProtocol"; + static constexpr const char *FUNCTION_CONNECT ="connect"; + static constexpr const char *FUNCTION_GET_CIPHER_SUITES = "getCipherSuites"; + static constexpr const char *FUNCTION_CLOSE = "close"; + + static napi_value GetCertificate(napi_env env, napi_callback_info info); + static napi_value GetProtocol(napi_env env, napi_callback_info info); + static napi_value Connect(napi_env env, napi_callback_info info); + static napi_value GetCipherSuites(napi_env env, napi_callback_info info); + static napi_value GetRemoteCertificate(napi_env env, napi_callback_info info); + static napi_value GetSignatureAlgorithms(napi_env env, napi_callback_info info); + static napi_value Close(napi_env env, napi_callback_info info); + }; + +public: + static constexpr const char *INTERFACE_TLS_SOCKET = "TLSSocket"; + static constexpr const char *FUNCTION_CONSTRUCTOR_TLS_SOCKET_INSTANCE = "constructTLSSocketInstance"; + + static napi_value InitTLSSocketModule(napi_env env, napi_value exports); + +private: + static napi_value ConstructTLSSocketInstance(napi_env env, napi_callback_info info); + static void DefineTLSSocketClass(napi_env env, napi_value exports); + static void InitTLSSocketProperties(napi_env env, napi_value exports); +}; +} // namespace NetStack +} // namespace OHOS +#endif // TLS_TLSSOCKET_MODULE_H diff --git a/frameworks/js/napi/tls/src/context/close_context.cpp b/frameworks/js/napi/tls/src/context/close_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac0b9beb7e583caa37de43e9087f11329b8d62f8 --- /dev/null +++ b/frameworks/js/napi/tls/src/context/close_context.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Device 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 "close_context.h" + +#include "constant.h" +#include "napi_utils.h" +#include "netstack_log.h" + +namespace OHOS { +namespace NetStack { +CloseContext::CloseContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} + +void CloseContext::ParseParams(napi_value *params, size_t paramsCount) +{ + if (!CheckParamsType(params, paramsCount)) { + return; + } + if (paramsCount == PARAM_JUST_CALLBACK) { + SetParseOK(SetCallback(params[ARG_INDEX_0]) == napi_ok); + return; + } + SetParseOK(true); +} + +bool CloseContext::CheckParamsType(napi_value *params, size_t paramsCount) +{ + if (paramsCount == PARAM_NONE) { + return true; + } + + if (paramsCount == PARAM_JUST_CALLBACK) { + if (NapiUtils::GetValueType(GetEnv(), params[ARG_INDEX_0]) != napi_function) { + NETSTACK_LOGE("CloseContext first param is not function"); + return false; + } + return true; + } + return false; +} +} // namespace NetStack +} // namespace OHOS diff --git a/frameworks/js/napi/tls/src/context/connect_context.cpp b/frameworks/js/napi/tls/src/context/connect_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6ae85a1399926e372d6eb7d3d081d8da77ea758c --- /dev/null +++ b/frameworks/js/napi/tls/src/context/connect_context.cpp @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2022 Huawei Device 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 "connect_context.h" + +#include +#include +#include + +#include "constant.h" +#include "napi_utils.h" +#include "netstack_log.h" + +namespace OHOS { +namespace NetStack { +ConnectContext::ConnectContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} + +void ConnectContext::ParseParams(napi_value *params, size_t paramsCount) +{ + if (!CheckParamsType(params, paramsCount)) { + return; + } + connectOptions_ = ReadTlsConnectOptions(GetEnv(), params); + + if (paramsCount == PARAM_OPTIONS_AND_CALLBACK) { + SetParseOK(SetCallback(params[ARG_INDEX_1]) == napi_ok); + return; + } + SetParseOK(true); +} + +bool ConnectContext::CheckParamsType(napi_value *params, size_t paramsCount) +{ + if (paramsCount == PARAM_JUST_OPTIONS) { + if (NapiUtils::GetValueType(GetEnv(), params[ARG_INDEX_0]) != napi_object) { + NETSTACK_LOGE("tlsConnectContext first param is not object"); + return false; + } + return true; + } + + if (paramsCount == PARAM_OPTIONS_AND_CALLBACK) { + if (NapiUtils::GetValueType(GetEnv(), params[ARG_INDEX_0]) != napi_object) { + NETSTACK_LOGE("tls ConnectContext first param is not number"); + return false; + } + if (NapiUtils::GetValueType(GetEnv(), params[ARG_INDEX_1]) != napi_function) { + NETSTACK_LOGE(" tls ConnectContext second param is not function"); + return false; + } + return true; + } + return false; +} + +TLSConnectOptions ConnectContext::ReadTlsConnectOptions(napi_env env, napi_value *params) +{ + TLSConnectOptions options; + NetAddress address = ReadNetAddress(GetEnv(), params); + TLSSecureOptions secureOption = ReadTlsSecureOptions(GetEnv(), params); + options.SetNetAddress(address); + options.SetTlsSecureOptions(secureOption); + //alpnProtocols + if (NapiUtils::HasNamedProperty(GetEnv(), params[0], "ALPNProtocols")) { + napi_value alpnProtocols = NapiUtils::GetNamedProperty(GetEnv(), params[0], "ALPNProtocols"); + uint32_t arrayLength = NapiUtils::GetArrayLength(GetEnv(), alpnProtocols); + napi_value elementValue = nullptr; + std::vector alpnProtocolVec; + for (uint32_t i = 0; i < arrayLength; i++) { + elementValue = NapiUtils::GetArrayElement(GetEnv(), alpnProtocols, i); + std::string alpnProtocol = NapiUtils::GetStringFromValueUtf8(GetEnv(), elementValue); + alpnProtocolVec.push_back(alpnProtocol); + } + options.SetAlpnProtocols(alpnProtocolVec); + } + NETSTACK_LOGI("ConnectContext::ReadTlsConnectOptions(napi_env env, napi_value *params) end"); + return options; +} + +TLSSecureOptions ConnectContext::ReadTlsSecureOptions(napi_env env, napi_value *params) +{ + TLSSecureOptions secureOption; + //caVector + napi_value secureOptions = NapiUtils::GetNamedProperty(GetEnv(), params[ARG_INDEX_0], "secureOptions"); + if (NapiUtils::HasNamedProperty(GetEnv(), secureOptions, "ca")) { + napi_value caVector = NapiUtils::GetNamedProperty(GetEnv(), secureOptions, "ca"); + uint32_t arrayLong = NapiUtils::GetArrayLength(GetEnv(), caVector); + napi_value element = nullptr; + std::vector caVec; + for (uint32_t i = 0; i < arrayLong; i++) { + element = NapiUtils::GetArrayElement(GetEnv(), caVector, i); + std::string ca = NapiUtils::GetStringFromValueUtf8(GetEnv(), element); + caVec.push_back(ca); + } + secureOption.SetCaChain(caVec); + } + //key + std::string key = NapiUtils::GetStringPropertyUtf8(env, secureOptions, "key"); + secureOption.SetKey(key); + //cert + std::string cert = NapiUtils::GetStringPropertyUtf8(env, secureOptions, "cert"); + secureOption.SetCert(cert); + //passwd + std::string passwd = NapiUtils::GetStringPropertyUtf8(env, secureOptions, "passwd"); + secureOption.SetPassWd(passwd); + //protocol + std::string protocol = NapiUtils::GetStringPropertyUtf8(env, secureOptions, "protocols"); + std::vector protocolVec = {protocol}; + secureOption.SetProtocolChain(protocolVec); + //signatureAlgorithms + std::string signatureAlgorithms = NapiUtils::GetStringPropertyUtf8(env, secureOptions, "signatureAlgorithms"); + secureOption.SetSignatureAlgorithms(signatureAlgorithms); + //useRemoteCipherPrefer + bool useRemoteCipherPrefer = NapiUtils::GetBooleanProperty(env, secureOptions, "useRemoteCipherPrefer"); + secureOption.SetUseRemoteCipherPrefer(useRemoteCipherPrefer); + //cipherSuites + std::string cipherSuites = NapiUtils::GetStringPropertyUtf8(env, secureOptions, "cipherSuites"); + secureOption.SetCipherSuite(cipherSuites); + return secureOption; +} + +NetAddress ConnectContext::ReadNetAddress(napi_env env, napi_value *params) +{ + NetAddress address; + napi_value netAddress = NapiUtils::GetNamedProperty(GetEnv(), params[0], "address"); + + std::string addr = NapiUtils::GetStringPropertyUtf8(GetEnv(), netAddress, "address"); + address.SetAddress(addr); + uint32_t family = NapiUtils::GetUint32Property(GetEnv(), netAddress, "family"); + if (family == 1) { + address.SetFamilyBySaFamily(AF_INET); + } else { + address.SetFamilyBySaFamily(AF_INET6); + } + if (NapiUtils::HasNamedProperty(GetEnv(), netAddress, "port")) { + uint16_t port = static_cast(NapiUtils::GetUint32Property(GetEnv(), netAddress, "port")); + address.SetPort(port); + } + return address; +} +} // namespace NetStack +} // namespace OHOS diff --git a/frameworks/js/napi/tls/src/context/get_certificate_context.cpp b/frameworks/js/napi/tls/src/context/get_certificate_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e6c7cd0fed52d52fa6f3893e80d899e179e5b4f0 --- /dev/null +++ b/frameworks/js/napi/tls/src/context/get_certificate_context.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Device 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 "get_certificate_context.h" + +#include "constant.h" +#include "napi_utils.h" +#include "netstack_log.h" + +namespace OHOS { +namespace NetStack { +GetCertificateContext::GetCertificateContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} + +void GetCertificateContext::ParseParams(napi_value *params, size_t paramsCount) +{ + NETSTACK_LOGI("GetCertificateContext paramsCount is %{public}zu", paramsCount); + if (!CheckParamsType(params, paramsCount)) { + return; + } + if (paramsCount == PARAM_JUST_CALLBACK) { + SetParseOK(SetCallback(params[ARG_INDEX_0]) == napi_ok); + return; + } + SetParseOK(true); +} + +bool GetCertificateContext::CheckParamsType(napi_value *params, size_t paramsCount) +{ + if (paramsCount == PARAM_NONE) { + return true; + } + + if (paramsCount == PARAM_JUST_CALLBACK) { + if (NapiUtils::GetValueType(GetEnv(), params[ARG_INDEX_0]) != napi_function) { + NETSTACK_LOGE("GetCertificateContext first param is not function"); + return false; + } + return true; + } + return false; +} +} // namespace NetStack +} // namespace OHOS diff --git a/frameworks/js/napi/tls/src/context/get_cipher_suites_context.cpp b/frameworks/js/napi/tls/src/context/get_cipher_suites_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7cf2e1eed5b7de3950802ff420cd6626cbdc3ead --- /dev/null +++ b/frameworks/js/napi/tls/src/context/get_cipher_suites_context.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Device 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 "get_cipher_suites_context.h" + +#include "constant.h" +#include "napi_utils.h" +#include "netstack_log.h" + +namespace OHOS { +namespace NetStack { +GetCipherSuitesContext::GetCipherSuitesContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} + +void GetCipherSuitesContext::ParseParams(napi_value *params, size_t paramsCount) +{ + if (!CheckParamsType(params, paramsCount)) { + return; + } + if (paramsCount == PARAM_JUST_CALLBACK) { + SetParseOK(SetCallback(params[ARG_INDEX_0]) == napi_ok); + return; + } + SetParseOK(true); +} + +bool GetCipherSuitesContext::CheckParamsType(napi_value *params, size_t paramsCount) +{ + if (paramsCount == PARAM_NONE) { + return true; + } + + if (paramsCount == PARAM_JUST_CALLBACK) { + if (NapiUtils::GetValueType(GetEnv(), params[ARG_INDEX_0]) != napi_function) { + NETSTACK_LOGE("GetCipherSuitesContext first param is not function"); + return false; + } + return true; + } + return false; +} +} // namespace NetStack +} // namespace OHOS diff --git a/frameworks/js/napi/tls/src/context/get_protocol_context.cpp b/frameworks/js/napi/tls/src/context/get_protocol_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..25ff067cc59d817b70db91461fec477416a171bd --- /dev/null +++ b/frameworks/js/napi/tls/src/context/get_protocol_context.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Device 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 "get_protocol_context.h" + +#include "constant.h" +#include "napi_utils.h" +#include "netstack_log.h" + +namespace OHOS { +namespace NetStack { +GetProtocolContext::GetProtocolContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} + +void GetProtocolContext::ParseParams(napi_value *params, size_t paramsCount) +{ + if (!CheckParamsType(params, paramsCount)) { + return; + } + if (paramsCount == PARAM_JUST_CALLBACK) { + SetParseOK(SetCallback(params[ARG_INDEX_0]) == napi_ok); + return; + } + SetParseOK(true); +} + +bool GetProtocolContext::CheckParamsType(napi_value *params, size_t paramsCount) +{ + if (paramsCount == PARAM_NONE) { + return true; + } + + if (paramsCount == PARAM_JUST_CALLBACK) { + if (NapiUtils::GetValueType(GetEnv(), params[ARG_INDEX_0]) != napi_function) { + NETSTACK_LOGE("GetProtocolContext first param is not function"); + return false; + } + return true; + } + return false; +} +} // namespace NetStack +} // namespace OHOS diff --git a/frameworks/js/napi/tls/src/context/get_remote_certificate_context.cpp b/frameworks/js/napi/tls/src/context/get_remote_certificate_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f53aec9099f6149985d6228eac54539510daf92e --- /dev/null +++ b/frameworks/js/napi/tls/src/context/get_remote_certificate_context.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Device 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 "get_remote_certificate_context.h" + +#include "constant.h" +#include "napi_utils.h" +#include "netstack_log.h" + +namespace OHOS { +namespace NetStack { +GetRemoteCertificateContext::GetRemoteCertificateContext(napi_env env, EventManager *manager) + : BaseContext(env, manager) {} + +void GetRemoteCertificateContext::ParseParams(napi_value *params, size_t paramsCount) +{ + if (!CheckParamsType(params, paramsCount)) { + return; + } + if (paramsCount == PARAM_JUST_CALLBACK) { + SetParseOK(SetCallback(params[ARG_INDEX_0]) == napi_ok); + return; + } + SetParseOK(true); +} + +bool GetRemoteCertificateContext::CheckParamsType(napi_value *params, size_t paramsCount) +{ + if (paramsCount == PARAM_NONE) { + return true; + } + if (paramsCount == PARAM_JUST_CALLBACK) { + if (NapiUtils::GetValueType(GetEnv(), params[ARG_INDEX_0]) != napi_function) { + NETSTACK_LOGE("GetRemoteCertificateContext first param is not function"); + return false; + } + return true; + } + return false; +} +} // namespace NetStack +} // namespace OHOS diff --git a/frameworks/js/napi/tls/src/context/get_signature_algorithms_context.cpp b/frameworks/js/napi/tls/src/context/get_signature_algorithms_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd3941a45207dd0a2895f29b2ee4da82c0bae4d1 --- /dev/null +++ b/frameworks/js/napi/tls/src/context/get_signature_algorithms_context.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Device 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 "get_signature_algorithms_context.h" + +#include "constant.h" +#include "napi_utils.h" +#include "netstack_log.h" + +namespace OHOS { +namespace NetStack { +GetSignatureAlgorithmsContext::GetSignatureAlgorithmsContext(napi_env env, EventManager *manager) + : BaseContext(env, manager) {} + +void GetSignatureAlgorithmsContext::ParseParams(napi_value *params, size_t paramsCount) +{ + if (!CheckParamsType(params, paramsCount)) { + return; + } + if (paramsCount == PARAM_JUST_CALLBACK) { + SetParseOK(SetCallback(params[ARG_INDEX_0]) == napi_ok); + return; + } + SetParseOK(true); +} + +bool GetSignatureAlgorithmsContext::CheckParamsType(napi_value *params, size_t paramsCount) +{ + if (paramsCount == PARAM_NONE) { + return true; + } + + if (paramsCount == PARAM_JUST_CALLBACK) { + if (NapiUtils::GetValueType(GetEnv(), params[ARG_INDEX_0]) != napi_function) { + NETSTACK_LOGE("GetSignatureAlgorithmsContext first param is not function"); + return false; + } + return true; + } + return false; +} +} // namespace NetStack +} // namespace OHOS diff --git a/frameworks/js/napi/tls/src/tlssocket_async_work.cpp b/frameworks/js/napi/tls/src/tlssocket_async_work.cpp new file mode 100644 index 0000000000000000000000000000000000000000..163f041c0dd7c3c6f70a985363817026a4e80cd7 --- /dev/null +++ b/frameworks/js/napi/tls/src/tlssocket_async_work.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Device 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 "tlssocket_async_work.h" + +#include "base_async_work.h" +#include "connect_context.h" +#include "close_context.h" +#include "get_certificate_context.h" +#include "get_cipher_suites_context.h" +#include "get_remote_certificate_context.h" +#include "tlssocket_exec.h" + +namespace OHOS { +namespace NetStack { +void TlsSocketAsyncWork::ExecGetCertificate(napi_env env, void *data) +{ + BaseAsyncWork::ExecAsyncWork(env, data); +} + +void TlsSocketAsyncWork::ExecConnect(napi_env env, void *data) +{ + BaseAsyncWork::ExecAsyncWork(env, data); +} + +void TlsSocketAsyncWork::ExecGetCipherSuites(napi_env env, void *data) +{ + BaseAsyncWork::ExecAsyncWork(env, data); +} + +void TlsSocketAsyncWork::ExecGetRemoteCertificate(napi_env env, void *data) +{ + BaseAsyncWork::ExecAsyncWork(env, data); +} + +void TlsSocketAsyncWork::ExecGetProtocol(napi_env env, void *data) +{ + BaseAsyncWork::ExecAsyncWork(env, data); +} + +void TlsSocketAsyncWork::ExecGetSignatureAlgorithms(napi_env env, void *data) +{ + BaseAsyncWork::ExecAsyncWork(env, data); +} + +void TlsSocketAsyncWork::ExecClose(napi_env env, void *data) +{ + BaseAsyncWork::ExecAsyncWork(env, data); +} + +void TlsSocketAsyncWork::GetCertificateCallback(napi_env env, napi_status status, void *data) +{ + BaseAsyncWork::AsyncWorkCallback(env, status, data); +} + +void TlsSocketAsyncWork::ConnectCallback(napi_env env, napi_status status, void *data) +{ + BaseAsyncWork::AsyncWorkCallback(env, status, data); +} + +void TlsSocketAsyncWork::GetCipherSuitesCallback(napi_env env, napi_status status, void *data) +{ + BaseAsyncWork::AsyncWorkCallback(env, status, data); +} + +void TlsSocketAsyncWork::GetRemoteCertificateCallback(napi_env env, napi_status status, void *data) +{ + BaseAsyncWork::AsyncWorkCallback(env, status, data); +} + +void TlsSocketAsyncWork::GetProtocolCallback(napi_env env, napi_status status, void *data) +{ + BaseAsyncWork::AsyncWorkCallback(env, status, data); +} + +void TlsSocketAsyncWork::GetSignatureAlgorithmsCallback(napi_env env, napi_status status, void *data) +{ + BaseAsyncWork::AsyncWorkCallback(env, status, data); +} + +void TlsSocketAsyncWork::CloseCallback(napi_env env, napi_status status, void *data) +{ + BaseAsyncWork::AsyncWorkCallback(env, status, data); +} +} // namespace NetStack +} // namespace OHOS diff --git a/frameworks/js/napi/tls/src/tlssocket_exec.cpp b/frameworks/js/napi/tls/src/tlssocket_exec.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5799fc126ff2a0b267034aa2bd6d090df3c5b6f --- /dev/null +++ b/frameworks/js/napi/tls/src/tlssocket_exec.cpp @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2022 Huawei Device 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 "tlssocket_exec.h" + +#include + +#include "napi_utils.h" +#include "netstack_log.h" +#include "tls_socket.h" + +namespace OHOS { +namespace NetStack { +namespace { +void SendCustomData(TLSSocket *tlsSocket) +{ + TCPSendOptions tcpSendOptions; + tcpSendOptions.SetData("custom data"); + tlsSocket->Send(tcpSendOptions, [](bool ok) { + if (!ok) { + NETSTACK_LOGE("send custom data is failed"); + } + }); +} +} // namespace + +bool TlsSocketExec::ExecGetCertificate(GetCertificateContext *context) +{ + auto manager = context->GetManager(); + if (manager == nullptr) { + NETSTACK_LOGE("manager is nullptr"); + return false; + } + auto tlsSocket = reinterpret_cast(manager->GetData()); + if (tlsSocket == nullptr) { + NETSTACK_LOGE("TlsSocketExec::ExecGetCipherSuites tlsSocket is null"); + return false; + } + tlsSocket->GetCertificate([&context](bool ok, const std::string &cert) { + context->ok_ = ok; + context->cert_ = cert; + }); + return context->ok_; +} + +bool TlsSocketExec::ExecConnect(ConnectContext *context) +{ + auto manager = context->GetManager(); + if (manager == nullptr) { + NETSTACK_LOGE("manager is nullptr"); + return false; + } + if (manager->GetData() != nullptr) { + NETSTACK_LOGE("tls tlsSocket is existed"); + return false; + } + auto tlsSocket = new TLSSocket(); + tlsSocket->Connect(context->connectOptions_, [&context](bool ok) { + context->ok_ = ok; + }); + if (!context->ok_) { + NETSTACK_LOGE("TlsSocketExec::ExecConnect result is false"); + delete tlsSocket; + tlsSocket = nullptr; + return false; + } + SendCustomData(tlsSocket); + manager->SetData(tlsSocket); + return true; +} + +bool TlsSocketExec::ExecGetCipherSuites(GetCipherSuitesContext *context) +{ + auto manager = context->GetManager(); + if (manager == nullptr) { + NETSTACK_LOGE("manager is nullptr"); + return false; + } + auto tlsSocket = reinterpret_cast(manager->GetData()); + if (tlsSocket == nullptr) { + NETSTACK_LOGE("TlsSocketExec::ExecGetCipherSuites tlsSocket is null"); + return false; + } + tlsSocket->GetCipherSuite([&context](bool ok, const std::vector &suite) { + context->ok_ = ok; + context->cipherSuites_ = suite; + }); + return context->ok_; +} + +bool TlsSocketExec::ExecGetRemoteCertificate(GetRemoteCertificateContext *context) +{ + auto manager = context->GetManager(); + if (manager == nullptr) { + NETSTACK_LOGE("manager is nullptr"); + return false; + } + auto tlsSocket = reinterpret_cast(manager->GetData()); + if (tlsSocket == nullptr) { + NETSTACK_LOGE("TlsSocketExec::ExecGetRemoteCertificate tlsSocket is null"); + return false; + } + tlsSocket->GetRemoteCertificate([&context](bool ok, const std::string &cert) { + context->ok_ = ok; + context->remoteCert_ = cert; + + }); + return context->ok_; +} + +bool TlsSocketExec::ExecGetProtocol(GetProtocolContext *context) +{ + auto manager = context->GetManager(); + if (manager == nullptr) { + NETSTACK_LOGE("manager is nullptr"); + return false; + } + auto tlsSocket = reinterpret_cast(manager->GetData()); + if (tlsSocket == nullptr) { + NETSTACK_LOGE("TlsSocketExec::ExecGetProtocol tlsSocket is null"); + return false; + } + tlsSocket->GetProtocol([&context](bool ok, const std::string &protocol) { + context->ok_ = ok; + context->protocol_ = protocol; + }); + return context->ok_; +} + +bool TlsSocketExec::ExecGetSignatureAlgorithms(GetSignatureAlgorithmsContext *context) +{ + auto manager = context->GetManager(); + if (manager == nullptr) { + NETSTACK_LOGE("manager is nullptr"); + return false; + } + auto tlsSocket = reinterpret_cast(manager->GetData()); + if (tlsSocket == nullptr) { + NETSTACK_LOGE("TlsSocketExec::ExecGetSignatureAlgorithms tlsSocket is null"); + return false; + } + tlsSocket->GetSignatureAlgorithms([&context](bool ok, const std::vector &algorithms) { + context->ok_ = ok; + context->signatureAlgorithms_ = algorithms; + }); + return context->ok_; +} + +bool TlsSocketExec::ExecClose(CloseContext *context) +{ + auto manager = context->GetManager(); + if (manager == nullptr) { + NETSTACK_LOGE("manager is nullptr"); + return false; + } + auto tlsSocket = reinterpret_cast(manager->GetData()); + if (tlsSocket == nullptr) { + NETSTACK_LOGE("TlsSocketExec::ExecClose tlsSocket is null"); + return false; + } + tlsSocket->Close([&context](bool ok) { + context->ok_ = ok; + }); + delete tlsSocket; + manager->SetData(nullptr); + return context->ok_; +} + +napi_value TlsSocketExec::GetCertificateCallback(GetCertificateContext *context) +{ + return NapiUtils::CreateStringUtf8(context->GetEnv(), context->cert_); +} + +napi_value TlsSocketExec::ConnectCallback(ConnectContext *context) +{ + return NapiUtils::GetUndefined(context->GetEnv()); +} + +napi_value TlsSocketExec::GetCipherSuitesCallback(GetCipherSuitesContext *context) +{ + napi_value cipherSuites = NapiUtils::CreateArray(context->GetEnv(), 0); + int index = 0; + for (const auto &cipher : context->cipherSuites_) { + napi_value cipherSuite = NapiUtils::CreateStringUtf8(context->GetEnv(), cipher); + NapiUtils::SetArrayElement(context->GetEnv(), cipherSuites, index++, cipherSuite); + } + return cipherSuites; +} + +napi_value TlsSocketExec::GetRemoteCertificateCallback(GetRemoteCertificateContext *context) +{ + return NapiUtils::CreateStringUtf8(context->GetEnv(), context->remoteCert_); +} + +napi_value TlsSocketExec::GetProtocolCallback(GetProtocolContext *context) +{ + return NapiUtils::CreateStringUtf8(context->GetEnv(), context->protocol_); +} + +napi_value TlsSocketExec::GetSignatureAlgorithmsCallback(GetSignatureAlgorithmsContext *context) +{ + napi_value signatureAlgorithms = NapiUtils::CreateArray(context->GetEnv(), 0); + int index = 0; + for (const auto &algorithm : context->signatureAlgorithms_) { + napi_value signatureAlgorithm = NapiUtils::CreateStringUtf8(context->GetEnv(), algorithm); + NapiUtils::SetArrayElement(context->GetEnv(), signatureAlgorithms, index++, signatureAlgorithm); + } + return signatureAlgorithms; +} + +napi_value TlsSocketExec::CloseCallback(CloseContext *context) +{ + return NapiUtils::GetBoolean(context->GetEnv(), true); +} +} // namespace NetStack +} // namespace OHOS diff --git a/frameworks/js/napi/tls/src/tlssocket_module.cpp b/frameworks/js/napi/tls/src/tlssocket_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bbaee645f65bac67cd904c7015e09873e5ce871a --- /dev/null +++ b/frameworks/js/napi/tls/src/tlssocket_module.cpp @@ -0,0 +1,144 @@ +/* + * Copyright (C) 2021-2022 Huawei Device 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 "tlssocket_module.h" + +#include + +#include +#include + +#include "connect_context.h" +#include "close_context.h" +#include "event_manager.h" +#include "get_certificate_context.h" +#include "get_remote_certificate_context.h" +#include "get_signature_algorithms_context.h" +#include "get_cipher_suites_context.h" +#include "module_template.h" +#include "napi_utils.h" +#include "netstack_log.h" +#include "tlssocket_async_work.h" + +namespace OHOS { +namespace NetStack { +namespace { +constexpr const char *TLS_SOCKET_MODULE_NAME = "net.tlssocket"; +} // namespace + +void Finalize(napi_env, void *data, void *) +{ + NETSTACK_LOGI("socket handle is finalized"); +} + +napi_value TLSSocketModuleExports::TLSSocket::GetCertificate(napi_env env , napi_callback_info info) +{ + return ModuleTemplate::Interface(env, info, FUNCTION_GET_CERTIFICATE, nullptr, + TlsSocketAsyncWork::ExecGetCertificate, + TlsSocketAsyncWork::GetCertificateCallback); +} + +napi_value TLSSocketModuleExports::TLSSocket::GetProtocol(napi_env env , napi_callback_info info) +{ + return ModuleTemplate::Interface(env, info, FUNCTION_GET_PROTOCOL, nullptr, + TlsSocketAsyncWork::ExecGetProtocol, + TlsSocketAsyncWork::GetProtocolCallback); +} + +napi_value TLSSocketModuleExports::TLSSocket::Connect(napi_env env , napi_callback_info info) +{ + return ModuleTemplate::Interface(env, info, FUNCTION_CONNECT, nullptr, + TlsSocketAsyncWork::ExecConnect, + TlsSocketAsyncWork::ConnectCallback); +} + +napi_value TLSSocketModuleExports::TLSSocket::GetCipherSuites(napi_env env , napi_callback_info info) +{ + return ModuleTemplate::Interface(env, info, FUNCTION_GET_CIPHER_SUITES, nullptr, + TlsSocketAsyncWork::ExecGetCipherSuites, + TlsSocketAsyncWork::GetCipherSuitesCallback); +} + +napi_value TLSSocketModuleExports::TLSSocket::GetRemoteCertificate(napi_env env , napi_callback_info info) +{ + return ModuleTemplate::Interface(env, info, FUNCTION_GET_REMOTE_CERTIFICATE, nullptr, + TlsSocketAsyncWork::ExecGetRemoteCertificate, + TlsSocketAsyncWork::GetRemoteCertificateCallback); +} + +napi_value TLSSocketModuleExports::TLSSocket::GetSignatureAlgorithms(napi_env env , napi_callback_info info) +{ + return ModuleTemplate::Interface(env, info, FUNCTION_GET_SIGNATURE_ALGORITHMS, nullptr, + TlsSocketAsyncWork::ExecGetSignatureAlgorithms, + TlsSocketAsyncWork::GetSignatureAlgorithmsCallback); +} + +napi_value TLSSocketModuleExports::TLSSocket::Close(napi_env env , napi_callback_info info) +{ + return ModuleTemplate::Interface(env, info, FUNCTION_CLOSE, nullptr, + TlsSocketAsyncWork::ExecClose, + TlsSocketAsyncWork::CloseCallback); +} + +void TLSSocketModuleExports::DefineTLSSocketClass(napi_env env, napi_value exports) +{ + std::initializer_list functions = { + DECLARE_NAPI_FUNCTION(TLSSocket::FUNCTION_GET_CERTIFICATE, TLSSocket::GetCertificate), + DECLARE_NAPI_FUNCTION(TLSSocket::FUNCTION_GET_REMOTE_CERTIFICATE, TLSSocket::GetRemoteCertificate), + DECLARE_NAPI_FUNCTION(TLSSocket::FUNCTION_GET_SIGNATURE_ALGORITHMS, TLSSocket::GetSignatureAlgorithms), + DECLARE_NAPI_FUNCTION(TLSSocket::FUNCTION_GET_PROTOCOL, TLSSocket::GetProtocol), + DECLARE_NAPI_FUNCTION(TLSSocket::FUNCTION_CONNECT, TLSSocket::Connect), + DECLARE_NAPI_FUNCTION(TLSSocket::FUNCTION_GET_CIPHER_SUITES, TLSSocket::GetCipherSuites), + DECLARE_NAPI_FUNCTION(TLSSocket::FUNCTION_CLOSE, TLSSocket::Close), + }; + ModuleTemplate::DefineClass(env, exports, functions, INTERFACE_TLS_SOCKET); +} + +napi_value TLSSocketModuleExports::ConstructTLSSocketInstance(napi_env env, napi_callback_info info) +{ + return ModuleTemplate::NewInstance(env, info, INTERFACE_TLS_SOCKET, Finalize); +} + +void TLSSocketModuleExports::InitTLSSocketProperties(napi_env env, napi_value exports) +{ + std::initializer_list properties = { + DECLARE_NAPI_FUNCTION(FUNCTION_CONSTRUCTOR_TLS_SOCKET_INSTANCE, ConstructTLSSocketInstance), + }; + NapiUtils::DefineProperties(env, exports, properties); +} + +napi_value TLSSocketModuleExports::InitTLSSocketModule(napi_env env, napi_value exports) +{ + DefineTLSSocketClass(env, exports); + InitTLSSocketProperties(env, exports); + return exports; +} + +static napi_module g_tlssocketModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = TLSSocketModuleExports::InitTLSSocketModule, + .nm_modname = TLS_SOCKET_MODULE_NAME, + .nm_priv = nullptr, + .reserved = {nullptr}, +}; + +extern "C" __attribute__((constructor)) void RegisterTlsSocket(void) +{ + napi_module_register(&g_tlssocketModule); +} +} // namespace NetStack +} // namespace OHOS diff --git a/frameworks/js/napi/websocket/BUILD.gn b/frameworks/js/napi/websocket/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b9c5107efbead4d04ad1a8a36491faff7db65a7a --- /dev/null +++ b/frameworks/js/napi/websocket/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2021-2022 Huawei Device 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. + +import("//build/ohos.gni") +import("//foundation/communication/netstack/netstack_config.gni") + +ohos_shared_library("websocket") { + include_dirs = [ + "async_context/include", + "async_work/include", + "constant/include", + "websocket_exec/include", + "websocket_module/include", + "//third_party/libwebsockets/include", + ] + + sources = [ + "async_context/src/close_context.cpp", + "async_context/src/connect_context.cpp", + "async_context/src/send_context.cpp", + "async_work/src/websocket_async_work.cpp", + "constant/src/constant.cpp", + "websocket_exec/src/websocket_exec.cpp", + "websocket_module/src/websocket_module.cpp", + ] + + deps = [ + "$NETSTACK_DIR/utils/napi_utils:napi_utils", + "//third_party/libwebsockets:websockets", + "//third_party/openssl:libcrypto_static", + "//third_party/openssl:ssl_source", + "//third_party/zlib:libz", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "napi:ace_napi", + ] + + relative_install_dir = "module/net" + part_name = "netstack" + subsystem_name = "communication" +} diff --git a/frameworks/js/napi/websocket/async_context/include/close_context.h b/frameworks/js/napi/websocket/async_context/include/close_context.h index 3bb8253d8689589c1e696a763e2819118168d8f9..908fa9fded952d7d07ce65c0a560819b64e56f45 100644 --- a/frameworks/js/napi/websocket/async_context/include/close_context.h +++ b/frameworks/js/napi/websocket/async_context/include/close_context.h @@ -18,7 +18,7 @@ #include -#include "netstack_base_context.h" +#include "base_context.h" #include "nocopyable.h" namespace OHOS::NetStack { diff --git a/frameworks/js/napi/websocket/async_context/include/connect_context.h b/frameworks/js/napi/websocket/async_context/include/connect_context.h index ddb0b08eea64c9c3b0770228b79cf3becc318b7c..2a450c09284666fad3681e5a2e8c0c1a9662b2db 100644 --- a/frameworks/js/napi/websocket/async_context/include/connect_context.h +++ b/frameworks/js/napi/websocket/async_context/include/connect_context.h @@ -19,7 +19,7 @@ #include #include -#include "netstack_base_context.h" +#include "base_context.h" #include "nocopyable.h" #include "libwebsockets.h" diff --git a/frameworks/js/napi/websocket/async_context/include/send_context.h b/frameworks/js/napi/websocket/async_context/include/send_context.h index f054d282827065204df60a4d1b2848e008a9786e..3d5b82267fbfe60f4a1d10ab1d55a93273999d8d 100644 --- a/frameworks/js/napi/websocket/async_context/include/send_context.h +++ b/frameworks/js/napi/websocket/async_context/include/send_context.h @@ -19,7 +19,7 @@ #include #include "libwebsockets.h" -#include "netstack_base_context.h" +#include "base_context.h" #include "nocopyable.h" namespace OHOS::NetStack { diff --git a/frameworks/js/napi/websocket/async_context/src/close_context.cpp b/frameworks/js/napi/websocket/async_context/src/close_context.cpp index e3e8c7c3f1389c9334cff7476b6e6f4b6e245eef..52c86a6f5b040e2579c59a3b8b71d8056c8ee85f 100644 --- a/frameworks/js/napi/websocket/async_context/src/close_context.cpp +++ b/frameworks/js/napi/websocket/async_context/src/close_context.cpp @@ -18,7 +18,7 @@ #include "constant.h" #include "netstack_common_utils.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" namespace OHOS::NetStack { CloseContext::CloseContext(napi_env env, EventManager *manager) @@ -75,4 +75,4 @@ bool CloseContext::CheckParamsType(napi_value *params, size_t paramsCount) return false; } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/websocket/async_context/src/connect_context.cpp b/frameworks/js/napi/websocket/async_context/src/connect_context.cpp index 4f4c758dd32f3cce994419a1f4575af978bf6d70..883513d6f3d975cc06f8fc5576bf51d38130fc05 100644 --- a/frameworks/js/napi/websocket/async_context/src/connect_context.cpp +++ b/frameworks/js/napi/websocket/async_context/src/connect_context.cpp @@ -18,7 +18,7 @@ #include "constant.h" #include "netstack_common_utils.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" #include "securec.h" namespace OHOS::NetStack { diff --git a/frameworks/js/napi/websocket/async_context/src/send_context.cpp b/frameworks/js/napi/websocket/async_context/src/send_context.cpp index 59e04a60412e553fe7c8f976ec244352f178b0d9..a559c62b7007ab9e7d3544fc82d570652cb60d0f 100644 --- a/frameworks/js/napi/websocket/async_context/src/send_context.cpp +++ b/frameworks/js/napi/websocket/async_context/src/send_context.cpp @@ -17,7 +17,7 @@ #include "constant.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" #include "securec.h" namespace OHOS::NetStack { @@ -96,4 +96,4 @@ bool SendContext::CheckParamsType(napi_value *params, size_t paramsCount) return false; } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/js/napi/websocket/async_work/src/websocket_async_work.cpp b/frameworks/js/napi/websocket/async_work/src/websocket_async_work.cpp index 7162eb49ee3e69390eef14ab09ddb5cc5c707511..e3bd04ec72948ebbda8f52bc5010ca32668dd53b 100644 --- a/frameworks/js/napi/websocket/async_work/src/websocket_async_work.cpp +++ b/frameworks/js/napi/websocket/async_work/src/websocket_async_work.cpp @@ -15,7 +15,7 @@ #include "websocket_async_work.h" -#include "netstack_base_async_work.h" +#include "base_async_work.h" namespace OHOS::NetStack { void WebSocketAsyncWork::ExecConnect(napi_env env, void *data) diff --git a/frameworks/js/napi/websocket/websocket_exec/src/websocket_exec.cpp b/frameworks/js/napi/websocket/websocket_exec/src/websocket_exec.cpp index 92202ed403b8f3aab99ba424bb72f4986ed15489..a87084554f643b33bc3b79a056a313c349c8a131 100644 --- a/frameworks/js/napi/websocket/websocket_exec/src/websocket_exec.cpp +++ b/frameworks/js/napi/websocket/websocket_exec/src/websocket_exec.cpp @@ -22,7 +22,7 @@ #include "constant.h" #include "netstack_common_utils.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" #include "securec.h" static constexpr const char *PATH_START = "/"; diff --git a/frameworks/js/napi/websocket/websocket_module/src/websocket_module.cpp b/frameworks/js/napi/websocket/websocket_module/src/websocket_module.cpp index 44b153d98977ddb3e8b179b503c160cbf471f527..5492a72f31bc8b353a28e1191f75d2ddaace9dbe 100644 --- a/frameworks/js/napi/websocket/websocket_module/src/websocket_module.cpp +++ b/frameworks/js/napi/websocket/websocket_module/src/websocket_module.cpp @@ -17,7 +17,7 @@ #include "constant.h" #include "netstack_log.h" -#include "netstack_module_template.h" +#include "module_template.h" #include "websocket_async_work.h" namespace OHOS::NetStack { @@ -90,4 +90,4 @@ napi_value WebSocketModule::WebSocket::Off(napi_env env, napi_callback_info info } NAPI_MODULE(webSocket, WebSocketModule::InitWebSocketModule) -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/frameworks/native/tls_socket/BUILD.gn b/frameworks/native/tls_socket/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e4fb64b1c0ab31b4c95e451279c3a92f8c662122 --- /dev/null +++ b/frameworks/native/tls_socket/BUILD.gn @@ -0,0 +1,95 @@ +# Copyright (c) 2021-2022 Huawei Device 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. + +import("//build/ohos.gni") +import("//foundation/communication/netstack/netstack_config.gni") + +SOCKET_INCLUDE_DIR = + "//foundation/communication/netstack/frameworks/js/napi/socket" + +utils_source = [ + "$SOCKET_INCLUDE_DIR/options/src/net_address.cpp", + "$SOCKET_INCLUDE_DIR/socket_exec/src/socket_exec.cpp", + "$SOCKET_INCLUDE_DIR/async_context/src/bind_context.cpp", + "$SOCKET_INCLUDE_DIR/options/src/socket_state_base.cpp", + "$SOCKET_INCLUDE_DIR/options/src/socket_remote_info.cpp", + "$SOCKET_INCLUDE_DIR/options/src/extra_options_base.cpp", + "$SOCKET_INCLUDE_DIR/options/src/tcp_connect_options.cpp", + "$SOCKET_INCLUDE_DIR/options/src/tcp_extra_options.cpp", + "$SOCKET_INCLUDE_DIR/options/src/tcp_send_options.cpp", + "$SOCKET_INCLUDE_DIR/options/src/udp_extra_options.cpp", + "$SOCKET_INCLUDE_DIR/options/src/udp_send_options.cpp", + "$SOCKET_INCLUDE_DIR/async_context/src/connect_context.cpp", + "$SOCKET_INCLUDE_DIR/async_context/src/common_context.cpp", + "$SOCKET_INCLUDE_DIR/async_context/src/udp_extra_context.cpp", + "$SOCKET_INCLUDE_DIR/async_context/src/udp_send_context.cpp", + "$SOCKET_INCLUDE_DIR/async_context/src/tcp_extra_context.cpp", + "$SOCKET_INCLUDE_DIR/async_context/src/tcp_send_context.cpp", +] + +common_include = [ + "//foundation/arkui/ace_engine/frameworks/base/utils", + "//foundation/arkui/napi/interfaces/kits", + "//foundation/arkui/napi", + "//third_party/node/src", +] + +config("tls_socket_config") { + include_dirs = [ "//third_party/openssl/include" ] +} + +config("tls_socket_public_config") { + include_dirs = [ + "$NETSTACK_DIR/frameworks/native/tls_socket/include", + "$SOCKET_INCLUDE_DIR/async_context/include", + "$SOCKET_INCLUDE_DIR/async_work/include", + "$SOCKET_INCLUDE_DIR/constant/include", + "$SOCKET_INCLUDE_DIR/socket_exec/include", + "$SOCKET_INCLUDE_DIR/socket_module/include", + "$SOCKET_INCLUDE_DIR/options/include", + "$SOCKET_INCLUDE_DIR/task_queue/include", + "$NETSTACK_DIR/interfaces/innerkits/tls_socket/include", + ] + include_dirs += common_include +} + +ohos_shared_library("tls_socket") { + sources = [ + "src/tls.cpp", + "src/tls_certificate.cpp", + "src/tls_configuration.cpp", + "src/tls_context.cpp", + "src/tls_key.cpp", + "src/tls_socket.cpp", + "src/tls_socket_internal.cpp", + ] + sources += utils_source + + public_deps = [ + "$NETSTACK_DIR/utils:stack_utils_common", + "$NETSTACK_DIR/utils/napi_utils:napi_utils", + "//third_party/openssl:libcrypto_shared", + "//third_party/openssl:ssl_source", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "napi:ace_napi", + ] + + configs = [ ":tls_socket_config" ] + public_configs = [ ":tls_socket_public_config" ] + + part_name = "netstack" + subsystem_name = "communication" +} diff --git a/frameworks/native/tls_socket/include/tls.h b/frameworks/native/tls_socket/include/tls.h new file mode 100644 index 0000000000000000000000000000000000000000..c35b664dbaef05daf357423670c84a2ff7e49c0b --- /dev/null +++ b/frameworks/native/tls_socket/include/tls.h @@ -0,0 +1,214 @@ +/* +* Copyright (c) 2022 Huawei Device 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. +*/ + +#ifndef COMMUNICATIONNETSTACK_TLS_H +#define COMMUNICATIONNETSTACK_TLS_H + +#include +#include "net_address.h" + +namespace OHOS { +namespace NetStack { + +using Handle = void *; +constexpr int MAX_BUF_LEN = 1024; + +class TlsSecureOptions { +public: + + TlsSecureOptions(); + + ~TlsSecureOptions() = default; + + void SetCa(const std::vector &ca); + + void SetCert(const std::string &cert); + + void SetKey(const std::string &key); + + void SetPasswd(const std::string &passwd); + + void SetProtocol(const std::vector &Protocol); + + void SetUseRemoteCipherPrefer(bool useRemoteCipherPrefer); + + void SetSignatureAlgorithms(const std::string &signatureAlgorithms); + + void SetCipherSuite(const std::string &cipherSuite); + + void SetCrl(const std::vector &crl); + + [[nodiscard]] std::vector GetCa() const; + + [[nodiscard]] std::string GetCert() const; + + [[nodiscard]] std::string GetKey() const; + + [[nodiscard]] std::vector GetProtocol() const; + + [[nodiscard]] std::vector GetCrl() const; + + [[nodiscard]] std::string GetPasswd() const; + + [[nodiscard]] std::string GetSignatureAlgorithms() const; + + [[nodiscard]] std::string GetCipherSuite() const; + + [[nodiscard]] bool GetUseRemoteCipherPrefer() const; + +private: + std::vector caChain_; + std::string cert_; + std::string key_; + std::string passwd_; + std::vector protocolChain_; + bool useRemoteCipherPrefer_ = false; + std::string signatureAlgorithms_; + std::string cipherSuite_; + std::vector crlChain_; +}; + +class TlsConnectOptions { +public: + void SetAddress(const NetAddress &address); + + void SetSecureOptions(const TlsSecureOptions &secureOptions); + + void SetAlpnProtocols(const std::vector &alpnProtocols); + + NetAddress GetAddress(); + + TlsSecureOptions GetTlsSecureOptions(); + + std::vector GetAlpnProtocols(); + +private: + NetAddress address_; + TlsSecureOptions secureOptions_; + std::vector alpnProtocols_; +}; + +struct CipherSuite { + unsigned long cipherId_; + std::string cipherName_; +}; + +enum TlsMode { + UNENCRYPTED_MODE, + SSL_CLIENT_MODE, + SSL_SERVER_MODE +}; + +enum PeerVerifyMode { + VERIFY_NONE, + QUERY_PEER, + VERIFY_PEER, + AUTO_VERIFY_PEER +}; + +enum KeyType { + PRIVATE_KEY, + PUBLIC_KEY +}; + +enum CertType { + CA_CERT, + LOCAL_CERT +}; + +enum EncodingFormat { + PEM, + DER +}; + +enum KeyAlgorithm { + OPAQUE, + ALGORITHM_RSA, + ALGORITHM_DSA, + ALGORITHM_EC, + ALGORITHM_DH +}; + +enum AlternativeNameEntryType { + EMAIL_ENTRY, + DNS_ENTRY, + IPADDRESS_ENTRY +}; + +enum OpenMode { + NOT_OPEN, + READ_ONLY, + WRITE_ONLY, + READ_WRITE = READ_ONLY | WRITE_ONLY, + APPEND, + TRUNCATE, + TEXT, + UNBUFFERED, + NEW_ONLY, + EXISTION_ONLY +}; + +enum NetworkLayerProtocol { + IPV4_PROTOCOL, + IPV6_PROTOCOL, + ANY_IP_PROTOCOL, + UNKNOW_NETWORK_LAYER_PROTOCOL = -1 +}; + +enum class ImplementedClass { + KEY, + CERTIFICATE, + SOCKET, + DIFFIE_HELLMAN, + ELLIPTIC_CURVE +}; + +enum class SupportedFeature { + CERTIFICATE_VERIFICATION, + CLIENT_SIDE_ALPN, + SERVER_SIDE_ALPN, + OCSP, + PSK, + SESSION_TICKET, + ALERTS +}; + +enum TlsOptions { + SSL_OPTION_DISABLE_EMPTY_FRAGMENTS = 0x01, + SSL_OPTION_DISABLE_SESSION_TICKETS = 0x02, + SSL_OPTION_DISABLE_COMPRESSION = 0x04, + SSL_OPTION_DISABLE_SERVER_NAME_INDICATION = 0x08, + SSL_OPTION_DISABLE_LEGACY_RENEGOTIATION = 0x10, + SSL_OPTION_DISABLE_SESSION_SHARING = 0x20, + SSL_OPTION_DISABLE_SESSION_PERSISTENCE = 0x40, + SSL_OPTION_DISABLE_SERVER_CIPHER_PREFERENCE = 0x80 +}; + +enum TLSProtocol { + TLS_V1_2, + TLS_V1_3, + UNKNOW_PROTOCOL +}; + +enum class Cipher { + DES_CBC, + DES_EDE3_CBC, + RC2_CBC, + AES_128_CBC, + AES_192_CBC, + AES_256_CBC +}; +} } // namespace OHOS::NetStack +#endif // COMMUNICATIONNETSTACK_TLS_H diff --git a/frameworks/native/tls_socket/include/tls_certificate.h b/frameworks/native/tls_socket/include/tls_certificate.h new file mode 100644 index 0000000000000000000000000000000000000000..f6f38c78f85168f21cca4d239c54de1a2a36ce1c --- /dev/null +++ b/frameworks/native/tls_socket/include/tls_certificate.h @@ -0,0 +1,68 @@ +/* +* Copyright (c) 2022 Huawei Device 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. +*/ + +#ifndef COMMUNICATIONNETSTACK_TLS_CERTIFICATE_H +#define COMMUNICATIONNETSTACK_TLS_CERTIFICATE_H + +#include +#include +#include + +#include + +#include "tls.h" + +namespace OHOS { +namespace NetStack { + +class TLSCertificate { +public: + TLSCertificate() = default; + TLSCertificate(const TLSCertificate &certificate); + explicit TLSCertificate(const std::string &data, + EncodingFormat format = PEM, + CertType certType = CA_CERT); + TLSCertificate(const std::string &data, CertType certType); + ~TLSCertificate() = default; + TLSCertificate &operator= (const TLSCertificate &other); + + bool CertificateFromData(const std::string &data, CertType certType); + bool CertificateFromPem(const std::string &data, CertType certType); + bool CertificateFromDer(const std::string &data, CertType certType); + bool CaCertToString(X509 *x509); + bool LocalCertToString(X509 *x509); + std::string GetLocalCertString() const; + std::string GetSignatureAlgorithm() const; + + Handle handle() const; + +private: + bool SetSerialNumber(X509 *x509); + bool SetX509Version(X509 *x509); + bool SetNotValidTime(X509 *x509); + bool SetSignatureAlgorithm(X509 *x509); + bool AnalysisCertificate(CertType certType, X509 *x509); +private: + X509 *x509_ = nullptr; + std::string version_; + std::string serialNumber_; + std::string notValidBefore_; + std::string notValidAfter_; + std::string signatureAlgorithm_; + std::string localCertString_; + std::string caCertString_; +}; +} } // namespace OHOS::NetStack +#endif // COMMUNICATIONNETSTACK_TLS_CERTIFICATE_H diff --git a/frameworks/native/tls_socket/include/tls_configuration.h b/frameworks/native/tls_socket/include/tls_configuration.h new file mode 100644 index 0000000000000000000000000000000000000000..60074487eea985318630720b1dc83ceaa0090a7b --- /dev/null +++ b/frameworks/native/tls_socket/include/tls_configuration.h @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2022 Huawei Device 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. +*/ + +#ifndef COMMUNICATIONNETSTACK_TLS_CONFIGURATION_H +#define COMMUNICATIONNETSTACK_TLS_CONFIGURATION_H + +#include +#include + +#include "tls_key.h" +#include "tls_certificate.h" + +namespace OHOS { +namespace NetStack { + +class TLSConfiguration { +public: + TLSConfiguration(); + TLSConfiguration(const TLSConfiguration &other); + ~TLSConfiguration() = default; + TLSConfiguration &operator=(const TLSConfiguration &other); + + void SetLocalCertificate(const TLSCertificate &certificate); + void SetLocalCertificate(const std::string &certificate); + [[nodiscard]] TLSCertificate GetLocalCertificate() const; + + void SetCaCertificate(const TLSCertificate &certificate); + void SetCaCertificate(const std::vector&certificate); + [[nodiscard]] std::vector GetCaCertificate() const; + + [[nodiscard]] const TLSKey& PrivateKey() const; + void SetPrivateKey(const TLSKey &key); + void SetPrivateKey(const std::string &key, const std::string &passwd); + [[nodiscard]] TLSKey GetPrivateKey() const; + + explicit TLSConfiguration(TLSConfiguration *tlsConfiguration); + + void SetProtocol(const std::string &Protocol); + void SetProtocol(const std::vector &Protocol); + [[nodiscard]] TLSProtocol GetMinProtocol() const; + [[nodiscard]] TLSProtocol GetMaxProtocol() const; + [[nodiscard]] TLSProtocol GetProtocol() const; + + void SetUseRemoteCipherPrefer(bool useRemoteCipherPrefer); + [[nodiscard]] bool GetUseRemoteCipherPrefer() const; + + void SetCipherSuite(const std::string &cipherSuite); + [[nodiscard]] std::string GetCipherSuite() const; + + [[nodiscard]] std::string GetCertificate() const; + void SetSignatureAlgorithms(const std::string &signatureAlgorithms); + [[nodiscard]] std::vector GetCipherSuiteVec() const; +private: + TLSProtocol minProtocol_ = TLS_V1_2; + TLSProtocol maxProtocol_ = TLS_V1_2; + TLSProtocol protocol_ = TLS_V1_2; + + std::string cipherSuite_; + std::string signatureAlgorithms_; + std::string localCertString_; + + bool useRemoteCipherPrefer_ = false; + + std::vector cipherSuiteVec_; + + TLSKey privateKey_; + TLSCertificate localCertificate_; + TLSCertificate caCertificate_; + std::vector caCertificateChain_; +}; +} } // namespace OHOS::NetStack::TlsSocketExec +#endif // COMMUNICATIONNETSTACK_TLS_CONFIGURATION_H diff --git a/frameworks/native/tls_socket/include/tls_context.h b/frameworks/native/tls_socket/include/tls_context.h new file mode 100644 index 0000000000000000000000000000000000000000..18ed00be641cd17d1dee643d5e49b2bab7bd54be --- /dev/null +++ b/frameworks/native/tls_socket/include/tls_context.h @@ -0,0 +1,56 @@ +/* +* Copyright (c) 2022 Huawei Device 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. +*/ + +#ifndef COMMUNICATIONNETSTACK_TLS_CONTEXT_H +#define COMMUNICATIONNETSTACK_TLS_CONTEXT_H + +#include + +#include "tls_configuration.h" +#include "tls.h" + +namespace OHOS { +namespace NetStack { + +class TLSContext { +public: + TLSContext() = default; + ~TLSContext() = default; + static std::unique_ptr + CreateConfiguration(TlsMode mode, const TLSConfiguration &configuration, bool allowRootCertOnDemandLoading); + SSL *CreateSsl(); + void CloseCtx(); + +private: + static bool InitTlsContext(TLSContext *sslContext, + TlsMode mode, + const TLSConfiguration &configuration, + bool allowRootCertOnDemandLoading); + static void SetCipherList(TLSContext *tlsContext, const TLSConfiguration &configuration); + static void GetCiphers(TLSContext *tlsContext); + static void UseRemoteCipher(TLSContext *tlsContext); + static void SetMinAndMaxProtocol(TLSContext *tlsContext); + static bool SetCaAndVerify(TLSContext *tlsContext, const TLSConfiguration &configuration); + static bool SetLocalCertificate(TLSContext *tlsContext, const TLSConfiguration &configuration); + static bool SetKeyAndCheck(TLSContext *tlsContext, const TLSConfiguration &configuration); + static void SetVerify(TLSContext *tlsContext); +private: + SSL_CTX *ctx_ = nullptr; + EVP_PKEY *pkey_ = nullptr; + SSL *ctxSsl_ = nullptr; + TLSConfiguration tlsConfiguration_; +}; +} } // namespace OHOS::NetStack +#endif // COMMUNICATIONNETSTACK_TLS_CONTEXT_H diff --git a/frameworks/native/tls_socket/include/tls_key.h b/frameworks/native/tls_socket/include/tls_key.h new file mode 100644 index 0000000000000000000000000000000000000000..5681bcb63a4f4e5e0b6b2b0c25203b72ee2ad962 --- /dev/null +++ b/frameworks/native/tls_socket/include/tls_key.h @@ -0,0 +1,73 @@ +/* +* Copyright (c) 2022 Huawei Device 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. +*/ + +#ifndef COMMUNICATIONNETSTACK_TLS_KEY_H +#define COMMUNICATIONNETSTACK_TLS_KEY_H + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include "tls.h" + +namespace OHOS { +namespace NetStack { + +class TLSKey { +public: + TLSKey() = default; + ~TLSKey() = default; + + TLSKey(const std::string &fileName, KeyAlgorithm algorithm, + EncodingFormat format = PEM, + KeyType type = PRIVATE_KEY, + const std::string &passPhrase = std::string()); + TLSKey(const std::string &data, KeyAlgorithm algorithm, + const std::string &passPhrase); + + TLSKey &operator = (const TLSKey &other); + [[nodiscard]] KeyAlgorithm Algorithm() const; + [[nodiscard]] Handle handle() const; + const std::string &GetPasswd() const; + +private: + void DecodeData(const std::string &data, KeyAlgorithm algorithm, + const std::string &passPhrase); + void DecodeDer(KeyType type, KeyAlgorithm algorithm, const std::string &fileName, + const std::string &passPhrase); + void DecodePem(KeyType type, KeyAlgorithm algorithm, const std::string &fileName, + const std::string &passPhrase); + void Clear(bool deep); + +private: + EVP_PKEY *opaque_ = nullptr; + RSA *rsa_ = nullptr; + DSA *dsa_ = nullptr; + DH *dh_ = nullptr; + EC_KEY *ec_ = nullptr; + EVP_PKEY *genericKey_ = nullptr; + std::string passwd_; + bool keyIsNull_ = true; + KeyType keyType_ = PUBLIC_KEY; + KeyAlgorithm keyAlgorithm_ = OPAQUE; +}; +} } // namespace OHOS::NetStack +#endif // COMMUNICATIONNETSTACK_TLS_KEY_H diff --git a/frameworks/native/tls_socket/include/tls_socket_internal.h b/frameworks/native/tls_socket/include/tls_socket_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..034b73bdf67d859035f2a6862a53f141fac8ac7f --- /dev/null +++ b/frameworks/native/tls_socket/include/tls_socket_internal.h @@ -0,0 +1,102 @@ +/* +* Copyright (c) 2022 Huawei Device 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. +*/ + +#ifndef COMMUNICATIONNETSTACK_TLS_SOCKET_INTERNAL_H +#define COMMUNICATIONNETSTACK_TLS_SOCKET_INTERNAL_H + +#include +#include +#include + +#include + +#include "net_address.h" +#include "socket_state_base.h" +#include "tcp_extra_options.h" +#include "socket_remote_info.h" +#include "tls.h" +#include "tls_configuration.h" +#include "tls_context.h" + +namespace OHOS { +namespace NetStack { + +static constexpr const char *SPLIT = " "; +using RecvCallback = std::function; +using ErrorCallback = std::function; + +class TLSSocketInternal final { +public: + TLSSocketInternal() = default; + ~TLSSocketInternal() = default; + + bool TlsConnectToHost(TlsConnectOptions options); + + void SetTlsConfiguration(const TLSConfiguration &config); + [[nodiscard]] TLSConfiguration GetTlsConfiguration() const; + + [[nodiscard]] TLSProtocol GetProtocol() const; + std::vector GetCipherSuite(); + + [[nodiscard]] bool IsRootsOnDemandAllowed() const; + bool Send(const std::string &data); + void Recv(); + bool Close(); + bool SetAlpnProtocols(const std::vector &alpnProtocols); + bool SetSharedSigalgs(); + [[nodiscard]] bool GetState(SocketStateBase &state) const; + [[nodiscard]] bool ExtraOptions(const TCPExtraOptions &options) const; + [[nodiscard]] bool GetRemoteAddress(NetAddress &address) const; + [[nodiscard]] bool Bind(NetAddress &address) const; + + bool SetRemoteCertificate(); + [[nodiscard]] std::string GetRemoteCertificate() const; + [[nodiscard]] std::string GetCertificate() const; + bool GetPeerCertificate(); + [[nodiscard]] std::vector GetSignatureAlgorithms() const; + + bool GetPasswd(); + std::string GetProtocol(); + + int GetRead(char *buffer, int MAX_BUFFER_SIZE); + void MakeRemoteInfo(SocketRemoteInfo &remoteInfo); + + ssl_st *GetSSL(); + +private: + bool StartTlsConnected(); + bool CreatTlsContext(); + bool StartShakingHands(); + bool VerifyPeerCert(stack_st_X509 *caChain, const char* certFile); +private: + std::shared_ptr tlsContextPointer_ = nullptr; +private: + std::string hostName_; + uint16_t port_ = 0; + std::vector signatureAlgorithms_; + sa_family_t family_ = 0; + NetAddress address_; + struct ssl_st *ssl_ = nullptr; + X509 *peerX509_ = nullptr; + std::string remoteCert_; + std::string passwd_; + TLSConfiguration configuration_; + bool allowRootCertOnDemandLoading_ = false; + int32_t socketDescriptor_ = 0; + RecvCallback recvCallback_; + ErrorCallback errorCallback_; +}; +} } // namespace OHOS::NetStack +#endif // COMMUNICATIONNETSTACK_TLS_SOCKET_INTERNAL_H diff --git a/frameworks/native/tls_socket/src/tls.cpp b/frameworks/native/tls_socket/src/tls.cpp new file mode 100644 index 0000000000000000000000000000000000000000..33121c1c276ca7866e666b809ce48d0b9d055f52 --- /dev/null +++ b/frameworks/native/tls_socket/src/tls.cpp @@ -0,0 +1,155 @@ +/* +* Copyright (c) 2022 Huawei Device 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 "tls.h" +#include "netstack_log.h" +namespace OHOS { +namespace NetStack { + +TlsSecureOptions::TlsSecureOptions() + :useRemoteCipherPrefer_(true) +{ +} + +void TlsSecureOptions::SetCa(const std::vector &ca) +{ + caChain_ = ca; +} + +void TlsSecureOptions::SetCert(const std::string &cert) +{ + cert_ = cert; +} + +void TlsSecureOptions::SetKey(const std::string &key) +{ + key_ = key; +} + +void TlsSecureOptions::SetPasswd(const std::string &passwd) +{ + passwd_ = passwd; +} + +void TlsSecureOptions::SetProtocol(const std::vector &Protocol) +{ + protocolChain_ = Protocol; +} + +void TlsSecureOptions::SetUseRemoteCipherPrefer(bool useRemoteCipherPrefer) +{ + useRemoteCipherPrefer_ = useRemoteCipherPrefer; +} + +void TlsSecureOptions::SetSignatureAlgorithms(const std::string &signatureAlgorithms) +{ + signatureAlgorithms_ = signatureAlgorithms; +} + +void TlsSecureOptions::SetCipherSuite(const std::string &cipherSuite) +{ + cipherSuite_ = cipherSuite; +} + +void TlsSecureOptions::SetCrl(const std::vector &crl) +{ + crlChain_ = crl; +} + +void TlsConnectOptions::SetAddress(const NetAddress &address) +{ + address_.SetAddress(address.GetAddress()); + address_.SetPort(address.GetPort()); + address_.SetFamilyBySaFamily(address.GetSaFamily()); +} + +void TlsConnectOptions::SetSecureOptions(const TlsSecureOptions &secureOptions) +{ + secureOptions_.SetKey(secureOptions.GetKey()); + secureOptions_.SetCa(secureOptions.GetCa()); + secureOptions_.SetCert(secureOptions.GetCert()); + secureOptions_.SetProtocol(secureOptions.GetProtocol()); + secureOptions_.SetCrl(secureOptions.GetCrl()); + secureOptions_.SetPasswd(secureOptions.GetPasswd()); + secureOptions_.SetSignatureAlgorithms(secureOptions.GetSignatureAlgorithms()); + secureOptions_.SetCipherSuite(secureOptions.GetCipherSuite()); + secureOptions_.SetUseRemoteCipherPrefer(secureOptions.GetUseRemoteCipherPrefer()); +} + +void TlsConnectOptions::SetAlpnProtocols(const std::vector &alpnProtocols) +{ + alpnProtocols_ = alpnProtocols; +} + +std::vector TlsSecureOptions::GetCa() const +{ + return caChain_; +} + +std::string TlsSecureOptions::GetCert() const +{ + return cert_; +} + +std::string TlsSecureOptions::GetKey() const +{ + return key_; +} + +std::vector TlsSecureOptions::GetProtocol() const +{ + return protocolChain_; +} + +std::vector TlsSecureOptions::GetCrl() const +{ + return crlChain_; +} + +std::string TlsSecureOptions::GetCipherSuite() const +{ + return cipherSuite_; +} + +std::string TlsSecureOptions::GetSignatureAlgorithms() const +{ + return signatureAlgorithms_; +} + +bool TlsSecureOptions::GetUseRemoteCipherPrefer() const +{ + return useRemoteCipherPrefer_; +} + +std::string TlsSecureOptions::GetPasswd() const +{ + return passwd_; +} + +NetAddress TlsConnectOptions::GetAddress() +{ + return address_; +} + +TlsSecureOptions TlsConnectOptions::GetTlsSecureOptions() +{ + return secureOptions_; +} + +std::vector TlsConnectOptions::GetAlpnProtocols() +{ + return alpnProtocols_; +} +} } // namespace OHOS::NetStack diff --git a/frameworks/native/tls_socket/src/tls_certificate.cpp b/frameworks/native/tls_socket/src/tls_certificate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c702ed34cf49f01c62ab81a88c166575e6df9428 --- /dev/null +++ b/frameworks/native/tls_socket/src/tls_certificate.cpp @@ -0,0 +1,325 @@ +/* +* Copyright (c) 2022 Huawei Device 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 "tls_certificate.h" + +#include + +#include +#include +#include +#include + +#include "netstack_log.h" + +namespace OHOS { +namespace NetStack { + +namespace { +constexpr const char *BIO_FILE_FLAG = "r"; +constexpr const char *FILE_OPEN_FLAG = "rb"; +constexpr const char *CERT_VERSION_FLAG = "V"; +constexpr int FILE_READ_CERT_LEN = 4096; +} // namespace + +TLSCertificate::TLSCertificate(const TLSCertificate &certificate) = default; + +TLSCertificate::TLSCertificate(const std::string &data, EncodingFormat format, CertType certType) +{ + if (data.empty()) { + NETSTACK_LOGE("TlsCertificate::TlsCertificate data is empty"); + return; + } + switch (format) { + case PEM: + if (!CertificateFromPem(data, certType)) { + NETSTACK_LOGE("return CertificateFromPem(data, certs) is false"); + } + break; + case DER: + if (!CertificateFromDer(data, certType)) { + NETSTACK_LOGE("return CertificateFromDer(data, certs) is false"); + } + break; + default: + NETSTACK_LOGE("%{public}u is not supported, only support PEM =0 and DER = 1", format); + } +} + +TLSCertificate::TLSCertificate(const std::string &data, CertType certType) +{ + if (data.empty()) { + NETSTACK_LOGE("TlsCertificate::TlsCertificate(const std::string &data, CertType certType) data is empty"); + return; + } + if (!CertificateFromData(data, certType)) { + NETSTACK_LOGE("return CertificatesFromPem(data, certs) is false"); + } +} + +TLSCertificate &TLSCertificate::operator= (const TLSCertificate &other) +{ + if (other.x509_ != nullptr) { + x509_ = X509_new(); + x509_ = other.x509_; + } + version_ = other.version_; + serialNumber_ = other.serialNumber_; + notValidBefore_ = other.notValidBefore_; + notValidAfter_ = other.notValidBefore_; + signatureAlgorithm_ = other.signatureAlgorithm_; + localCertString_ = other.localCertString_; + caCertString_ = other.caCertString_; + return *this; +} + +bool TLSCertificate::CertificateFromData(const std::string &data, CertType certType) +{ + if (data.empty()) { + NETSTACK_LOGE("TlsCertificate::CertificateFromData: data is empty"); + return false; + } + BIO *bio = BIO_new_mem_buf(data.c_str(), -1); + if (!bio) { + NETSTACK_LOGE("TlsCertificate(const std::string &data, CertType certType) ---"); + return false; + } + X509 *x509 = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr); + BIO_free(bio); + + if (!x509) { + NETSTACK_LOGE("--- TlsCertificate::CertificateFromData: x509 is null ---"); + return false; + } + + x509_ = X509_dup(x509); + if (!AnalysisCertificate(certType, x509)) { + NETSTACK_LOGE("TlsCertificate::CertificateFromData: AnalysisCertificate is false"); + X509_free(x509); + return false; + } + X509_free(x509); + return true; +} + +bool TLSCertificate::CertificateFromPem(const std::string &data, CertType certType) +{ + BIO *bio = BIO_new_file((data.c_str()), BIO_FILE_FLAG); + if (!bio) { + NETSTACK_LOGE("bio new file fail errno = %{public}d reason = %{public}s \n", errno, strerror(errno)); + return false; + } + X509 *x509 = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr); + BIO_free(bio); + + if (!x509) { + NETSTACK_LOGE("--- TlsCertificate::CertificateFromPem: x509 is null ---"); + return false; + } + + x509_ = X509_dup(x509); + if (!AnalysisCertificate(certType, x509)) { + NETSTACK_LOGE("TlsCertificate::CertificateFromPem: AnalysisCertificate is false"); + X509_free(x509); + return false; + } + X509_free(x509); + return true; +} + +bool TLSCertificate::CertificateFromDer(const std::string &data, CertType certType) +{ + FILE *fp = nullptr; + fp = fopen(data.c_str(), FILE_OPEN_FLAG); + if (!fp) { + NETSTACK_LOGE("TlsCertificate::CertificateFromDer: Couldn't open %{public}s file for reading", data.c_str()); + return false; + } + unsigned char cert[FILE_READ_CERT_LEN] = {}; + long certLen = fread(cert, 1, FILE_READ_CERT_LEN, fp); + fclose(fp); + const auto *cert_data = reinterpret_cast(cert); + X509 *x509 = d2i_X509(nullptr, &cert_data, certLen); + if (!x509) { + NETSTACK_LOGE("TlsCertificate::CertificateFromDer: x509 is null"); + return false; + } + x509_ = X509_dup(x509); + if (!AnalysisCertificate(certType, x509)) { + NETSTACK_LOGE("TlsCertificate::CertificateFromDer: AnalysisCertificate is false"); + X509_free(x509); + return false; + } + X509_free(x509); + return true; +} + +bool TLSCertificate::AnalysisCertificate(CertType certType, X509 *x509) +{ + if (certType == CA_CERT) { + if (!CaCertToString(x509)) { + NETSTACK_LOGE("TlsCertificate::AnalysisCertificate: CaCertToString is false"); + return false; + } + } + if (certType == LOCAL_CERT) { + if (!LocalCertToString(x509)) { + NETSTACK_LOGE("TlsCertificate::AnalysisCertificate: LocalCertToString is false"); + return false; + } + } + if (!SetX509Version(x509)) { + NETSTACK_LOGE("TlsCertificate::AnalysisCertificate: SetX509Version is false"); + return false; + } + if (!SetSerialNumber(x509)) { + NETSTACK_LOGE("TlsCertificate::AnalysisCertificate: SetSerialNumber is false"); + return false; + } + if (!SetNotValidTime(x509)) { + NETSTACK_LOGE("TlsCertificate::AnalysisCertificate: SetNotValidTime is false"); + return false; + } + if (!SetSignatureAlgorithm(x509)) { + NETSTACK_LOGE("TlsCertificate::AnalysisCertificate: SetSignatureAlgorithm is false"); + return false; + } + return true; +} + +bool TLSCertificate::CaCertToString(X509 *x509) +{ + if (!x509) { + NETSTACK_LOGE("TlsCertificate::CaCertToString: x509 is null"); + return false; + } + BIO *bio = BIO_new(BIO_s_mem()); + X509_print(bio, x509); + char data[FILE_READ_CERT_LEN] = {}; + if (!BIO_read(bio, data, FILE_READ_CERT_LEN)) { + NETSTACK_LOGI("CaCertToString is BIO_read false"); + } + caCertString_ = std::string(data); + BIO_free(bio); + return true; +} + +bool TLSCertificate::LocalCertToString(X509 *x509) +{ + if (!x509) { + NETSTACK_LOGE("TlsCertificate::LocalCertToString: x509 is null"); + return false; + } + BIO *bio = BIO_new(BIO_s_mem()); + X509_print(bio, x509); + char data[FILE_READ_CERT_LEN] = {}; + if (!BIO_read(bio, data, FILE_READ_CERT_LEN)) { + NETSTACK_LOGE("LocalCertToString BIO_read is false"); + } + localCertString_ = std::string(data); + NETSTACK_LOGI("TlsCertificate::LocalCertToString cert is %{public}s", localCertString_.c_str()); + BIO_free(bio); + return true; +} + +bool TLSCertificate::SetX509Version(X509 *x509) +{ + if (!x509) { + NETSTACK_LOGE("TlsCertificate::SetX509Version: x509 is null"); + return false; + } + auto ver = X509_get_version(x509) + 1; + version_ = CERT_VERSION_FLAG + std::to_string(ver); + NETSTACK_LOGI("tls version_ %{public}s", version_.c_str()); + return true; +} + +bool TLSCertificate::SetSerialNumber(X509 *x509) +{ + if (!x509) { + NETSTACK_LOGE("TlsCertificate::SetSerialNumber: x509 is null"); + return false; + } + ASN1_INTEGER *serial = X509_get_serialNumber(x509); + if (!serial->length) { + NETSTACK_LOGE("X509_get_serialNumber length error"); + return false; + } + BIGNUM *bn = ASN1_INTEGER_to_BN(serial, nullptr); + if (!bn) { + NETSTACK_LOGE("TlsCertificate::SetSerialNumber: unable to convert ASN1INTEGER to BN"); + return false; + } + serialNumber_ = BN_bn2hex(bn); + BN_free(bn); + return true; +} + +bool TLSCertificate::SetNotValidTime(X509 *x509) +{ + if (!x509) { + NETSTACK_LOGE("TlsCertificate::SetNotValidTime: x509 is null"); + return false; + } + ASN1_TIME *before = X509_get_notBefore(x509); + if (!before) { + NETSTACK_LOGE("TlsCertificate::SetNotValidTime: before is null"); + return false; + } + tm tmBefore = {0}; + if (!ASN1_TIME_to_tm(before, &tmBefore)) { + NETSTACK_LOGE("TlsCertificate::SetNotValidTime: ASN1_TIME_to_tm before is false"); + return false; + } + notValidBefore_ = asctime(&tmBefore); + + ASN1_TIME *after = X509_get_notAfter(x509); + if (!after) { + NETSTACK_LOGE("TlsCertificate::SetNotValidTime: after is null"); + return false; + } + tm tmAfter; + if (!ASN1_TIME_to_tm(after, &tmAfter)) { + NETSTACK_LOGE("TlsCertificate::SetNotValidTime: ASN1_TIME_to_tm before is false"); + return false; + } + notValidAfter_ = asctime(&tmAfter); + return true; +} + +bool TLSCertificate::SetSignatureAlgorithm(X509 *x509) +{ + int signNid = X509_get_signature_nid(x509); + const char* sign = OBJ_nid2sn(signNid); + signatureAlgorithm_ = sign; + NETSTACK_LOGD("TlsCertificate::SetSignatureAlgorithm OBJ_nid2sn = %{public}s", signatureAlgorithm_.c_str()); + return true; +} + +std::string TLSCertificate::GetSignatureAlgorithm() const +{ + return signatureAlgorithm_; +} +std::string TLSCertificate::GetLocalCertString() const +{ + NETSTACK_LOGD("TlsCertificate::GetLocalCertString cert is %{public}s", localCertString_.c_str()); + return localCertString_; +} + +Handle TLSCertificate::handle() const +{ + return Handle(x509_); +} +} } // namespace OHOS::NetStack diff --git a/frameworks/native/tls_socket/src/tls_configuration.cpp b/frameworks/native/tls_socket/src/tls_configuration.cpp new file mode 100644 index 0000000000000000000000000000000000000000..448f2034e72a1559fceb977a4a6edf433e08b90b --- /dev/null +++ b/frameworks/native/tls_socket/src/tls_configuration.cpp @@ -0,0 +1,186 @@ +/* +* Copyright (c) 2022 Huawei Device 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 "tls_configuration.h" + +#include +#include "tls.h" +#include "tls_key.h" +#include "netstack_log.h" + +namespace OHOS { +namespace NetStack { + +namespace { +constexpr const char *TLS_1_3 = "TlsV1_3"; +constexpr const char *TLS_1_2 = "TlsV1_2"; +} // namespace + +TLSConfiguration::TLSConfiguration(const TLSConfiguration &other) +{ + privateKey_ = other.privateKey_; +} + +const TLSKey& TLSConfiguration::PrivateKey() const +{ + return privateKey_; +} + +TLSConfiguration &TLSConfiguration::operator=(const TLSConfiguration &other) +{ + privateKey_= other.privateKey_; + localCertificate_ = other.localCertificate_; + caCertificate_ = other.caCertificate_; + minProtocol_ = other.minProtocol_; + maxProtocol_ = other.maxProtocol_; + cipherSuite_ = other.cipherSuite_; + return *this; +} + +void TLSConfiguration::SetLocalCertificate(const TLSCertificate &certificate) +{ + localCertificate_ = certificate; +} + +void TLSConfiguration::SetCaCertificate(const TLSCertificate &certificate) +{ + caCertificate_ = certificate; +} + +void TLSConfiguration::SetPrivateKey(const TLSKey &key) +{ + privateKey_ = key; +} + +void TLSConfiguration::SetPrivateKey(const std::string &key, const std::string &passwd) +{ +// TLSKey pkey(key, ALGORITHM_RSA, PEM, PRIVATE_KEY, passwd); + TLSKey pkey(key, ALGORITHM_RSA, passwd); + privateKey_ = pkey; +} + +void TLSConfiguration::SetLocalCertificate(const std::string &certificate) +{ +// TLSCertificate local(certificate, PEM, LOCAL_CERT); + TLSCertificate local(certificate, LOCAL_CERT); + localCertificate_ = local; +} + +void TLSConfiguration::SetCaCertificate(const std::vector &certificate) +{ + caCertificateChain_ = certificate; +} + +void TLSConfiguration::SetProtocol(const std::string &Protocol) +{ + if (Protocol == TLS_1_3) { + minProtocol_ = TLS_V1_3; + maxProtocol_ = TLS_V1_3; + } + if (Protocol == TLS_1_2) { + minProtocol_ = TLS_V1_2; + maxProtocol_ = TLS_V1_2; + } +} + +void TLSConfiguration::SetProtocol(const std::vector &Protocol) +{ + bool isTls1_3 = false; + bool isTls1_2 = false; + for (const auto &p : Protocol) { + if (p == TLS_1_3) { + maxProtocol_ = TLS_V1_3; + isTls1_3 = true; + } + if (p == TLS_1_2) { + minProtocol_ = TLS_V1_2; + isTls1_2 = true; + } + } + if (!isTls1_3) { + maxProtocol_ = TLS_V1_2; + } + if (!isTls1_2) { + minProtocol_ = TLS_V1_3; + } +} + +TLSProtocol TLSConfiguration::GetMinProtocol() const +{ + return minProtocol_; +} + +TLSProtocol TLSConfiguration::GetMaxProtocol() const +{ + return maxProtocol_; +} + +TLSProtocol TLSConfiguration::GetProtocol() const +{ + return protocol_; +} + +std::string TLSConfiguration::GetCipherSuite() const +{ + return cipherSuite_; +} + +std::vector TLSConfiguration::GetCipherSuiteVec() const +{ + return cipherSuiteVec_; +} + +std::string TLSConfiguration::GetCertificate() const +{ + return localCertificate_.GetLocalCertString(); +} + +void TLSConfiguration::SetCipherSuite(const std::string &cipherSuite) +{ + cipherSuite_ = cipherSuite; +} + +void TLSConfiguration::SetSignatureAlgorithms(const std::string &signatureAlgorithms) +{ + signatureAlgorithms_ = signatureAlgorithms; +} + +void TLSConfiguration::SetUseRemoteCipherPrefer(bool useRemoteCipherPrefer) +{ + useRemoteCipherPrefer_ = useRemoteCipherPrefer; +} + +bool TLSConfiguration::GetUseRemoteCipherPrefer() const +{ + return useRemoteCipherPrefer_; +} + +std::vector TLSConfiguration::GetCaCertificate() const +{ + return caCertificateChain_; +} + +TLSCertificate TLSConfiguration::GetLocalCertificate() const +{ + return localCertificate_; +} + +TLSKey TLSConfiguration::GetPrivateKey() const +{ + return privateKey_; +} + +TLSConfiguration::TLSConfiguration() = default; +} } // namespace OHOS::NetStack diff --git a/frameworks/native/tls_socket/src/tls_context.cpp b/frameworks/native/tls_socket/src/tls_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e06c7509d637054fa12eecac491759ed4fd9d64 --- /dev/null +++ b/frameworks/native/tls_socket/src/tls_context.cpp @@ -0,0 +1,228 @@ +/* +* Copyright (c) 2022 Huawei Device 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 "tls_context.h" +#include +#include + +#include +#include +#include "openssl/evp.h" + +#include "netstack_log.h" + +namespace OHOS { +namespace NetStack { + +std::unique_ptr TLSContext::CreateConfiguration(TlsMode mode, + const TLSConfiguration &configuration, + bool allowRootCertOnDemandLoading) +{ + auto tlsContext = std::make_unique(); + if (!InitTlsContext(tlsContext.get(), mode, configuration, allowRootCertOnDemandLoading)) { + return nullptr; + } + return tlsContext; +} + +void InitEnv() +{ + SSL_library_init(); + OpenSSL_add_all_algorithms(); + SSL_load_error_strings(); +} + +void TLSContext::SetCipherList(TLSContext *tlsContext, const TLSConfiguration &configuration) +{ + NETSTACK_LOGD("GetCipherSuite = %{public}s", configuration.GetCipherSuite().c_str()); + if (SSL_CTX_set_cipher_list(tlsContext->ctx_, configuration.GetCipherSuite().c_str()) <= 0) { + NETSTACK_LOGE("Error setting the cipher list"); + } +} + +void TLSContext::GetCiphers(TLSContext *tlsContext) +{ + std::vector cipherSuiteVec; + STACK_OF(SSL_CIPHER)* sk = SSL_CTX_get_ciphers(tlsContext->ctx_); + CipherSuite cipherSuite; + for (int i = 0; i < sk_SSL_CIPHER_num(sk); i++) { + const SSL_CIPHER* c = sk_SSL_CIPHER_value(sk, i); + cipherSuite.cipherId_ = SSL_CIPHER_get_id(c); + cipherSuite.cipherName_ = SSL_CIPHER_get_name(c); + cipherSuiteVec.push_back(cipherSuite); + NETSTACK_LOGD("SSL_CIPHER_get_id = %{public}lu, SSL_CIPHER_get_name = %{public}s", + cipherSuite.cipherId_, cipherSuite.cipherName_.c_str()); + } +} + +void TLSContext::UseRemoteCipher(TLSContext *tlsContext) +{ + if (tlsContext->tlsConfiguration_.GetUseRemoteCipherPrefer()) { + SSL_CTX_set_options(tlsContext->ctx_, SSL_OP_CIPHER_SERVER_PREFERENCE); + } + NETSTACK_LOGI("SSL_CTX_get_options = %{public}lx", SSL_CTX_get_options(tlsContext->ctx_)); +} + +void TLSContext::SetMinAndMaxProtocol(TLSContext *tlsContext) +{ + const long anyVersion = TLS_ANY_VERSION; + long minVersion = anyVersion; + long maxVersion = anyVersion; + + switch (tlsContext->tlsConfiguration_.GetMinProtocol()) { + case TLS_V1_2: + minVersion = TLS1_2_VERSION; + break; + case TLS_V1_3: + minVersion = TLS1_3_VERSION; + break; + case UNKNOW_PROTOCOL: + break; + } + + switch (tlsContext->tlsConfiguration_.GetMaxProtocol()) { + case TLS_V1_2: + maxVersion = TLS1_2_VERSION; + break; + case TLS_V1_3: + maxVersion = TLS1_3_VERSION; + break; + case UNKNOW_PROTOCOL: + break; + } + + if (minVersion != anyVersion && !SSL_CTX_set_min_proto_version(tlsContext->ctx_, minVersion)) { + NETSTACK_LOGE("Error while setting the minimal protocol version"); + return; + } + + if (maxVersion != anyVersion && !SSL_CTX_set_max_proto_version(tlsContext->ctx_, maxVersion)) { + NETSTACK_LOGE("Error while setting the maximum protocol version"); + return; + } + + NETSTACK_LOGD("minProtocol = %{public}lx, maxProtocol = %{public}lx", + SSL_CTX_get_min_proto_version(tlsContext->ctx_), SSL_CTX_get_max_proto_version(tlsContext->ctx_)); +} + +bool TLSContext::SetCaAndVerify(TLSContext *tlsContext, const TLSConfiguration &configuration) +{ + for (const auto &cert : configuration.GetCaCertificate()) { + TLSCertificate ca(cert, CA_CERT); + if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(tlsContext->ctx_), (X509 *)ca.handle())) { + return false; + } + } + return true; +} + +bool TLSContext::SetLocalCertificate(TLSContext *tlsContext, const TLSConfiguration &configuration) +{ + X509_print_fp(stdout, (X509*)configuration.GetLocalCertificate().handle()); + if (!SSL_CTX_use_certificate(tlsContext->ctx_, (X509 *)configuration.GetLocalCertificate().handle())) { + NETSTACK_LOGE("Error loading local certificate"); + return false; + } + return true; +} + +bool TLSContext::SetKeyAndCheck(TLSContext *tlsContext, const TLSConfiguration &configuration) +{ + if (configuration.GetPrivateKey().Algorithm() == OPAQUE) { + tlsContext->pkey_ = reinterpret_cast(configuration.GetPrivateKey().handle()); + } else { + tlsContext->pkey_ = EVP_PKEY_new(); + if (configuration.GetPrivateKey().Algorithm() == ALGORITHM_RSA) { + EVP_PKEY_set1_RSA(tlsContext->pkey_, + reinterpret_cast(configuration.GetPrivateKey().handle())); + } else if (tlsContext->tlsConfiguration_.GetPrivateKey().Algorithm() == ALGORITHM_DSA) { + EVP_PKEY_set1_DSA(tlsContext->pkey_, + reinterpret_cast(configuration.GetPrivateKey().handle())); + } + } + + if (configuration.GetPrivateKey().Algorithm() == OPAQUE) { + tlsContext->pkey_ = nullptr; + } + auto pkey_ = tlsContext->pkey_; + if (!SSL_CTX_use_PrivateKey(tlsContext->ctx_, pkey_)) { + NETSTACK_LOGE("SSL_CTX_use_PrivateKey is error"); + return false; + } + + if (!configuration.GetPrivateKey().GetPasswd().empty()) { + std::string password = tlsContext->tlsConfiguration_.GetPrivateKey().GetPasswd(); + NETSTACK_LOGI("tlsContext->tlsConfiguration_.privateKey_.GetPasswd()%{public}s", password.c_str()); + const char *pass = password.c_str(); + SSL_CTX_set_default_passwd_cb_userdata(tlsContext->ctx_, (void*)pass); + } + + const char *passwd = static_cast(SSL_CTX_get_default_passwd_cb_userdata(tlsContext->ctx_)); + NETSTACK_LOGI("pass = %{public}s", passwd); + + // Check if the certificate matches the private key. + if (!SSL_CTX_check_private_key(tlsContext->ctx_)) { + NETSTACK_LOGE("Check if the certificate matches the private key is error"); + return false; + } + return true; +} + +void TLSContext::SetVerify(TLSContext *tlsContext) +{ + SSL_CTX_set_verify(tlsContext->ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); +} + +bool TLSContext::InitTlsContext(TLSContext *tlsContext, + TlsMode mode, + const TLSConfiguration &configuration, + bool allowRootCertOnDemandLoading) +{ + InitEnv(); + tlsContext->tlsConfiguration_ = configuration; + tlsContext->ctx_ = SSL_CTX_new(TLS_client_method()); + if (tlsContext->ctx_ == nullptr) { + ERR_print_errors_fp(stdout); + NETSTACK_LOGE("tlsContext->ctx_ is nullptr"); + return false; + } + + SetCipherList(tlsContext, configuration); + GetCiphers(tlsContext); + UseRemoteCipher(tlsContext); + SetMinAndMaxProtocol(tlsContext); + SetVerify(tlsContext); + if (!SetCaAndVerify(tlsContext, configuration)) { + return false; + } + if (!SetLocalCertificate(tlsContext, configuration)) { + return false; + } + if (!SetKeyAndCheck(tlsContext, configuration)) { + return false; + } + return true; +} +SSL *TLSContext::CreateSsl() +{ + ctxSsl_ = SSL_new(ctx_); + return ctxSsl_; +} + +void TLSContext::CloseCtx() +{ + SSL_CTX_free(ctx_); +} +} } // namespace OHOS::NetStack diff --git a/frameworks/native/tls_socket/src/tls_key.cpp b/frameworks/native/tls_socket/src/tls_key.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a4add526df7c36c19282d90e4d4dd4fc52ff9bde --- /dev/null +++ b/frameworks/native/tls_socket/src/tls_key.cpp @@ -0,0 +1,269 @@ +/* +* Copyright (c) 2022 Huawei Device 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 "tls_key.h" + +#include "netstack_log.h" + +namespace OHOS { +namespace NetStack { + +namespace { +constexpr int FILE_READ_Key_LEN = 4096; +constexpr const char *FILE_OPEN_FLAG = "rb"; +} // namespace + +TLSKey::TLSKey(const std::string &fileName, + KeyAlgorithm algorithm, + EncodingFormat encoding, + KeyType type, + const std::string &passPhrase) +{ + if (encoding == DER) { + DecodeDer(type, algorithm, fileName, passPhrase); + } else { + DecodePem(type, algorithm, fileName, passPhrase); + } +} + +TLSKey::TLSKey(const std::string &data, KeyAlgorithm algorithm, const std::string &passPhrase) +{ + if (data.empty()) { + NETSTACK_LOGE("TlsKey::TlsKey(const std::string &data, const std::string &passPhrase) data is empty"); + return; + } + DecodeData(data, algorithm, passPhrase); +} + +TLSKey &TLSKey::operator= (const TLSKey &other) +{ + if (other.rsa_ != nullptr) { + rsa_ = RSA_new(); + rsa_ = other.rsa_; + } + if (other.dsa_ != nullptr) { + dsa_ = DSA_new(); + dsa_ = other.dsa_; + } + if (other.dh_ != nullptr) { + dh_ = DH_new(); + dh_ = other.dh_; + } + if (other.genericKey_ != nullptr) { + genericKey_ = EVP_PKEY_new(); + genericKey_ = other.genericKey_; + } + keyIsNull_ = other.keyIsNull_; + keyType_ = other.keyType_; + keyAlgorithm_ = other.keyAlgorithm_; + passwd_ = other.passwd_; + return *this; +} + +void TLSKey::DecodeData(const std::string &data, KeyAlgorithm algorithm, const std::string &passPhrase) +{ + if (data.empty()) { + NETSTACK_LOGE("TlsKey::DecodeData data is empty"); + return; + } + keyAlgorithm_ = algorithm; + passwd_ = passPhrase; + BIO *bio = BIO_new_mem_buf(data.c_str(), -1); + if (!bio) { + NETSTACK_LOGE("TlsKey::DecodeData bio is null"); + return; + } + NETSTACK_LOGI("--- TlsKey::DecodeData rsa"); + RSA_print_fp(stdout,rsa_,11); + rsa_ = PEM_read_bio_RSAPrivateKey(bio, nullptr, nullptr, nullptr); + + if (rsa_) { + keyIsNull_ = false; + } +} + +void TLSKey::DecodeDer(KeyType type, + KeyAlgorithm algorithm, + const std::string &fileName, + const std::string &passPhrase) +{ + if (fileName.empty()) { + NETSTACK_LOGI("TlsKey::DecodeDer filename is empty"); + return; + } + keyType_ = type; + keyAlgorithm_ = algorithm; + passwd_ = passPhrase; + FILE *fp = nullptr; + fp = fopen(static_cast(fileName.c_str()), FILE_OPEN_FLAG); + if (!fp) { + NETSTACK_LOGE("TlsKey::DecodeDer: Couldn't open %{public}s file for reading", fileName.c_str()); + return; + } + char keyDer[FILE_READ_Key_LEN] = {}; + long keyLen = fread(keyDer, 1, FILE_READ_Key_LEN, fp); + (void)fclose(fp); + + const unsigned char *key_data = reinterpret_cast(keyDer); + if (type == PUBLIC_KEY) { + rsa_ = d2i_RSA_PUBKEY(nullptr, &key_data, keyLen); + } else { + rsa_ = d2i_RSAPrivateKey(nullptr, &key_data, keyLen); + } + if (!rsa_) { + NETSTACK_LOGE("TlsKey::DecodeDer rsa_ is null"); + return; + } + keyIsNull_ = false; +} + +void TLSKey::DecodePem(KeyType type, + KeyAlgorithm algorithm, + const std::string &fileName, + const std::string &passPhrase) +{ + if (fileName.empty()) { + NETSTACK_LOGE("TlsKey::DecodePem filename is empty"); + return; + } + keyType_ = type; + keyAlgorithm_ = algorithm; + FILE *fp = nullptr; + fp = fopen(static_cast(fileName.c_str()), FILE_OPEN_FLAG); + + if (!fp) { + NETSTACK_LOGE("TlsKey::DecodePem: Couldn't open %{public}s file for reading", fileName.c_str()); + return; + } + char privateKey[FILE_READ_Key_LEN] = {}; + if (!fread(privateKey, 1, FILE_READ_Key_LEN, fp)) { + NETSTACK_LOGE("TlsKey::DecodePem file read false"); + } + (void)fclose(fp); + const char *privateKeyData = static_cast(privateKey); + BIO *bio = BIO_new_mem_buf(privateKeyData, -1); + if (!bio) { + NETSTACK_LOGE("TlsKey::DecodePem: bio is null"); + return; + } + passwd_ = passPhrase; + switch (algorithm) { + case ALGORITHM_RSA: + rsa_ = (type == PUBLIC_KEY) + ? PEM_read_bio_RSA_PUBKEY(bio, nullptr, nullptr, nullptr) + : PEM_read_bio_RSAPrivateKey(bio, nullptr, nullptr, nullptr); + if (rsa_) { + keyIsNull_ = false; + } + break; + case ALGORITHM_DSA: + dsa_ = (type == PUBLIC_KEY) + ? PEM_read_bio_DSA_PUBKEY(bio, nullptr, nullptr, nullptr) + : PEM_read_bio_DSAPrivateKey(bio, nullptr, nullptr, nullptr); + if (dsa_) { + keyIsNull_ = false; + } + break; + case ALGORITHM_DH: { + EVP_PKEY *result = (type == PUBLIC_KEY) + ? PEM_read_bio_PUBKEY(bio, nullptr, nullptr, nullptr) + : PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr); + if (result) { + dh_ = EVP_PKEY_get1_DH(result); + } + if (dh_) { + keyIsNull_ = false; + } + EVP_PKEY_free(result); + break; + } + case ALGORITHM_EC: + ec_ = (type == PUBLIC_KEY) + ? PEM_read_bio_EC_PUBKEY(bio, nullptr, nullptr, nullptr) + : PEM_read_bio_ECPrivateKey(bio, nullptr, nullptr, nullptr); + if (ec_) { + keyIsNull_ = false; + } + break; + default: + NETSTACK_LOGE("TlsKey::DecodePem algorithm = %{public}d", algorithm); + } + BIO_free(bio); +} + +void TLSKey::Clear(bool deep) +{ + keyIsNull_ = true; + const auto algo = Algorithm(); + if (algo == ALGORITHM_RSA && rsa_) { + if (deep) { + RSA_free(rsa_); + } + rsa_ = nullptr; + } + if (algo == ALGORITHM_DSA && dsa_) { + if (deep) { + DSA_free(dsa_); + } + dsa_ = nullptr; + } + if (algo == ALGORITHM_DH && dh_) { + if (deep) { + DH_free(dh_); + } + dh_ = nullptr; + } + if (algo == ALGORITHM_EC && ec_) { + if (deep) { + EC_KEY_free(ec_); + } + ec_ = nullptr; + } + if (algo == OPAQUE && opaque_) { + if (deep) { + EVP_PKEY_free(opaque_); + } + opaque_ = nullptr; + } +} + +KeyAlgorithm TLSKey::Algorithm() const +{ + return keyAlgorithm_; +} + +Handle TLSKey::handle() const +{ + switch (keyAlgorithm_) { + case OPAQUE: + return Handle(OPAQUE); + case ALGORITHM_RSA: + return Handle(rsa_); + case ALGORITHM_DSA: + return Handle(dsa_); + case ALGORITHM_DH: + return Handle(dh_); + case ALGORITHM_EC: + return Handle(ec_); + default: + return Handle(nullptr); + } +} + +const std::string &TLSKey::GetPasswd() const +{ + return passwd_; +} +} } // namespace OHOS::NetStack diff --git a/frameworks/native/tls_socket/src/tls_socket.cpp b/frameworks/native/tls_socket/src/tls_socket.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b408940484bda55ad6979b705d429111a8a601b --- /dev/null +++ b/frameworks/native/tls_socket/src/tls_socket.cpp @@ -0,0 +1,953 @@ +/* + * Copyright (c) 2022 Huawei Device 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 "netstack_log.h" +#include "securec.h" + +#include "tls_socket.h" + +namespace OHOS { +namespace NetStack { + +namespace { +constexpr int WAIT_MS = 10; +constexpr int TIMEOUT_MS = 10000; +} + +TLSSecureOptions& TLSSecureOptions::operator=(const TLSSecureOptions &tlsSecureOptions) +{ + key_ = tlsSecureOptions.GetKey(); + caChain_ = tlsSecureOptions.GetCaChain(); + cert_ = tlsSecureOptions.GetCert(); + protocolChain_ = tlsSecureOptions.GetProtocolChain(); + crlChain_ = tlsSecureOptions.GetCrlChain(); + passwd_ = tlsSecureOptions.GetPasswd(); + signatureAlgorithms_ = tlsSecureOptions.GetSignatureAlgorithms(); + cipherSuite_ = tlsSecureOptions.GetCipherSuite(); + useRemoteCipherPrefer_ = tlsSecureOptions.UseRemoteCipherPrefer(); + return *this; +} + +void TLSSecureOptions::SetCaChain(const std::vector &caChain) +{ + caChain_ = caChain; +} + +void TLSSecureOptions::SetCert(const std::string &cert) +{ + cert_ = cert; +} + +void TLSSecureOptions::SetKey(const std::string &key) +{ + key_ = key; +} + +void TLSSecureOptions::SetPassWd(const std::string &passwd) +{ + passwd_ = passwd; +} + +void TLSSecureOptions::SetProtocolChain(const std::vector &protocolChain) +{ + protocolChain_ = protocolChain; +} + +void TLSSecureOptions::SetUseRemoteCipherPrefer(bool useRemoteCipherPrefer) +{ + useRemoteCipherPrefer_ = useRemoteCipherPrefer; +} + +void TLSSecureOptions::SetSignatureAlgorithms(const std::string &signatureAlgorithms) +{ + signatureAlgorithms_ = signatureAlgorithms; +} + +void TLSSecureOptions::SetCipherSuite(const std::string &cipherSuite) +{ + cipherSuite_ = cipherSuite; +} + +void TLSSecureOptions::SetCrlChain(const std::vector &crlChain) +{ + crlChain_ = crlChain; +} + +const std::vector& TLSSecureOptions::GetCaChain() const +{ + return caChain_; +} + +const std::string& TLSSecureOptions::GetCert() const +{ + return cert_; +} + +const std::string& TLSSecureOptions::GetKey() const +{ + return key_; +} + +const std::string& TLSSecureOptions::GetPasswd() const +{ + return passwd_; +} + +const std::vector& TLSSecureOptions::GetProtocolChain() const +{ + return protocolChain_; +} + +bool TLSSecureOptions::UseRemoteCipherPrefer() const +{ + return useRemoteCipherPrefer_; +} + +const std::string& TLSSecureOptions::GetSignatureAlgorithms() const +{ + return signatureAlgorithms_; +} + +const std::string& TLSSecureOptions::GetCipherSuite() const +{ + return cipherSuite_; +} + +const std::vector& TLSSecureOptions::GetCrlChain() const +{ + return crlChain_; +} + +void TLSConnectOptions::SetNetAddress(const NetAddress &address) +{ + address_.SetAddress(address.GetAddress()); + address_.SetPort(address.GetPort()); + address_.SetFamilyBySaFamily(address.GetSaFamily()); +} + +void TLSConnectOptions::SetTlsSecureOptions(TLSSecureOptions &tlsSecureOptions) +{ + tlsSecureOptions_ = tlsSecureOptions; +} + +void TLSConnectOptions::SetCheckServerIdentity(const CheckServerIdentity &checkServerIdentity) +{ + checkServerIdentity_ = checkServerIdentity; +} + +void TLSConnectOptions::SetAlpnProtocols(const std::vector &alpnProtocols) +{ + alpnProtocols_ = alpnProtocols; +} + +NetAddress TLSConnectOptions::GetNetAddress() const +{ + return address_; +} + +TLSSecureOptions TLSConnectOptions::GetTlsSecureOptions() const +{ + return tlsSecureOptions_; +} + +CheckServerIdentity TLSConnectOptions::GetCheckServerIdentity() const +{ + return checkServerIdentity_; +} + +const std::vector& TLSConnectOptions::GetAlpnProtocols() const +{ + return alpnProtocols_; +} + +std::string TLSSocket::MakeErrnoString() +{ + return strerror(errno); +} + +std::string TLSSocket::MakeAddressString(sockaddr *addr) +{ + if (addr->sa_family == AF_INET) { + auto *addr4 = reinterpret_cast(addr); + const char *str = inet_ntoa(addr4->sin_addr); + if (str == nullptr || strlen(str) == 0) { + return {}; + } + return str; + } else if (addr->sa_family == AF_INET6) { + auto *addr6 = reinterpret_cast(addr); + char str[INET6_ADDRSTRLEN] = {0}; + if (inet_ntop(AF_INET6, &addr6->sin6_addr, str, INET6_ADDRSTRLEN) == nullptr || strlen(str) == 0) { + return {}; + } + return str; + } + return {}; +} + +void TLSSocket::GetAddr(const NetAddress &address, + sockaddr_in *addr4, + sockaddr_in6 *addr6, + sockaddr **addr, + socklen_t *len) +{ + sa_family_t family = address.GetSaFamily(); + if (family == AF_INET) { + addr4->sin_family = AF_INET; + addr4->sin_port = htons(address.GetPort()); + addr4->sin_addr.s_addr = inet_addr(address.GetAddress().c_str()); + *addr = reinterpret_cast(addr4); + *len = sizeof(sockaddr_in); + } else if (family == AF_INET6) { + addr6->sin6_family = AF_INET6; + addr6->sin6_port = htons(address.GetPort()); + inet_pton(AF_INET6, address.GetAddress().c_str(), &addr6->sin6_addr); + *addr = reinterpret_cast(addr6); + *len = sizeof(sockaddr_in6); + } +} + +void TLSSocket::MakeTcpSocket(sa_family_t family) +{ + if (family != AF_INET && family != AF_INET6) { + return; + } + sockFd_ = socket(family, SOCK_STREAM, IPPROTO_TCP); +} + +void TLSSocket::StartReadMessage() +{ + std::thread thread([this]() { + isRunning_ = true; + isRunOver_ = false; + char buffer[MAX_BUFFER_SIZE]; + bzero(buffer, MAX_BUFFER_SIZE); + while (isRunning_) { + int len = openSslContext_.tlsSocketInternal_.GetRead(buffer, MAX_BUFFER_SIZE); + if (!isRunning_) { + break; + } + if (len < 0) { + NETSTACK_LOGE("SSL_read errno is %{public}d %{public}s", errno, MakeErrnoString().c_str()); + CallOnErrorCallback(errno, MakeErrnoString()); + break; + } + + if (len == 0) { + continue; + } + + SocketRemoteInfo remoteInfo; + openSslContext_.tlsSocketInternal_.MakeRemoteInfo(remoteInfo); + CallOnMessageCallback(buffer, remoteInfo); + } + isRunOver_ = true; + }); + thread.detach(); +} + +TLSSocket::~TLSSocket() +{ + if (sockFd_ < 0) { + CallOnErrorCallback(errno, MakeErrnoString()); + return; + } + + int ret = close(sockFd_); + if (ret < 0) { + NETSTACK_LOGE("close errno is %{public}d %{public}s", errno, MakeErrnoString().c_str()); + CallOnErrorCallback(errno, MakeErrnoString()); + return; + } + + CallOnCloseCallback(); +} + +void TLSSocket::CallOnMessageCallback(const std::string &data, const OHOS::NetStack::SocketRemoteInfo &remoteInfo) +{ + OnMessageCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (onMessageCallback_) { + func = onMessageCallback_; + } + } + + if (func) { + func(data, remoteInfo); + } +} + +void TLSSocket::CallOnConnectCallback() +{ + OnConnectCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (onConnectCallback_) { + func = onConnectCallback_; + } + } + + if (func) { + func(); + } +} + +void TLSSocket::CallOnCloseCallback() +{ + OnCloseCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (onCloseCallback_) { + func = onCloseCallback_; + } + } + + if (func) { + func(); + } +} + +void TLSSocket::CallOnErrorCallback(int32_t err, const std::string &errString) +{ + OnErrorCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (onErrorCallback_) { + func = onErrorCallback_; + } + } + + if (func) { + func(err, errString); + } +} + +void TLSSocket::CallBindCallback(bool ok, const BindCallback &callback) +{ + BindCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (bindCallback_) { + func = bindCallback_; + } + } + + if (func) { + func(ok); + } +} + +void TLSSocket::CallConnectCallback(bool ok, const ConnectCallback &callback) +{ + ConnectCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (connectCallback_) { + func = connectCallback_; + } + } + + if (func) { + func(ok); + } +} + +void TLSSocket::CallSendCallback(bool ok, const SendCallback &callback) +{ + SendCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (sendCallback_) { + func = sendCallback_; + } + } + + if (func) { + func(ok); + } +} + +void TLSSocket::CallCloseCallback(bool ok, const CloseCallback &callback) +{ + CloseCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (closeCallback_) { + func = closeCallback_; + } + } + + if (func) { + func(ok); + } +} + +void TLSSocket::CallGetRemoteAddressCallback(bool ok, const NetAddress &address, + const GetRemoteAddressCallback &callback) +{ + GetRemoteAddressCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (getRemoteAddressCallback_) { + func = getRemoteAddressCallback_; + } + } + + if (func) { + func(ok, address); + } +} + +void TLSSocket::CallGetStateCallback(bool ok, const SocketStateBase &state, + const GetStateCallback &callback) +{ + GetStateCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (getStateCallback_) { + func = getStateCallback_; + } + } + + if (func) { + func(ok, state); + } +} + +void TLSSocket::CallSetExtraOptionsCallback(bool ok, const SetExtraOptionsCallback &callback) +{ + SetExtraOptionsCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (setExtraOptionsCallback_) { + func = setExtraOptionsCallback_; + } + } + + if (func) { + func(ok); + } +} + +void TLSSocket::CallGetCertificateCallback(bool ok, const std::string &cert) +{ + GetCertificateCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (getCertificateCallback_) { + func = getCertificateCallback_; + } + } + + if (func) { + func(ok, cert); + } +} + +void TLSSocket::CallGetRemoteCertificateCallback(bool ok, const std::string &cert) +{ + GetRemoteCertificateCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (getRemoteCertificateCallback_) { + func = getRemoteCertificateCallback_; + } + } + + if (func) { + func(ok, cert); + } +} + +void TLSSocket::CallGetProtocolCallback(bool ok, const std::string &protocol) +{ + GetProtocolCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (getProtocolCallback_) { + func = getProtocolCallback_; + } + } + + if (func) { + func(ok, protocol); + } +} + +void TLSSocket::CallGetCipherSuiteCallback(bool ok, const std::vector &suite) +{ + GetCipherSuiteCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (getCipherSuiteCallback_) { + func = getCipherSuiteCallback_; + } + } + + if (func) { + func(ok, suite); + } +} + +void TLSSocket::CallGetSignatureAlgorithmsCallback(bool ok, + const std::vector &algorithms) +{ + GetSignatureAlgorithmsCallback func = nullptr; + { + std::lock_guard lock(mutex_); + if (getSignatureAlgorithmsCallback_) { + func = getSignatureAlgorithmsCallback_; + } + } + + if (func) { + func(ok, algorithms); + } +} + +void TLSSocket::Bind(const OHOS::NetStack::NetAddress &address, + const OHOS::NetStack::BindCallback &callback) +{ + if (sockFd_ >= 0) { + CallBindCallback(true, callback); + return; + } + + MakeTcpSocket(address.GetSaFamily()); + if (sockFd_ < 0) { + NETSTACK_LOGE("make tcp socket failed errno is %{public}d %{public}s", errno, MakeErrnoString().c_str()); + CallOnErrorCallback(errno, MakeErrnoString()); + CallBindCallback(false, callback); + return; + } + + sockaddr_in addr4 = {0}; + sockaddr_in6 addr6 = {0}; + sockaddr *addr = nullptr; + socklen_t len; + GetAddr(address, &addr4, &addr6, &addr, &len); + if (addr == nullptr) { + NETSTACK_LOGE("TLSSocket::Bind Address Is Invalid"); + CallOnErrorCallback(-1, "Address Is Invalid"); + CallBindCallback(false, callback); + return; + } + + if (bind(sockFd_, addr, len) < 0) { + if (errno != EADDRINUSE) { + NETSTACK_LOGE("TLSSocket::Bind bind error is %{public}s %{public}d", MakeErrnoString().c_str(), errno); + CallOnErrorCallback(errno, MakeErrnoString()); + CallBindCallback(false, callback); + return; + } + + if (addr->sa_family == AF_INET) { + addr4.sin_port = 0; /* distribute a random port */ + } else if (addr->sa_family == AF_INET6) { + addr6.sin6_port = 0; /* distribute a random port */ + } + + if (bind(sockFd_, addr, len) < 0) { + NETSTACK_LOGE("TLSSocket::Bind rebind error is %{public}s %{public}d", MakeErrnoString().c_str(), errno); + CallOnErrorCallback(errno, MakeErrnoString()); + CallBindCallback(false, callback); + return; + } + } + + CallBindCallback(true, callback); +} + +void TLSSocket::Connect(OHOS::NetStack::TLSConnectOptions &tlsConnectOptions, + const OHOS::NetStack::ConnectCallback &callback) +{ + TlsConnectOptions options; + TlsSecureOptions secureOptions; + secureOptions.SetKey(tlsConnectOptions.GetTlsSecureOptions().GetKey()); + secureOptions.SetCa(tlsConnectOptions.GetTlsSecureOptions().GetCaChain()); + secureOptions.SetCert(tlsConnectOptions.GetTlsSecureOptions().GetCert()); + secureOptions.SetProtocol(tlsConnectOptions.GetTlsSecureOptions().GetProtocolChain()); + secureOptions.SetCrl(tlsConnectOptions.GetTlsSecureOptions().GetCrlChain()); + secureOptions.SetPasswd(tlsConnectOptions.GetTlsSecureOptions().GetPasswd()); + secureOptions.SetSignatureAlgorithms(tlsConnectOptions.GetTlsSecureOptions().GetSignatureAlgorithms()); + secureOptions.SetCipherSuite(tlsConnectOptions.GetTlsSecureOptions().GetCipherSuite()); + secureOptions.SetUseRemoteCipherPrefer(tlsConnectOptions.GetTlsSecureOptions().UseRemoteCipherPrefer()); + options.SetAddress(tlsConnectOptions.GetNetAddress()); + options.SetAlpnProtocols(tlsConnectOptions.GetAlpnProtocols()); + options.SetSecureOptions(secureOptions); + + auto res = openSslContext_.tlsSocketInternal_.TlsConnectToHost(options); + if (!res) { + CallOnErrorCallback(errno, MakeErrnoString()); + callback(false); + return; + } + + StartReadMessage(); + CallOnConnectCallback(); + callback(true); +} + +void TLSSocket::Send(const OHOS::NetStack::TCPSendOptions &tcpSendOptions, const OHOS::NetStack::SendCallback &callback) +{ + (void)tcpSendOptions; + + auto res = openSslContext_.tlsSocketInternal_.Send(tcpSendOptions.GetData()); + if (!res) { + CallOnErrorCallback(errno, MakeErrnoString()); + CallSendCallback(false, callback); + return; + } + CallSendCallback(true, callback); +} + +bool WaitConditionWithTimeout(bool *flag, int32_t timeoutMs) +{ + int MAX_WAIT_CNT = timeoutMs / WAIT_MS; + int cnt = 0; + while (!(*flag)) { + if (cnt >= MAX_WAIT_CNT) { + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_MS)); + cnt++; + } + return true; +} + +void TLSSocket::Close(const OHOS::NetStack::CloseCallback &callback) +{ + if (!WaitConditionWithTimeout(&isRunning_, TIMEOUT_MS)) { + callback(false); + } + isRunning_ = false; + if (!WaitConditionWithTimeout(&isRunOver_, TIMEOUT_MS)) { + callback(false); + } + auto res = openSslContext_.tlsSocketInternal_.Close(); + if (!res) { + CallOnErrorCallback(errno, MakeErrnoString()); + callback(false); + return; + } + callback(true); +} + +void TLSSocket::GetRemoteAddress(const OHOS::NetStack::GetRemoteAddressCallback &callback) +{ + sa_family_t family; + socklen_t len = sizeof(family); + int ret = getsockname(sockFd_, reinterpret_cast(&family), &len); + if (ret < 0) { + NETSTACK_LOGE("getsockname failed errno %{public}d", errno); + CallOnErrorCallback(errno, MakeErrnoString()); + CallGetRemoteAddressCallback(false, {}, callback); + return; + } + + if (family == AF_INET) { + GetIp4RemoteAddress(callback); + } else if (family == AF_INET6) { + GetIp6RemoteAddress(callback); + } +} + +void TLSSocket::GetIp4RemoteAddress(const OHOS::NetStack::GetRemoteAddressCallback &callback) +{ + sockaddr_in addr4 = {0}; + socklen_t len4 = sizeof(sockaddr_in); + + int ret = getpeername(sockFd_, reinterpret_cast(&addr4), &len4); + if (ret < 0) { + NETSTACK_LOGE("GetIp4RemoteAddress failed errno %{public}d", errno); + CallOnErrorCallback(errno, MakeErrnoString()); + CallGetRemoteAddressCallback(false, {}, callback); + return; + } + + std::string address = MakeAddressString(reinterpret_cast(&addr4)); + if (address.empty()) { + NETSTACK_LOGE("GetIp4RemoteAddress failed errno %{public}d", errno); + CallOnErrorCallback(-1, "Address is invalid"); + CallGetRemoteAddressCallback(false, {}, callback); + return; + } + NetAddress netAddress; + netAddress.SetAddress(address); + netAddress.SetFamilyBySaFamily(AF_INET); + netAddress.SetPort(ntohs(addr4.sin_port)); + CallGetRemoteAddressCallback(true, netAddress, callback); +} + +void TLSSocket::GetIp6RemoteAddress(const OHOS::NetStack::GetRemoteAddressCallback &callback) +{ + sockaddr_in6 addr6 = {0}; + socklen_t len6 = sizeof(sockaddr_in6); + + int ret = getpeername(sockFd_, reinterpret_cast(&addr6), &len6); + if (ret < 0) { + NETSTACK_LOGE("GetIp6RemoteAddress failed errno %{public}d", errno); + CallOnErrorCallback(errno, MakeErrnoString()); + CallGetRemoteAddressCallback(false, {}, callback); + return; + } + + std::string address = MakeAddressString(reinterpret_cast(&addr6)); + if (address.empty()) { + NETSTACK_LOGE("GetIp6RemoteAddress failed errno %{public}d", errno); + CallOnErrorCallback(-1, "Address is invalid"); + CallGetRemoteAddressCallback(false, {}, callback); + return; + } + NetAddress netAddress; + netAddress.SetAddress(address); + netAddress.SetFamilyBySaFamily(AF_INET6); + netAddress.SetPort(ntohs(addr6.sin6_port)); + CallGetRemoteAddressCallback(true, netAddress, callback); +} + +void TLSSocket::GetState(const OHOS::NetStack::GetStateCallback &callback) +{ + int opt; + socklen_t optLen = sizeof(int); + int r = getsockopt(sockFd_, SOL_SOCKET, SO_TYPE, &opt, &optLen); + if (r < 0) { + SocketStateBase state; + state.SetIsClose(true); + CallGetStateCallback(true, state, callback); + return; + } + + sa_family_t family; + socklen_t len = sizeof(family); + SocketStateBase state; + int ret = getsockname(sockFd_, reinterpret_cast(&family), &len); + state.SetIsBound(ret > 0); + ret = getpeername(sockFd_, reinterpret_cast(&family), &len); + state.SetIsConnected(ret > 0); + + CallGetStateCallback(true, state, callback); +} + +bool TLSSocket::SetBaseOptions(const ExtraOptionsBase &option) const +{ + if (option.GetReceiveBufferSize() != 0) { + int size = (int)option.GetReceiveBufferSize(); + if (setsockopt(sockFd_, SOL_SOCKET, SO_RCVBUF, reinterpret_cast(&size), sizeof(size)) < 0) { + return false; + } + } + + if (option.GetSendBufferSize() != 0) { + int size = (int)option.GetSendBufferSize(); + if (setsockopt(sockFd_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast(&size), sizeof(size)) < 0) { + return false; + } + } + + if (option.IsReuseAddress()) { + int reuse = 1; + if (setsockopt(sockFd_, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&reuse), sizeof(reuse)) < 0) { + return false; + } + } + + if (option.GetSocketTimeout() != 0) { + timeval timeout = {(int)option.GetSocketTimeout(), 0}; + if (setsockopt(sockFd_, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)) < 0) { + return false; + } + if (setsockopt(sockFd_, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast(&timeout), sizeof(timeout)) < 0) { + return false; + } + } + + return true; +} + +bool TLSSocket::SetExtraOptions(const TCPExtraOptions &option) const +{ + if (option.IsKeepAlive()) { + int keepalive = 1; + if (setsockopt(sockFd_, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive)) < 0) { + return false; + } + } + + if (option.IsOOBInline()) { + int oobInline = 1; + if (setsockopt(sockFd_, SOL_SOCKET, SO_OOBINLINE, &oobInline, sizeof(oobInline)) < 0) { + return false; + } + } + + if (option.IsTCPNoDelay()) { + int tcpNoDelay = 1; + if (setsockopt(sockFd_, IPPROTO_TCP, TCP_NODELAY, &tcpNoDelay, sizeof(tcpNoDelay)) < 0) { + return false; + } + } + + linger soLinger = {0}; + soLinger.l_onoff = option.socketLinger.IsOn(); + soLinger.l_linger = (int)option.socketLinger.GetLinger(); + if (setsockopt(sockFd_, SOL_SOCKET, SO_LINGER, &soLinger, sizeof(soLinger)) < 0) { + return false; + } + + return true; +} + +void TLSSocket::SetExtraOptions(const OHOS::NetStack::TCPExtraOptions &tcpExtraOptions, + const OHOS::NetStack::SetExtraOptionsCallback &callback) +{ + if (!SetBaseOptions(tcpExtraOptions)) { + NETSTACK_LOGE("SetExtraOptions errno %{public}d", errno); + CallOnErrorCallback(errno, MakeErrnoString()); + CallSetExtraOptionsCallback(false, callback); + return; + } + + if (!SetExtraOptions(tcpExtraOptions)) { + NETSTACK_LOGE("SetExtraOptions errno %{public}d", errno); + CallOnErrorCallback(errno, MakeErrnoString()); + CallSetExtraOptionsCallback(false, callback); + return; + } + + CallSetExtraOptionsCallback(true, callback); +} + +void TLSSocket::GetCertificate(const GetCertificateCallback &callback) +{ + std::string cert = openSslContext_.tlsSocketInternal_.GetCertificate(); + if (cert.empty()) { + NETSTACK_LOGE("GetCertificate errno %{public}d, %{public}s", errno, strerror(errno)); + CallOnErrorCallback(errno, MakeErrnoString()); + callback(false, ""); + return; + } + callback(true, cert); +} + +void TLSSocket::GetRemoteCertificate(const GetRemoteCertificateCallback &callback) +{ + std::string remoteCert = openSslContext_.tlsSocketInternal_.GetRemoteCertificate(); + if (remoteCert.empty()) { + NETSTACK_LOGE("GetRemoteCertificate errno %{public}d", errno); + CallOnErrorCallback(errno, MakeErrnoString()); + callback(false, ""); + return; + } + callback(true, remoteCert); +} + +void TLSSocket::GetProtocol(const GetProtocolCallback &callback) +{ + std::string protocal = openSslContext_.tlsSocketInternal_.GetProtocol(); + if (protocal.empty()) { + NETSTACK_LOGE("GetProtocol errno %{public}d", errno); + CallOnErrorCallback(errno, MakeErrnoString()); + callback(false, ""); + return; + } + callback(true, protocal); +} + +void TLSSocket::GetCipherSuite(const GetCipherSuiteCallback &callback) +{ + std::vector cipherSuite = openSslContext_.tlsSocketInternal_.GetCipherSuite(); + if (cipherSuite.empty()) { + NETSTACK_LOGE("GetCipherSuite errno %{public}d", errno); + CallOnErrorCallback(errno, MakeErrnoString()); + callback(false, cipherSuite); + return; + } + callback(true, cipherSuite); +} + +void TLSSocket::GetSignatureAlgorithms(const GetSignatureAlgorithmsCallback &callback) +{ + std::vector signatureAlgorithms = openSslContext_.tlsSocketInternal_.GetSignatureAlgorithms(); + if (signatureAlgorithms.empty()) { + NETSTACK_LOGE("GetSignatureAlgorithms errno %{public}d", errno); + CallOnErrorCallback(errno, MakeErrnoString()); + callback(false, {}); + return; + } + callback(true, signatureAlgorithms); +} + +void TLSSocket::OnMessage(const OHOS::NetStack::OnMessageCallback &onMessageCallback) +{ + std::lock_guard lock(mutex_); + onMessageCallback_ = onMessageCallback; +} + +void TLSSocket::OffMessage() +{ + std::lock_guard lock(mutex_); + if (onMessageCallback_) { + onMessageCallback_ = nullptr; + } +} + +void TLSSocket::OnConnect(const OnConnectCallback &onConnectCallback) +{ + std::lock_guard lock(mutex_); + onConnectCallback_ = onConnectCallback; +} + +void TLSSocket::OffConnect() +{ + std::lock_guard lock(mutex_); + if (onConnectCallback_) { + onConnectCallback_ = nullptr; + } +} + +void TLSSocket::OnClose(const OnCloseCallback &onCloseCallback) +{ + std::lock_guard lock(mutex_); + onCloseCallback_ = onCloseCallback; +} + +void TLSSocket::OffClose() +{ + std::lock_guard lock(mutex_); + if (onCloseCallback_) { + onCloseCallback_ = nullptr; + } +} + +void TLSSocket::OnError(const OnErrorCallback &onErrorCallback) +{ + std::lock_guard lock(mutex_); + onErrorCallback_ = onErrorCallback; +} + +void TLSSocket::OffError() +{ + std::lock_guard lock(mutex_); + if (onErrorCallback_) { + onErrorCallback_ = nullptr; + } +} +} } // namespace OHOS::NetStack diff --git a/frameworks/native/tls_socket/src/tls_socket_internal.cpp b/frameworks/native/tls_socket/src/tls_socket_internal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2d8a915ca1946901b26baafa705c099999982ca --- /dev/null +++ b/frameworks/native/tls_socket/src/tls_socket_internal.cpp @@ -0,0 +1,661 @@ +/* +* Copyright (c) 2022 Huawei Device 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 "tls_socket_internal.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "socket_exec.h" +#include "socket_state_base.h" +#include "tls_context.h" +#include "netstack_common_utils.h" +#include "netstack_log.h" + +#include "securec.h" + +namespace OHOS { +namespace NetStack { + +namespace { +constexpr int REMOTE_CERT_LEN = 8192; +constexpr int PROTOCOL_V1_2 = 0x303; +constexpr int PROTOCOL_V1_3 = 0x304; +constexpr const char *TLS_VERSION_1_1 = "TLSv1.1"; +constexpr const char * UNKNOWN_ERROR = "SSL_ERROR_UNKNOWN_"; +} +struct ErrorInfo { + int32_t errorCode; + const char *errorString; +}; +ErrorInfo g_errorInfos[] = { + { SSL_ERROR_NONE, "SSL_ERROR_NONE" }, + { SSL_ERROR_WANT_READ, "SSL_ERROR_WANT_READ"}, + { SSL_ERROR_WANT_WRITE, "SSL_ERROR_WANT_WRITE"}, + { SSL_ERROR_ZERO_RETURN, "SSL_ERROR_ZERO_RETURN"}, + { SSL_ERROR_WANT_CONNECT, "SSL_ERROR_WANT_CONNECT"}, + { SSL_ERROR_WANT_ACCEPT, "SSL_ERROR_WANT_ACCEPT"}, + { SSL_ERROR_WANT_X509_LOOKUP, "SSL_ERROR_WANT_X509_LOOKUP"}, + { SSL_ERROR_WANT_ASYNC, "SSL_ERROR_WANT_ASYNC"}, + { SSL_ERROR_WANT_ASYNC_JOB, "SSL_ERROR_WANT_ASYNC_JOB"}, + { SSL_ERROR_SSL, "SSL_ERROR_SSL"}, + { SSL_ERROR_SYSCALL, "SSL_ERROR_SYSCALL"} +}; + +std::string GetErrorString(int32_t errorCode) +{ + for (const auto &p : g_errorInfos) { + if (p.errorCode == errorCode) { + return p.errorString; + } + } + return UNKNOWN_ERROR + std::to_string(errorCode); +} + +void SetIsBound(SocketStateBase state, + sa_family_t family, + const sockaddr_in *addr4, + const sockaddr_in6 *addr6) +{ + if (family == AF_INET) { + state.SetIsBound(ntohs(addr4->sin_port) != 0); + } else if (family == AF_INET6) { + state.SetIsBound(ntohs(addr6->sin6_port) != 0); + } +} + +void SetIsConnected(SocketStateBase state, + sa_family_t family, + const sockaddr_in *addr4, + const sockaddr_in6 *addr6) +{ + if (family == AF_INET) { + state.SetIsConnected(ntohs(addr4->sin_port) != 0); + } else if (family == AF_INET6) { + state.SetIsConnected(ntohs(addr6->sin6_port) != 0); + } +} + +std::string MakeAddressString(sockaddr *addr) +{ + if (addr->sa_family == AF_INET) { + auto *addr4 = reinterpret_cast(addr); + const char *str = inet_ntoa(addr4->sin_addr); + if (str == nullptr || strlen(str) == 0) { + return {}; + } + return str; + } else if (addr->sa_family == AF_INET6) { + auto *addr6 = reinterpret_cast(addr); + char str[INET6_ADDRSTRLEN] = {0}; + if (inet_ntop(AF_INET6, &addr6->sin6_addr, str, INET6_ADDRSTRLEN) == nullptr || strlen(str) == 0) { + return {}; + } + return str; + } + return {}; +} + +bool SetBaseOptions(int sock, ExtraOptionsBase *option) +{ + if (option->GetReceiveBufferSize() != 0) { + int size = (int)option->GetReceiveBufferSize(); + if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, reinterpret_cast(&size), sizeof(size)) < 0) { + return false; + } + } + + if (option->GetSendBufferSize() != 0) { + int size = (int)option->GetSendBufferSize(); + if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, reinterpret_cast(&size), sizeof(size)) < 0) { + return false; + } + } + + if (option->IsReuseAddress()) { + int reuse = 1; + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&reuse), sizeof(reuse)) < 0) { + return false; + } + } + + if (option->GetSocketTimeout() != 0) { + timeval timeout = {(int)option->GetSocketTimeout(), 0}; + if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)) < 0) { + return false; + } + if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast(&timeout), sizeof(timeout)) < 0) { + return false; + } + } + return true; +} + +int MakeIpSocket(sa_family_t family) +{ + if (family != AF_INET && family != AF_INET6) { + return -1; + } + int sock = socket(family, SOCK_STREAM, IPPROTO_IP); + if (sock < 0) { + NETSTACK_LOGE("make tcp socket failed errno is %{public}d %{public}s", errno, strerror(errno)); + return -1; + } + return sock; +} + +bool ExecSocketConnect(const std::string &hostName, int port, sa_family_t family, int socketDescriptor) +{ + struct sockaddr_in dest = {0}; + bzero(&dest, sizeof(dest)); + dest.sin_family = family; + dest.sin_port = htons(port); + if (inet_aton(hostName.c_str(), (struct in_addr *) &dest.sin_addr.s_addr) == 0) { + NETSTACK_LOGE("hostName is %s", hostName.c_str()); + return false; + } + int connectResult = connect(socketDescriptor, reinterpret_cast(&dest), sizeof(dest)); + if (connectResult == -1) { + NETSTACK_LOGE("socket connect error."); + return false; + } + return true; +} + +bool TLSSocketInternal::TlsConnectToHost(TlsConnectOptions options) +{ + configuration_.SetPrivateKey(options.GetTlsSecureOptions().GetKey(), options.GetTlsSecureOptions().GetPasswd()); + configuration_.SetCaCertificate(options.GetTlsSecureOptions().GetCa()); + configuration_.SetLocalCertificate(options.GetTlsSecureOptions().GetCert()); + configuration_.SetCipherSuite(options.GetTlsSecureOptions().GetCipherSuite()); + X509_print_fp(stdout, (X509*)configuration_.GetLocalCertificate().handle()); + int result = 0; + result = MakeIpSocket(address_.GetSaFamily()); + if (!result) { + return false; + } + socketDescriptor_ = result; + if (!ExecSocketConnect(options.GetAddress().GetAddress(), + options.GetAddress().GetPort(), + options.GetAddress().GetSaFamily(), + socketDescriptor_)) { + return false; + } + return StartTlsConnected(); +} + +bool TLSSocketInternal::StartTlsConnected() +{ + if (!CreatTlsContext()) { + return false; + } + if (!StartShakingHands()) { + return false; + } + return true; +} + +bool TLSSocketInternal::CreatTlsContext() +{ + tlsContextPointer_ = TLSContext::CreateConfiguration(SSL_CLIENT_MODE, configuration_, + IsRootsOnDemandAllowed()); + if (!tlsContextPointer_) { + return false; + } + if (!(ssl_ = tlsContextPointer_->CreateSsl())) { + NETSTACK_LOGI("Error creating SSL session"); + return false; + } + SSL_set_fd(ssl_, socketDescriptor_); + SSL_set_connect_state(ssl_); + return true; +} + +bool TLSSocketInternal::StartShakingHands() +{ + int result = SSL_connect(ssl_); + if (result == -1) { + if (errorCallback_) { + errorCallback_(errno, strerror(errno)); + } + ERR_print_errors_fp(stderr); + int errorStatus = SSL_get_error(ssl_, result); + NETSTACK_LOGE("%{public}s", GetErrorString(errorStatus).c_str()); + return false; + } + configuration_.SetProtocol(SSL_get_version(ssl_)); + std::string list = SSL_get_cipher_list(ssl_, 0); + NETSTACK_LOGI("SSL_get_cipher_list: %{public}s", list.c_str()); + configuration_.SetCipherSuite(list); + if (!SetSharedSigalgs()) { + NETSTACK_LOGE("TlsSocket::StartShakingHands SetSharedSigalgs is false"); + } + if (!SetRemoteCertificate()) { + NETSTACK_LOGE("TlsSocket::StartShakingHands SetRemoteCertificate is false"); + } + NETSTACK_LOGI("SSL Get Version: %{public}s, SSL Get Cipher: %{public}s", + SSL_get_version(ssl_), + SSL_get_cipher(ssl_)); + return true; +} + +TLSConfiguration TLSSocketInternal::GetTlsConfiguration() const +{ + return configuration_; +} + +bool TLSSocketInternal::IsRootsOnDemandAllowed() const +{ + return allowRootCertOnDemandLoading_; +} + +void TLSSocketInternal::SetTlsConfiguration(const TLSConfiguration &config) +{ + configuration_.GetPrivateKey() = config.PrivateKey(); + configuration_.GetLocalCertificate() = config.GetLocalCertificate(); + configuration_.GetCaCertificate() = config.GetCaCertificate(); +} + +bool TLSSocketInternal::SetAlpnProtocols(const std::vector &alpnProtocols) +{ + int len = 0, i = 0; + for (const auto &str : alpnProtocols) { + len += str.length(); + } + auto result = std::make_unique(alpnProtocols.size() + len); + for (const auto &str : alpnProtocols) { + len = str.length(); + result[i++] = len; + strcpy(reinterpret_cast(&result[i]), (const char *) str.c_str()); + i = i + len; + } + + NETSTACK_LOGI("%{public}s", result.get()); + if (SSL_set_alpn_protos(ssl_, result.get(), i)) { + if (errorCallback_) { + errorCallback_(errno, strerror(errno)); + } + NETSTACK_LOGE("Failed to set negotiable protocol list"); + return false; + } + return true; +} + +bool TLSSocketInternal::Send(const std::string &data) +{ + NETSTACK_LOGI("data to send :%{public}s", data.c_str()); + int len = 0; + len = SSL_write(ssl_, data.c_str(), data.length()); + if (len < 0) { + if (errorCallback_) { + errorCallback_(errno, strerror(errno)); + } + NETSTACK_LOGE("data '%{public}s' send failed!The error code is %{public}d, The error message is'%{public}s'", + data.c_str(), errno, strerror(errno)); + return false; + } else { + NETSTACK_LOGI("data '%{public}s' Sent successfully,sent in total %{public}d bytes!", data.c_str(), len); + } + return true; +} + +int TLSSocketInternal::GetRead(char *buffer, int MAX_BUFFER_SIZE) +{ + return SSL_read(ssl_, buffer, MAX_BUFFER_SIZE); +} + +void TLSSocketInternal::MakeRemoteInfo(SocketRemoteInfo &remoteInfo) +{ + remoteInfo.SetAddress(hostName_); + remoteInfo.SetPort(port_); + remoteInfo.SetFamily(family_); +} + +void TLSSocketInternal::Recv() +{ + std::thread thread([this]() { + int len; + char buffer[MAX_BUF_LEN + 1]; + bzero(buffer, MAX_BUF_LEN + 1); + + while (1) { + bzero(buffer, MAX_BUF_LEN + 1); + len = SSL_read(ssl_, buffer, MAX_BUF_LEN); + if (len > 0) { + NETSTACK_LOGD("Receive message successfully:'%{public}s',total %{public}d bytes of data", buffer, len); + if (recvCallback_) { + SocketRemoteInfo remoteInfo; + remoteInfo.SetAddress(hostName_); + remoteInfo.SetPort(port_); + remoteInfo.SetFamily(family_); + recvCallback_(buffer, remoteInfo); + } + break; + } else { + if (errorCallback_) { + errorCallback_(errno, strerror(errno)); + } + } + } + }); + thread.detach(); +} + +bool TLSSocketInternal::GetRemoteAddress(NetAddress &address) const +{ + sa_family_t family; + socklen_t len = sizeof(family); + int ret = getsockname(socketDescriptor_, reinterpret_cast(&family), &len); + if (ret < 0) { + if (errorCallback_) { + errorCallback_(errno, strerror(errno)); + } + NETSTACK_LOGE("Error in getsockname"); + return false; + } + if (family == AF_INET) { + sockaddr_in addr4 = {0}; + socklen_t len4 = sizeof(sockaddr_in); + ret = getpeername(socketDescriptor_, reinterpret_cast(&addr4), &len4); + if (ret < 0) { + if (errorCallback_) { + errorCallback_(errno, strerror(errno)); + } + NETSTACK_LOGE("Error in getpeername"); + return false; + } + std::string addressStr = MakeAddressString(reinterpret_cast(&addr4)); + if (addressStr.empty()) { + NETSTACK_LOGE("Error in MakeAddressString"); + return false; + } + address.SetAddress(addressStr); + address.SetFamilyBySaFamily(family); + address.SetPort(ntohs(addr4.sin_port)); + return true; + } else if (family == AF_INET6) { + sockaddr_in6 addr6 = {0}; + socklen_t len6 = sizeof(sockaddr_in6); + ret = getpeername(socketDescriptor_, reinterpret_cast(&addr6), &len6); + if (ret < 0) { + if (errorCallback_) { + errorCallback_(errno, strerror(errno)); + } + NETSTACK_LOGE("Error in getpeername"); + return false; + } + std::string addressStr = MakeAddressString(reinterpret_cast(&addr6)); + if (addressStr.empty()) { + NETSTACK_LOGE("MakeAddressString is empty"); + return false; + } + address.SetAddress(addressStr); + address.SetFamilyBySaFamily(family); + address.SetPort(ntohs(addr6.sin6_port)); + return true; + } + return false; +} + +bool TLSSocketInternal::SetRemoteCertificate() +{ + peerX509_ = SSL_get_peer_certificate(ssl_); + if (peerX509_ == nullptr) { + NETSTACK_LOGE("open fail errno = %{public}d reason = %{public}s \n", errno, strerror(errno)); + return false; + } + BIO *bio = BIO_new(BIO_s_mem()); + X509_print(bio, peerX509_); + if (!bio) { + NETSTACK_LOGE("TlsSocket::SetRemoteCertificate bio is null"); + return false; + } + char data[REMOTE_CERT_LEN]; + if (!BIO_read(bio, data, REMOTE_CERT_LEN)) { + NETSTACK_LOGE("TlsSocket::SetRemoteCertificate BIO_read is error"); + BIO_free(bio); + return false; + } + BIO_free(bio); + remoteCert_ = std::string(data); + NETSTACK_LOGI("TlsSocket::SetRemoteCertificate %{public}s", remoteCert_.c_str()); + return true; +} + +std::string TLSSocketInternal::GetRemoteCertificate() const +{ + return remoteCert_; +} + +std::string TLSSocketInternal::GetCertificate() const +{ + return configuration_.GetCertificate(); +} + +bool TLSSocketInternal::SetSharedSigalgs() +{ + if (!ssl_) { + NETSTACK_LOGE("TlsSocket::SetSharedSigalgs ssl_ is null"); + return false; + } + int number = SSL_get_shared_sigalgs(ssl_, 0, nullptr, nullptr, nullptr, nullptr, nullptr); + if (!number) { + NETSTACK_LOGE("TlsSocket::SetSharedSigalgs SSL_get_shared_sigalgs number is 0"); + return false; + } + for (int i = 0; i < number; i++) { + int hash_nid; + int sign_nid; + std::string sig_with_md; + SSL_get_shared_sigalgs(ssl_, i, &sign_nid, &hash_nid, nullptr, nullptr, nullptr); + switch (sign_nid) { + case EVP_PKEY_RSA: + sig_with_md = "RSA+"; + break; + case EVP_PKEY_RSA_PSS: + sig_with_md = "RSA-PSS+"; + break; + case EVP_PKEY_DSA: + sig_with_md = "DSA+"; + break; + case EVP_PKEY_EC: + sig_with_md = "ECDSA+"; + break; + case NID_ED25519: + sig_with_md = "Ed25519+"; + break; + case NID_ED448: + sig_with_md = "Ed448+"; + break; + default: + const char* sn = OBJ_nid2sn(sign_nid); + if (sn != nullptr) { + sig_with_md = std::string(sn) + "+"; + } else { + sig_with_md = "UNDEF+"; + } + break; + } + const char* sn_hash = OBJ_nid2sn(hash_nid); + if (sn_hash != nullptr) { + sig_with_md += std::string(sn_hash); + } else { + sig_with_md += "UNDEF"; + } + signatureAlgorithms_.push_back(sig_with_md); + } + for (auto l : signatureAlgorithms_) { + NETSTACK_LOGI("signatureAlgorithms_ =%{public}s ", l.c_str()); + } + return true; +} + +std::vector TLSSocketInternal::GetSignatureAlgorithms() const +{ + return signatureAlgorithms_; +} + +bool TLSSocketInternal::GetPasswd() +{ + if (configuration_.GetPrivateKey().GetPasswd().empty()) { + return false; + } + passwd_ = configuration_.GetPrivateKey().GetPasswd(); + NETSTACK_LOGI("--- GetPasswd is %{public}s", passwd_.c_str()); + return true; +} + +bool TLSSocketInternal::ExtraOptions(const TCPExtraOptions &options) const +{ + if (!SetBaseOptions(socketDescriptor_, (ExtraOptionsBase *) &options)) { + NETSTACK_LOGE("Error in SetBaseOptions"); + return false; + } + + if (options.IsKeepAlive()) { + int keepalive = 1; + if (setsockopt(socketDescriptor_, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive)) < 0) { + if (errorCallback_) { + errorCallback_(errno, strerror(errno)); + } + NETSTACK_LOGE("Error in setsockopt KeepAlive"); + return false; + } + } + + if (options.IsOOBInline()) { + int oobInline = 1; + if (setsockopt(socketDescriptor_, SOL_SOCKET, SO_OOBINLINE, &oobInline, sizeof(oobInline)) < 0) { + if (errorCallback_) { + errorCallback_(errno, strerror(errno)); + } + NETSTACK_LOGE("Error in setsockopt OOBInline"); + return false; + } + } + + if (options.IsTCPNoDelay()) { + int tcpNoDelay = 1; + if (setsockopt(socketDescriptor_, IPPROTO_TCP, TCP_NODELAY, &tcpNoDelay, sizeof(tcpNoDelay)) < 0) { + if (errorCallback_) { + errorCallback_(errno, strerror(errno)); + } + NETSTACK_LOGE("Error in setsockopt TCPNoDelay"); + return false; + } + } + + linger soLinger = {0}; + soLinger.l_onoff = options.socketLinger.IsOn(); + soLinger.l_linger = (int)options.socketLinger.GetLinger(); + if (setsockopt(socketDescriptor_, SOL_SOCKET, SO_LINGER, &soLinger, sizeof(soLinger)) < 0) { + if (errorCallback_) { + errorCallback_(errno, strerror(errno)); + } + NETSTACK_LOGE("Error in setsockopt SO_LINGER"); + return false; + } + return true; +} + +bool TLSSocketInternal::GetPeerCertificate() +{ + peerX509_ = SSL_get_peer_certificate(ssl_); + X509_print_fp(stdout, peerX509_); + BIO *bio = BIO_new(BIO_s_mem()); + X509_print(bio, peerX509_); + char data[REMOTE_CERT_LEN]; + if (BIO_read(bio, data, REMOTE_CERT_LEN)) { + NETSTACK_LOGI("wo is PeerCertToString is success "); + } + NETSTACK_LOGI("%{public}s", data); + return true; +} + +TLSProtocol TLSSocketInternal::GetProtocol() const +{ + if (!ssl_) { + return UNKNOW_PROTOCOL; + } + const int version = SSL_version(ssl_); + switch (version) { + case PROTOCOL_V1_2: + return TLS_V1_2; + case PROTOCOL_V1_3: + return TLS_V1_3; + default: + return UNKNOW_PROTOCOL; + } +} + +std::vector TLSSocketInternal::GetCipherSuite() +{ + if (!ssl_) { + return {}; + } + STACK_OF(SSL_CIPHER)* sk = SSL_get_ciphers(ssl_); + CipherSuite cipherSuite; + std::vector cipherSuiteVec; + for (int i = 0; i < sk_SSL_CIPHER_num(sk); i++) { + const SSL_CIPHER* c = sk_SSL_CIPHER_value(sk, i); + cipherSuite.cipherId_ = SSL_CIPHER_get_id(c); + cipherSuite.cipherName_ = SSL_CIPHER_get_name(c); + cipherSuiteVec.push_back(cipherSuite.cipherName_); + NETSTACK_LOGI("SSL_CIPHER_get_id = %{public}lu, SSL_CIPHER_get_name = %{public}s", cipherSuite.cipherId_, cipherSuite.cipherName_.c_str()); + } + return cipherSuiteVec; +} + +bool TLSSocketInternal::Close() +{ + if (!ssl_) { + NETSTACK_LOGE("ssl in NULL"); + return false; + } + int result = SSL_shutdown(ssl_); + if (result < 0) { + if (errorCallback_) { + errorCallback_(errno, strerror(errno)); + } + NETSTACK_LOGE("Error in shutdown"); + return false; + } + SSL_free(ssl_); + close(socketDescriptor_); + tlsContextPointer_->CloseCtx(); + return true; +} + +std::string TLSSocketInternal::GetProtocol() +{ + if (ssl_) { + return SSL_get_version(ssl_); + } + return TLS_VERSION_1_1; +} + +ssl_st *TLSSocketInternal::GetSSL() +{ + return ssl_; +} +} } // namespace OHOS::NetStack diff --git a/interfaces/innerkits/tls_socket/include/tls_socket.h b/interfaces/innerkits/tls_socket/include/tls_socket.h new file mode 100644 index 0000000000000000000000000000000000000000..11e021e01bff5a6ac6046c9171f2073be793155e --- /dev/null +++ b/interfaces/innerkits/tls_socket/include/tls_socket.h @@ -0,0 +1,473 @@ +/* + * Copyright (c) 2022 Huawei Device 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. + */ + +#ifndef COMMUNICATIONNETSTACK_TLS_SOCEKT_H +#define COMMUNICATIONNETSTACK_TLS_SOCEKT_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "extra_options_base.h" +#include "net_address.h" +#include "socket_remote_info.h" +#include "socket_state_base.h" +#include "tcp_connect_options.h" +#include "tcp_extra_options.h" +#include "tcp_send_options.h" + +#include "tls_key.h" +#include "tls_certificate.h" +#include "tls_configuration.h" +#include "tls_context.h" +#include "tls_socket_internal.h" + +namespace OHOS { +namespace NetStack { + +using BindCallback = std::function; +using ConnectCallback = std::function; +using SendCallback = std::function; +using CloseCallback = std::function; +using GetRemoteAddressCallback = std::function; +using GetStateCallback = std::function; +using SetExtraOptionsCallback = std::function; +using GetCertificateCallback = std::function; +using GetRemoteCertificateCallback = std::function; +using GetProtocolCallback = std::function; +using GetCipherSuiteCallback = std::function &suite)>; +using GetSignatureAlgorithmsCallback = std::function &algorithms)>; + +using OnMessageCallback = std::function; +using OnConnectCallback = std::function; +using OnCloseCallback = std::function; +using OnErrorCallback = std::function; + +using CheckServerIdentity = + std::function(const std::string &hostName, + const std::vector &x509Certificates)>; + +static constexpr const char *PROTOCOL_TLS_V12 = "TLSv1.2"; +static constexpr const char *PROTOCOL_TLS_V13 = "TLSv1.3"; + +static constexpr const char *ALPN_PROTOCOLS_HTTP_1_1 = "http1.1"; +static constexpr const char *ALPN_PROTOCOLS_HTTP_2 = "h2"; + +/** +* TODO: +*/ +class TLSSecureOptions { +public: + TLSSecureOptions() = default; + ~TLSSecureOptions() = default; + + TLSSecureOptions& operator=(const TLSSecureOptions &tlsSecureOptions); + /** + * set root CA Chain to verify the server cert + * @param caChain root certificate chain to verify the server + */ + void SetCaChain(const std::vector &caChain); + + /** + * set cert chain to send to server/client for check + * @param certChain cert chain to send to server/client for check + */ + void SetCert(const std::string &cert); + + /** + * set key chain to decrypt server data + * @param keyChain key chain to decrypt server data + */ + void SetKey(const std::string &key); + + /** + * set cert password + * @param passwd creating cert used password + */ + void SetPassWd(const std::string &passwd); + + /** + * set protocol Chain to encryption data + * @param protocolChain protocol Chain to encryption data + */ + void SetProtocolChain(const std::vector &protocolChain); + + /** + * set flag use Remote Cipher Prefer + * @param useRemoteCipherPrefer is use Remote Cipher Prefer + */ + void SetUseRemoteCipherPrefer(bool useRemoteCipherPrefer); + + /** + * set signature Algorithms for encryption/decrypt data + * @param signatureAlgorithms signature Algorithms e.g: rsa + */ + void SetSignatureAlgorithms(const std::string &signatureAlgorithms); + + /** + * set cipher Suite + * @param cipherSuite cipher Suite + */ + void SetCipherSuite(const std::string &cipherSuite); + + /** + * set crl chain for to creat cert chain + * @param crlChain crl chain for to creat cert chain TODO:: + */ + void SetCrlChain(const std::vector &crlChain); + + /** + * get root CA Chain to verify the server cert + * @return root CA Chain to verify the server cert + */ + [[nodiscard]] const std::vector& GetCaChain() const; + + /** + * get cert chain to send to server/client for check + * @return cert chain to send to server/client for check + */ + [[nodiscard]] const std::string& GetCert() const; + + /** + * get key chain to decrypt server data + * @return key chain to decrypt server data + */ + [[nodiscard]] const std::string& GetKey() const; + + /** + * get cert creat used password + * @return password + */ + [[nodiscard]] const std::string& GetPasswd() const; + + /** + * get protocol Chain to encryption data + * @return protocol Chain to encryption data + */ + [[nodiscard]] const std::vector& GetProtocolChain() const; + + /** + * get flag use Remote Cipher Prefer + * @return is use Remote Cipher Prefer + */ + [[nodiscard]] bool UseRemoteCipherPrefer() const; + + /** + * get signature Algorithms for encryption/decrypt data + * @return signature Algorithms for encryption/decrypt data + */ + [[nodiscard]] const std::string& GetSignatureAlgorithms() const; + + /** + * get cipher suite + * @return cipher suite + */ + [[nodiscard]] const std::string& GetCipherSuite() const; + + /** + * get crl chain for to creat cert chain + * @return crl chain for to creat cert chain + */ + [[nodiscard]] const std::vector& GetCrlChain() const; + +private: + std::vector caChain_; + std::string cert_; + std::string key_; + std::string passwd_; + std::vector protocolChain_; + bool useRemoteCipherPrefer_ = false; + std::string signatureAlgorithms_; + std::string cipherSuite_; + std::vector crlChain_; +}; + +/** + * tls connect options + */ +class TLSConnectOptions { +public: + /** + * Set Net Socket Address + * @param address socket address + */ + void SetNetAddress(const NetAddress &address); + + /** + * Set Tls Secure Options + * @param tlsSecureOptions class TLSSecureOptions + */ + void SetTlsSecureOptions(TLSSecureOptions &tlsSecureOptions); + + /** + * Check Server Identity + * @param checkServerIdentity TODO:: + */ + void SetCheckServerIdentity(const CheckServerIdentity &checkServerIdentity); + + /** + * Set Alpn Protocols + * @param alpnProtocols alpn Protocols + */ + void SetAlpnProtocols(const std::vector &alpnProtocols); + + /** + * Get Net Socket Address + * @return net socket address + */ + [[nodiscard]] NetAddress GetNetAddress() const; + + /** + * Get TLS Secure Options + * @return tls secure options + */ + [[nodiscard]] TLSSecureOptions GetTlsSecureOptions() const; + + /** + * Check Server Indentity + * @return Server Indentity + */ + [[nodiscard]] CheckServerIdentity GetCheckServerIdentity() const; + + /** + * Get Alpn Protocols + * @return alpn protocols + */ + [[nodiscard]] const std::vector& GetAlpnProtocols() const; + +private: + NetAddress address_; + TLSSecureOptions tlsSecureOptions_; + CheckServerIdentity checkServerIdentity_; + std::vector alpnProtocols_; +}; + +/** + * TLS socket interface class + */ +class TLSSocket { +public: + TLSSocket(const TLSSocket &) = delete; + TLSSocket(TLSSocket &&) = delete; + + TLSSocket &operator=(const TLSSocket &) = delete; + TLSSocket &operator=(TLSSocket &&) = delete; + + TLSSocket() = default; + ~TLSSocket(); + + /** + * Establish Bind Monitor + * @param address Ip address + * @param callback callback + */ + void Bind(const NetAddress &address, const BindCallback &callback); + + /** + * Establish connection + * @param tlsConnectOptions tls connect options + * @param callback callback + */ + void Connect(TLSConnectOptions &tlsConnectOptions, const ConnectCallback &callback); + + /** + * Send Data + * @param tcpSendOptions tcp send options + * @param callback callback + */ + void Send(const TCPSendOptions &tcpSendOptions, const SendCallback &callback); + + /** + * Close + * @param callback callback + */ + void Close(const CloseCallback &callback); + + /** + * Get Remote Address + * @param callback callback + */ + void GetRemoteAddress(const GetRemoteAddressCallback &callback); + + /** + * Get Tls State + * @param callback callback state data + */ + void GetState(const GetStateCallback &callback); + + /** + * Set Extra Options + * @param tcpExtraOptions tcp extra options + * @param callback callback extra options + */ + void SetExtraOptions(const TCPExtraOptions &tcpExtraOptions, const SetExtraOptionsCallback &callback); + + /** + * Get Certificate + * @param callback callback certificate + */ + void GetCertificate(const GetCertificateCallback &callback); + + /** + * Get Remote Certificate + * @param needChain need chain + * @param callback callback get remote certificate + */ + void GetRemoteCertificate(const GetRemoteCertificateCallback &callback); + + /** + * Get Protocol + * @param callback callback protocol + */ + void GetProtocol(const GetProtocolCallback &callback); + + /** + * Get Cipher Suite + * @param callback callback cipher suite + */ + void GetCipherSuite(const GetCipherSuiteCallback &callback); + + /** + * Get Signature Algorithms + * @param callback callback signature algorithms + */ + void GetSignatureAlgorithms(const GetSignatureAlgorithmsCallback &callback); + + /** + * On Message + * @param onMessageCallback callback on message + */ + void OnMessage(const OnMessageCallback &onMessageCallback); + + /** + * On Connect + * @param onConnectCallback callback on connect + */ + void OnConnect(const OnConnectCallback &onConnectCallback); + + /** + * On Close + * @param onCloseCallback callback on close + */ + void OnClose(const OnCloseCallback &onCloseCallback); + + /** + * On Error + * @param onErrorCallback callback on error + */ + void OnError(const OnErrorCallback &onErrorCallback); + + /** + * On Error + * @param onErrorCallback callback on error + */ + void OffMessage(); + + /** + * Off Connect + */ + void OffConnect(); + + /** + * Off Close + */ + void OffClose(); + + /** + * Off Error + */ + void OffError(); + +private: + class OpenSSLContext { + public: + TLSContext tlsContext_; + TLSConfiguration tlsConfiguration_; + TLSCertificate tlsCertificate_; + TLSKey tlsKey_; + TLSSocketInternal tlsSocketInternal_; + }; + OpenSSLContext openSslContext_; + static std::string MakeErrnoString(); + + static std::string MakeAddressString(sockaddr *addr); + + static void + GetAddr(const NetAddress &address, sockaddr_in *addr4, sockaddr_in6 *addr6, sockaddr **addr, socklen_t *len); + + void CallOnMessageCallback(const std::string &data, const SocketRemoteInfo &remoteInfo); + void CallOnConnectCallback(); + void CallOnCloseCallback(); + void CallOnErrorCallback(int32_t err, const std::string &errString); + + void CallBindCallback(bool ok, const BindCallback &callback); + void CallConnectCallback(bool ok, const ConnectCallback &callback); + void CallSendCallback(bool ok, const SendCallback &callback); + void CallCloseCallback(bool ok, const CloseCallback &callback); + void CallGetRemoteAddressCallback(bool ok, const NetAddress &address, const GetRemoteAddressCallback &callback); + void CallGetStateCallback(bool ok, const SocketStateBase &state, const GetStateCallback &callback); + void CallSetExtraOptionsCallback(bool ok, const SetExtraOptionsCallback &callback); + void CallGetCertificateCallback(bool ok, const std::string &cert); + void CallGetRemoteCertificateCallback(bool ok, const std::string &cert); + void CallGetProtocolCallback(bool ok, const std::string &protocol); + void CallGetCipherSuiteCallback(bool ok, const std::vector &suite); + void CallGetSignatureAlgorithmsCallback(bool ok, const std::vector& algorithms); + + void StartReadMessage(); + + void GetIp4RemoteAddress(const GetRemoteAddressCallback &callback); + void GetIp6RemoteAddress(const GetRemoteAddressCallback &callback); + + [[nodiscard]] bool SetBaseOptions(const ExtraOptionsBase &option) const; + [[nodiscard]] bool SetExtraOptions(const TCPExtraOptions &option) const; + + void MakeTcpSocket(sa_family_t family); + + static constexpr const size_t MAX_ERROR_LEN = 128; + static constexpr const size_t MAX_BUFFER_SIZE = 8192; + + OnMessageCallback onMessageCallback_; + OnConnectCallback onConnectCallback_; + OnCloseCallback onCloseCallback_; + OnErrorCallback onErrorCallback_; + + BindCallback bindCallback_; + ConnectCallback connectCallback_; + SendCallback sendCallback_; + CloseCallback closeCallback_; + GetRemoteAddressCallback getRemoteAddressCallback_; + GetStateCallback getStateCallback_; + SetExtraOptionsCallback setExtraOptionsCallback_; + GetCertificateCallback getCertificateCallback_; + GetRemoteCertificateCallback getRemoteCertificateCallback_; + GetProtocolCallback getProtocolCallback_; + GetCipherSuiteCallback getCipherSuiteCallback_; + GetSignatureAlgorithmsCallback getSignatureAlgorithmsCallback_; + + std::mutex mutex_; + bool isRunning_ = false; + bool isRunOver_ = true; + + int sockFd_ = -1; +}; +} } // namespace OHOS::NetStack + +#endif // COMMUNICATIONNETSTACK_TLS_SOCEKT_H diff --git a/netstack_config.gni b/netstack_config.gni new file mode 100644 index 0000000000000000000000000000000000000000..a5c76b058b533b1038f7a85aa06e60217d5ec09b --- /dev/null +++ b/netstack_config.gni @@ -0,0 +1,17 @@ +# Copyright (c) 2022 Huawei Device 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. + +SUBSYSTEM_DIR = "//foundation/communication" +NETSTACK_DIR = "$SUBSYSTEM_DIR/netstack" +NETSTACK_NATIVE_ROOT = "$NETSTACK_DIR/frameworks/native" +NETSTACK_INNERKITS_DIR = "$NETSTACK_DIR/interfaces/innerkits" diff --git a/test/napi/socket/fuzztest/socketexec_fuzzer/BUILD.gn b/test/napi/socket/fuzztest/socketexec_fuzzer/BUILD.gn index 4314b5972eb82401345d4d274ad7ac443ca1857e..df69284c7ff3316b7e9a25f6d031ae1a1c3e62e0 100644 --- a/test/napi/socket/fuzztest/socketexec_fuzzer/BUILD.gn +++ b/test/napi/socket/fuzztest/socketexec_fuzzer/BUILD.gn @@ -15,38 +15,12 @@ import("//build/config/features.gni") import("//build/ohos.gni") import("//build/test.gni") +import("//foundation/communication/netstack/netstack_config.gni") ##############################fuzztest########################################## -SUBSYSTEM_DIR = "//foundation/communication" NETSTACK_NAPI_ROOT = "$SUBSYSTEM_DIR/netstack/frameworks/js/napi/" -utils_include = [ - "$SUBSYSTEM_DIR/netstack/utils/base_async_work/include", - "$SUBSYSTEM_DIR/netstack/utils/base_context/include", - "$SUBSYSTEM_DIR/netstack/utils/common_utils/include", - "$SUBSYSTEM_DIR/netstack/utils/event_manager/include", - "$SUBSYSTEM_DIR/netstack/utils/log/include", - "$SUBSYSTEM_DIR/netstack/utils/module_template/include", - "$SUBSYSTEM_DIR/netstack/utils/napi_utils/include", -] - -utils_source = [ - "$SUBSYSTEM_DIR/netstack/utils/base_context/src/netstack_base_context.cpp", - "$SUBSYSTEM_DIR/netstack/utils/common_utils/src/netstack_common_utils.cpp", - "$SUBSYSTEM_DIR/netstack/utils/event_manager/src/netstack_event_listener.cpp", - "$SUBSYSTEM_DIR/netstack/utils/event_manager/src/netstack_event_manager.cpp", - "$SUBSYSTEM_DIR/netstack/utils/module_template/src/netstack_module_template.cpp", - "$SUBSYSTEM_DIR/netstack/utils/napi_utils/src/netstack_napi_utils.cpp", -] - -common_include = [ - "//foundation/arkui/ace_engine/frameworks/base/utils", - "//foundation/arkui/napi/interfaces/kits", - "//foundation/arkui/napi", - "//third_party/node/src", -] - ohos_fuzztest("SocketExecFuzzTest") { module_out_path = "communication/netstack" fuzz_config_file = "//foundation/communication/netstack/test/napi/socket/fuzztest/socketexec_fuzzer" @@ -60,8 +34,6 @@ ohos_fuzztest("SocketExecFuzzTest") { "$NETSTACK_NAPI_ROOT/socket/options/include", "$NETSTACK_NAPI_ROOT/socket/task_queue/include", ] - include_dirs += utils_include - include_dirs += common_include cflags = [ "-g", @@ -91,13 +63,13 @@ ohos_fuzztest("SocketExecFuzzTest") { "$NETSTACK_NAPI_ROOT/socket/socket_exec/src/socket_exec.cpp", ] sources += [ "socket_exec_fuzzer.cpp" ] - sources += utils_source - deps = [ "//foundation/arkui/napi/:ace_napi" ] + deps = [ "$NETSTACK_DIR/utils/napi_utils:napi_utils" ] external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", + "napi:ace_napi", ] defines = [ diff --git a/test/unittest/tlssocket/BUILD.gn b/test/unittest/tlssocket/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f21891d3b05205be2e15b9c0ad18fa1a3b723f6b --- /dev/null +++ b/test/unittest/tlssocket/BUILD.gn @@ -0,0 +1,19 @@ +# Copyright (c) 2022 Huawei Device 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. + +import("//build/test.gni") + +group("unittest") { + testonly = true + deps = [ "client:tls_socket_unittest" ] +} diff --git a/test/unittest/tlssocket/client/BUILD.gn b/test/unittest/tlssocket/client/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9784f652f7f755007eb859366cd6d9ca5d64eba3 --- /dev/null +++ b/test/unittest/tlssocket/client/BUILD.gn @@ -0,0 +1,30 @@ +# Copyright (c) 2022 Huawei Device 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. + +import("//build/test.gni") +import("//foundation/communication/netstack/netstack_config.gni") + +ohos_unittest("tls_socket_unittest") { + sources = [ + "TlsSocketTest.cpp", + #"TlsSocketCertChainTest.cpp" + ] + + deps = [ "$NETSTACK_DIR/frameworks/native/tls_socket:tls_socket" ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + + module_out_path = "netstack/tls_socket_unittest" + part_name = "netstack" + subsystem_name = "communication" +} diff --git a/test/unittest/tlssocket/client/ClientCert/ca.crt b/test/unittest/tlssocket/client/ClientCert/ca.crt new file mode 100644 index 0000000000000000000000000000000000000000..66f0d2026bffc8f135a4d503c138e47e1dfcc5a6 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCert/ca.crt @@ -0,0 +1,23 @@ +-----BEGIN CERTIFICATE----- +MIID0TCCArmgAwIBAgIUCZ5b9GcdGuZSlOtEPh8jgd7Sn24wDQYJKoZIhvcNAQEL +BQAweDELMAkGA1UEBhMCQ04xCzAJBgNVBAgMAkdEMQswCQYDVQQHDAJTWjEMMAoG +A1UECgwDQ09NMQwwCgYDVQQLDANOU1AxCzAJBgNVBAMMAkNBMSYwJAYJKoZIhvcN +AQkBFhd6aGFuZ3poZXdlaTAxMDNAMTYzLmNvbTAeFw0yMjA0MjQwMTUzMjNaFw0y +MzA0MjQwMTUzMjNaMHgxCzAJBgNVBAYTAkNOMQswCQYDVQQIDAJHRDELMAkGA1UE +BwwCU1oxDDAKBgNVBAoMA0NPTTEMMAoGA1UECwwDTlNQMQswCQYDVQQDDAJDQTEm +MCQGCSqGSIb3DQEJARYXemhhbmd6aGV3ZWkwMTAzQDE2My5jb20wggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQC6mP/OO1aOt2Mp8z0tOf6ZZce/hVrl+Sx5 +g3hoaVNbqQ4hGXlmCBJu+CqUWvdHBlkzXSeGW6WCyywKRyXl/oJow1kjWlA1NnrL +SRz5u8d1yRbwXAkon5uE9dHVsayKJfIe0KRpBP9r20MVsPzlZYlVrZdZIVbtRzuS +AJbPtiVkXBBxq/8YgTyEXkh7aP1dPqybwCx9VzIs4y4+/GoM1l+cG9AMlhyiLGkB +LNwxmUuhyUCtfH+Z1KQM1fJpFjqMRA9Pif9ZOWqiiWCYzxsyF1Z7TRvLMUPISrOn +xrif4fUNCzoqjgrNocpjpcXY5PrDZX4aOy4OEPgE6k8Mvlz4akc9AgMBAAGjUzBR +MB0GA1UdDgQWBBQEdONzRnt5aX8cp6Gbu5KPcaBmUTAfBgNVHSMEGDAWgBQEdONz +Rnt5aX8cp6Gbu5KPcaBmUTAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUA +A4IBAQCZaTPG8tDmlLO8WyKSDxs7Vbh8z8WkXNvLUzqTNcT/99G++N0bEckt9aAQ +KKhlLjcnC0D5guFGtko56GwnwiEyANqnmxJXRViFP10Ok87hcbD5jP/z0wGFLS0K +1k3eZ/x6aq7ZoHKtLY+1QgKiafhrHiC04zRxs/buol/06+jnExveHgpPvmSMNeDf +C5Pe7a9KBUcUFlIjPNVJAKL/cYHCkuXv8sLrdsero8gXs9hax44DFuWyADFpkHdB +Sy1AYpNzomUPa0tc1LWsAG7ANnAe1MdWYKjIj9zx7zNaQC0YMSJUbhJRhXOcVpLw +jIwQFCUFGdT2os5CJJUSgKGrBtAo +-----END CERTIFICATE----- diff --git a/test/unittest/tlssocket/client/ClientCert/ca.der b/test/unittest/tlssocket/client/ClientCert/ca.der new file mode 100644 index 0000000000000000000000000000000000000000..717b78dd2e28c9f6a31a9fb2e26e9c7479cda63a Binary files /dev/null and b/test/unittest/tlssocket/client/ClientCert/ca.der differ diff --git a/test/unittest/tlssocket/client/ClientCert/certificate.der b/test/unittest/tlssocket/client/ClientCert/certificate.der new file mode 100644 index 0000000000000000000000000000000000000000..fb3fb6093173a15464459bbb352216f52c5e201c Binary files /dev/null and b/test/unittest/tlssocket/client/ClientCert/certificate.der differ diff --git a/test/unittest/tlssocket/client/ClientCert/client.crt b/test/unittest/tlssocket/client/ClientCert/client.crt new file mode 100644 index 0000000000000000000000000000000000000000..80693516681648d27b59425eaac0d50a238de17b --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCert/client.crt @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDezCCAmMCFD6h5R4QvySV9q9mC6s31qQFLX14MA0GCSqGSIb3DQEBCwUAMHgx +CzAJBgNVBAYTAkNOMQswCQYDVQQIDAJHRDELMAkGA1UEBwwCU1oxDDAKBgNVBAoM +A0NPTTEMMAoGA1UECwwDTlNQMQswCQYDVQQDDAJDQTEmMCQGCSqGSIb3DQEJARYX +emhhbmd6aGV3ZWkwMTAzQDE2My5jb20wHhcNMjIwNDI0MDIwMjU3WhcNMjMwNDI0 +MDIwMjU3WjB8MQswCQYDVQQGEwJDTjELMAkGA1UECAwCR0QxCzAJBgNVBAcMAlNa +MQwwCgYDVQQKDANDT00xDDAKBgNVBAsMA05TUDEPMA0GA1UEAwwGQ0xJRU5UMSYw +JAYJKoZIhvcNAQkBFhd6aGFuZ3poZXdlaTAxMDNAMTYzLmNvbTCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAKlc63+j5C7tLoaecpdhzzZtLy8iNSi6oLHc ++bPib1XWz1zcQ4On5ncGuuLSV2Tyse4tSsDbPycd8b9Teq6gdGrvirtGXau82zAq +no+t0mxVtV1r0OkSe+hnIrYKxTE5UDeAM319MSxWlCR0bg0uEAuVBPQpld5A9PQT +YCLbv4cTwB0sIKupsnNbrn2AsAlCFd288XeuTN+N87m05cDkprAkqkCJfAtRnejV +k+vbS+H6toR3P9PVQJXC77oM7cDOjR8AwpkRRA890XUWoQLwhHXvDpGPwKK+lLnG +FswiaHy3silUIOidwk7E/81BOqXSk77oUG6UQrVilkmu6g79VssCAwEAATANBgkq +hkiG9w0BAQsFAAOCAQEAOeqp+hFVRs4YB3UjU/3bvAUFQLS97gapCp2lk6jS88jt +uNeyvwulOAtZEbcoIIvzzNxvBDOVibTJ6gZU9P9g0WyRu2RTgy+UggNwH8u8KZzM +DT8sxuoYvRcEWbOhlNQgACa7AlQSLQifo8nvEMS2i9o8WHoHu42MRDYOHYVIwWXH +h6mZzfo+zrPyv3NFlwlWqaNiTGgnGCXzlVK3p5YYqLbNVYpy0U5FBxQ7fITsqcbK +PusAAEZzPxm8Epo647M28gNkdEEM/7bqhSTJO+jfkojgyQt2ghlw+NGCmG4dJGZb +yA7Z3PBj8aqEwmRUF8SAR1bxWBGk2IYRwgStuwvusg== +-----END CERTIFICATE----- diff --git a/test/unittest/tlssocket/client/ClientCert/client_rsa_private.pem.unsecure b/test/unittest/tlssocket/client/ClientCert/client_rsa_private.pem.unsecure new file mode 100644 index 0000000000000000000000000000000000000000..ead6b4a28a8a16470336b3ef60f7b01fa23db109 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCert/client_rsa_private.pem.unsecure @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAqVzrf6PkLu0uhp5yl2HPNm0vLyI1KLqgsdz5s+JvVdbPXNxD +g6fmdwa64tJXZPKx7i1KwNs/Jx3xv1N6rqB0au+Ku0Zdq7zbMCqej63SbFW1XWvQ +6RJ76GcitgrFMTlQN4AzfX0xLFaUJHRuDS4QC5UE9CmV3kD09BNgItu/hxPAHSwg +q6myc1uufYCwCUIV3bzxd65M343zubTlwOSmsCSqQIl8C1Gd6NWT69tL4fq2hHc/ +09VAlcLvugztwM6NHwDCmRFEDz3RdRahAvCEde8OkY/Aor6UucYWzCJofLeyKVQg +6J3CTsT/zUE6pdKTvuhQbpRCtWKWSa7qDv1WywIDAQABAoIBAFGpbCPvcmbuFjDy +1W4Iy1EC9G1VoSwyUKlyUzRZSjWpjfLIggVJP+bEZ/hWU61pGEIvtIupK5pA5f/K +0KzC0V9+gPYrx563QTjIVAwTVBLIgNq60dCQCQ7WK/Z62voRGIyqVCl94+ftFyE8 +wpO4UiRDhk/0fT7dMz882G32ZzNJmY9eHu+yOaRctJW2gRBROHpQfDGBCz7w8s2j +ulIcnvwGOrvVllsL+vgY95M0LOq0W8ObbUSlawTnNTSRxFL68Hz5EaVJ19EYvEcC +eWnpEqIfF8OhQ+mYbdrAutXCkqJLz3rdu5P2Lbk5Ht5ETfr7rtUzvb4+ExIcxVOs +eys8EgECgYEA29tTxJOy2Cb4DKB9KwTErD1sFt9Ed+Z/A3RGmnM+/h75DHccqS8n +g9DpvHVMcMWYFVYGlEHC1F+bupM9CgxqQcVhGk/ysJ5kXF6lSTnOQxORnku3HXnV +4QzgKtLfHbukW1Y2RZM3aCz+Hg+bJrpacWyWZ4tRWNYsO58JRaubZjsCgYEAxTSP +yUBleQejl5qO76PGUUs2W8+GPr492NJGb63mEiM1zTYLVN0uuDJ2JixzHb6o1NXZ +6i00pSksT3+s0eiBTRnF6BJ0y/8J07ZnfQQXRAP8ypiZtd3jdOnUxEHfBw2QaIdP +tVdUc2mpIhosAYT9sWpHYvlUqTCdeLwhkYfgeLECgYBoajjVcmQM3i0OKiZoCOKy +/pTYI/8rho+p/04MylEPdXxIXEWDYD6/DrgDZh4ArQc2kt2bCcRTAnk+WfEyVYUd +aXVdfry+/uqhJ94N8eMw3hlZeZIk8JkQQgIwtGd8goJjUoWB85Hr6vphIn5IHVcY +6T5hPLxMmaL2SeioawDpwwKBgQCFXjDH6Hc3zQTEKND2HIqou/b9THH7yOlG056z +NKZeKdXe/OfY8uT/yZDB7FnGCgVgO2huyTfLYvcGpNAZ/eZEYGPJuYGn3MmmlruS +fsvFQfUahu2dY3zKusEcIXhV6sR5DNnJSFBi5VhvKcgNFwYDkF7K/thUu/4jgwgo +xf33YQKBgDQffkP1jWqT/pzlVLFtF85/3eCC/uedBfxXknVMrWE+CM/Vsx9cvBZw +hi15LA5+hEdbgvj87hmMiCOc75e0oz2Rd12ZoRlBVfbncH9ngfqBNQElM7Bueqoc +JOpKV+gw0gQtiu4beIdFnYsdZoZwrTjC4rW7OI0WYoLJabMFFh3I +-----END RSA PRIVATE KEY----- diff --git a/test/unittest/tlssocket/client/ClientCert/sendTest.txt b/test/unittest/tlssocket/client/ClientCert/sendTest.txt new file mode 100644 index 0000000000000000000000000000000000000000..87cd892dd1867838db2b06ebf87a073194f5de16 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCert/sendTest.txt @@ -0,0 +1,6 @@ +First: +First Flight +Mr. Johnson had never been up in an aerophane +His friend started the engine and began to ta +After a minute or two he opened them again, looked +Several weeks later,Jhlynn and I were wakened by a small voice crying,"Da-da".Turning over to go back to sleep,my wife said,"She's calling you,dear" \ No newline at end of file diff --git a/test/unittest/tlssocket/client/ClientCertChain/agent/index.txt b/test/unittest/tlssocket/client/ClientCertChain/agent/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..6afbbfbc139561f0d74bbf281768813bcc20180e --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/agent/index.txt @@ -0,0 +1 @@ +V 230823082111Z 01 unknown /C=CN/ST=changchun/O=ahahaha Inc/OU=ahaha IT/CN=server.cn diff --git a/test/unittest/tlssocket/client/ClientCertChain/agent/index.txt.attr b/test/unittest/tlssocket/client/ClientCertChain/agent/index.txt.attr new file mode 100644 index 0000000000000000000000000000000000000000..3a7e39e6ee60a25017c2fd64fed55b665faa387c --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/agent/index.txt.attr @@ -0,0 +1 @@ +unique_subject = no diff --git a/test/unittest/tlssocket/client/ClientCertChain/agent/index.txt.attr.old b/test/unittest/tlssocket/client/ClientCertChain/agent/index.txt.attr.old new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/test/unittest/tlssocket/client/ClientCertChain/agent/index.txt.old b/test/unittest/tlssocket/client/ClientCertChain/agent/index.txt.old new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/test/unittest/tlssocket/client/ClientCertChain/agent/key/ca.csr b/test/unittest/tlssocket/client/ClientCertChain/agent/key/ca.csr new file mode 100644 index 0000000000000000000000000000000000000000..de28ef94ba87fa51869c40eaeb34c1551f72272a --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/agent/key/ca.csr @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICzDCCAbQCAQAwgYYxCzAJBgNVBAYTAkNOMRIwEAYDVQQIDAlHdWFuZ2Rvbmcx +EjAQBgNVBAcMCUd1YW5nemhvdTEdMBsGA1UECgwUR2xvYmFsIEdvb2dsZSBDQSBJ +bmMxFzAVBgNVBAsMDkdvb2dsZSAyMDE5IENBMRcwFQYDVQQDDA5Hb29nbGUgMjAx +OSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANMXi2jJJx9kFlrH +kbL6m7V7gTuosxk22ghJlPuj6RAwTXoRj5akg0oWDLLRPDJwLUK4ldDLa3+BaY5T +nmFPKdLLSp65S30w3nbDoI1wS6Vec4gU1KNCY206KUlbl9cinMw8Es2BskeR9LIy +ubEh9sCzcMUH7r2M5vJtQl/Znsfk1ku8CULalvcxXA0c6Wc8O90f/VByVJx0tnCq +t3mp/p57hx6Ru9+0aswIY21y/5/z816QQAfe679VcIBoOlSfYKxV52/9YPNETG9k +CuYI5v7E5RNHKzO0mUAuQLGCgvAcw5fkgUwjKxeg/G6+2d1QfLQdKlYEl86mlM/D +wb5+RWsCAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4IBAQC3QNIL+AeOJk85DWtnx+jr +8PHK02vwG9bA2Ta+xa8HWmIczLHXgiyctEhDqkYjVw2YGpJglKJjHwwg8Ha6UiMi +ilvsM0lhE/zQGbBjFyt52IEB0YKYCHpfv7TnqCKCmKzi+kIYOJqHVG1LqlhXEAY2 +yHgiqPtihBxOi8wi7HaNR/ToPETUf/884goU5qRNrSpyWBBtVF/4Bj3nGANkSe2+ +lTZ/vxW3cCe6p54vJfXe0cJJWL+sTa4X7/41KJg8OhxG3h55TKwna3v3JyxM0nyw +YnNyIOMdYCTOo19wQ1Vnf0VBzG1sKDgpgb56Pnccb5r6InwrrHpZEKCs5mAmTCcz +-----END CERTIFICATE REQUEST----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/agent/key/caMidcert.crt b/test/unittest/tlssocket/client/ClientCertChain/agent/key/caMidcert.crt new file mode 100644 index 0000000000000000000000000000000000000000..bd53701bf5d8e1d68c08babe5bd2c3b305538b3d --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/agent/key/caMidcert.crt @@ -0,0 +1,73 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 2 (0x2) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=CN, ST=beijing, O=Global Google CA Inc, OU=Root CA, CN=Global Google Root CA + Validity + Not Before: Aug 23 07:44:34 2022 GMT + Not After : Aug 23 07:44:34 2023 GMT + Subject: C=CN, ST=Guangdong, O=Global Google CA Inc, OU=Google 2019 CA, CN=Google 2019 CA + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + RSA Public-Key: (2048 bit) + Modulus: + 00:d3:17:8b:68:c9:27:1f:64:16:5a:c7:91:b2:fa: + 9b:b5:7b:81:3b:a8:b3:19:36:da:08:49:94:fb:a3: + e9:10:30:4d:7a:11:8f:96:a4:83:4a:16:0c:b2:d1: + 3c:32:70:2d:42:b8:95:d0:cb:6b:7f:81:69:8e:53: + 9e:61:4f:29:d2:cb:4a:9e:b9:4b:7d:30:de:76:c3: + a0:8d:70:4b:a5:5e:73:88:14:d4:a3:42:63:6d:3a: + 29:49:5b:97:d7:22:9c:cc:3c:12:cd:81:b2:47:91: + f4:b2:32:b9:b1:21:f6:c0:b3:70:c5:07:ee:bd:8c: + e6:f2:6d:42:5f:d9:9e:c7:e4:d6:4b:bc:09:42:da: + 96:f7:31:5c:0d:1c:e9:67:3c:3b:dd:1f:fd:50:72: + 54:9c:74:b6:70:aa:b7:79:a9:fe:9e:7b:87:1e:91: + bb:df:b4:6a:cc:08:63:6d:72:ff:9f:f3:f3:5e:90: + 40:07:de:eb:bf:55:70:80:68:3a:54:9f:60:ac:55: + e7:6f:fd:60:f3:44:4c:6f:64:0a:e6:08:e6:fe:c4: + e5:13:47:2b:33:b4:99:40:2e:40:b1:82:82:f0:1c: + c3:97:e4:81:4c:23:2b:17:a0:fc:6e:be:d9:dd:50: + 7c:b4:1d:2a:56:04:97:ce:a6:94:cf:c3:c1:be:7e: + 45:6b + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: + CA:TRUE + Signature Algorithm: sha256WithRSAEncryption + 8a:f3:81:7d:d1:f4:df:85:ba:74:a8:ee:c2:31:e4:96:e1:64: + 38:aa:7a:7a:c2:47:d8:e5:f9:94:1c:27:62:34:f9:7d:49:d8: + a8:ed:c7:7f:7e:cd:4a:c0:61:ff:94:ab:63:9a:eb:b2:bb:34: + ff:3f:d7:66:40:14:80:fc:fd:72:ad:27:f6:61:8e:12:ef:2d: + 39:b1:94:9b:1d:a7:60:4b:d4:52:80:82:08:5c:83:e5:3a:dd: + 57:a7:c2:35:ed:39:54:5b:4a:c2:68:da:30:a4:66:81:0d:b1: + af:9e:aa:ec:39:19:22:be:df:de:2b:5e:ae:8d:27:e3:78:8e: + b4:36:9a:1b:91:32:d3:d0:05:b3:8d:bf:29:ff:64:f9:7e:7c: + ea:5b:54:d4:3e:fa:c4:9e:ce:12:ee:37:ae:c7:38:85:d6:ba: + f5:3d:dc:a6:9c:83:e1:77:6b:0a:74:e1:19:e4:e3:5a:b6:ff: + bb:09:5b:1d:7d:c1:a0:66:fc:ef:d5:83:20:c1:44:9b:5c:c6: + a2:21:af:df:be:07:ea:a6:b1:6d:5f:fd:3f:eb:ab:87:e9:bd: + b8:3c:8e:f4:dd:52:64:c5:fd:cf:e9:dd:94:7b:99:e7:5c:99: + b7:23:68:2e:ca:77:bc:5c:48:3e:dd:d9:18:f0:82:9c:fd:f3: + 24:6a:18:5f +-----BEGIN CERTIFICATE----- +MIIDbTCCAlWgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBwMQswCQYDVQQGEwJDTjEQ +MA4GA1UECAwHYmVpamluZzEdMBsGA1UECgwUR2xvYmFsIEdvb2dsZSBDQSBJbmMx +EDAOBgNVBAsMB1Jvb3QgQ0ExHjAcBgNVBAMMFUdsb2JhbCBHb29nbGUgUm9vdCBD +QTAeFw0yMjA4MjMwNzQ0MzRaFw0yMzA4MjMwNzQ0MzRaMHIxCzAJBgNVBAYTAkNO +MRIwEAYDVQQIDAlHdWFuZ2RvbmcxHTAbBgNVBAoMFEdsb2JhbCBHb29nbGUgQ0Eg +SW5jMRcwFQYDVQQLDA5Hb29nbGUgMjAxOSBDQTEXMBUGA1UEAwwOR29vZ2xlIDIw +MTkgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDTF4toyScfZBZa +x5Gy+pu1e4E7qLMZNtoISZT7o+kQME16EY+WpINKFgyy0TwycC1CuJXQy2t/gWmO +U55hTynSy0qeuUt9MN52w6CNcEulXnOIFNSjQmNtOilJW5fXIpzMPBLNgbJHkfSy +MrmxIfbAs3DFB+69jObybUJf2Z7H5NZLvAlC2pb3MVwNHOlnPDvdH/1QclScdLZw +qrd5qf6ee4cekbvftGrMCGNtcv+f8/NekEAH3uu/VXCAaDpUn2CsVedv/WDzRExv +ZArmCOb+xOUTRysztJlALkCxgoLwHMOX5IFMIysXoPxuvtndUHy0HSpWBJfOppTP +w8G+fkVrAgMBAAGjEDAOMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEB +AIrzgX3R9N+FunSo7sIx5JbhZDiqenrCR9jl+ZQcJ2I0+X1J2Kjtx39+zUrAYf+U +q2Oa67K7NP8/12ZAFID8/XKtJ/ZhjhLvLTmxlJsdp2BL1FKAgghcg+U63VenwjXt +OVRbSsJo2jCkZoENsa+equw5GSK+394rXq6NJ+N4jrQ2mhuRMtPQBbONvyn/ZPl+ +fOpbVNQ++sSezhLuN67HOIXWuvU93Kacg+F3awp04Rnk41q2/7sJWx19waBm/O/V +gyDBRJtcxqIhr9++B+qmsW1f/T/rq4fpvbg8jvTdUmTF/c/p3ZR7medcmbcjaC7K +d7xcSD7d2Rjwgpz98yRqGF8= +-----END CERTIFICATE----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/agent/key/cakey.pem.unsecure b/test/unittest/tlssocket/client/ClientCertChain/agent/key/cakey.pem.unsecure new file mode 100644 index 0000000000000000000000000000000000000000..0869bc8e47ca1fbd4b7f67e647707a33aa80db14 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/agent/key/cakey.pem.unsecure @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEA0xeLaMknH2QWWseRsvqbtXuBO6izGTbaCEmU+6PpEDBNehGP +lqSDShYMstE8MnAtQriV0Mtrf4FpjlOeYU8p0stKnrlLfTDedsOgjXBLpV5ziBTU +o0JjbTopSVuX1yKczDwSzYGyR5H0sjK5sSH2wLNwxQfuvYzm8m1CX9mex+TWS7wJ +QtqW9zFcDRzpZzw73R/9UHJUnHS2cKq3ean+nnuHHpG737RqzAhjbXL/n/PzXpBA +B97rv1VwgGg6VJ9grFXnb/1g80RMb2QK5gjm/sTlE0crM7SZQC5AsYKC8BzDl+SB +TCMrF6D8br7Z3VB8tB0qVgSXzqaUz8PBvn5FawIDAQABAoIBAHjTGTC5MnN9Tm5X +nMXdPBL8xlPnk9vy0Ym81FHU2Coz+6TLOGz5bUySomIX8WTNYJq4HMiOJtGsuUaG +BjmcnkvRoLyJQvQ9bJh+EP/kLuhQz8AsbCmmblKu38Llclvpq+Ya3IhUnD7rBCyb +bD4/OoXCL+IXUEeexvIsJ7nFTmULRJfH5kyO9ZIgUL9abmawdYmPIkJDjw6zVq69 +5ORrSEQXYYILRvkwM7WiWmHZpperMiEZvjA2rbFXrkN/mj40jikBzM86F+lfR4UU +JI3E0uN1riGWhe9mCuJft0mo5rloIYydDJfRM9YRJt9OB4kaRzTJRBM/ARKiNHvG +9+QxoMECgYEA6++Z9Igks6RYOxdmt3+II1Qx2gvKlf9ewRkesmWdW5zBf3KakisN +uL+mugb1OHvXwnztPYqtAXAfOWd4aq0FKAXGplKHxFtQrKeiC21bhlemGNRRpmFo +xwENmXUgQ0SREl0qYEiPAn9hZRfKGqjGt+1ZqPIMkmqnhqwQ36VOX18CgYEA5QsV +C7DK8oxoGH/tPi53rxi0L3z1XvI9LRH16Tf45UpXcjuvCOrs0Vi4QCpaj3+1s8Xg +KXUG6HP5BBVLHGB441V8KSP2vJ4gYvxBCAeniAO2BHwTHPCR2ij/nIaUCZq86uek +SEovrWB41BoMVxjKhGoOg6cZyVLwpeAH6yPEsXUCgYBq3Reqfo/BHksoWK0ZqBYN +inEaBgU4c3aDl9EjlIr1l8a85zfDxORuLcBiugwQDWfom5UJLuq1oAdEhO0xxDR1 +sEgNxYvhEEs2KKdo7Ztq+gAtdt2UssI2gO+b9kUqsr/SxYgQHE1KIFAI7gGImbGI +VWUq9JdlKhG/Geh6o/EfmQKBgEoJ8A6sYp5PNuMcj1M3cCbgxHZJXYQIqC/mi2iN +WF6+TlA17NnkHxN5K25KgqW6ccEgKNsd4lLIEmn4fCQ7JzjNjGo8HulP8EYvJtJy +rvwvvunqNb94IJ21/RLbCgWkyIbixF894/WWpthhZzXMZMKzCegS3yoOLo5gQg8H +q/B1AoGBAMjt8xPvXTlyWHUxyhJi2S4Ml6mu7TqJIN9Ip2o4vJHOC50zFza5ZaSL +fb8+Cvyr6kyhz8dR/OXsL8lMgYL0d/Al91TkNiZ0ikZOUYbDE75OmnuzAEIGlkCM +qUR3b94ECWCXejRcqq2V/LXdhiNYtutVdRK9B4myrV71gBjOKdaE +-----END RSA PRIVATE KEY----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/agent/newcerts/01.pem b/test/unittest/tlssocket/client/ClientCertChain/agent/newcerts/01.pem new file mode 100644 index 0000000000000000000000000000000000000000..4f8bba606ddbfd154c60558999f056c82ad759d5 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/agent/newcerts/01.pem @@ -0,0 +1,75 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 1 (0x1) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=CN, ST=Guangdong, O=Global Google CA Inc, OU=Google 2019 CA, CN=Google 2019 CA + Validity + Not Before: Aug 23 08:21:11 2022 GMT + Not After : Aug 23 08:21:11 2023 GMT + Subject: C=CN, ST=changchun, O=ahahaha Inc, OU=ahaha IT, CN=server.cn + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + RSA Public-Key: (2048 bit) + Modulus: + 00:bd:5e:39:ac:20:03:00:75:d9:05:3c:ed:bc:60: + 5b:8e:c5:13:50:46:89:ea:91:f5:15:cf:95:2a:d3: + f3:f8:c6:a4:db:41:db:45:79:d1:46:a0:1d:25:4e: + c8:5c:32:d1:65:dc:86:7c:03:a0:58:58:02:8b:a4: + 51:48:37:26:ca:7c:ee:da:0e:f8:7b:e4:24:53:56: + e5:5c:dc:0f:30:42:dc:56:f3:47:49:9d:5a:2d:e6: + a4:86:04:3a:68:a8:c5:d5:8a:03:a0:58:6f:18:97: + 62:e6:ba:01:d1:67:2c:5f:ba:43:5e:0e:b5:af:a4: + 20:2e:69:e9:03:b1:87:ff:b1:6d:44:b6:db:c2:12: + 15:db:a2:39:1f:2c:ee:6b:42:0a:f8:a4:09:6c:4f: + a4:30:87:1d:b4:38:d7:00:3f:56:a7:4d:6d:18:d2: + 09:75:96:90:4b:88:00:bf:fb:bf:90:48:02:ab:10: + a1:e0:c1:f3:67:84:c7:28:c0:ee:e3:cc:9a:0f:47: + c9:3e:72:ec:03:cb:dc:60:30:cb:07:f8:c8:cc:fe: + b1:5a:3d:93:9b:16:8a:e6:72:cf:c8:c2:5b:38:ab: + 23:aa:cb:48:e1:ea:4d:84:fc:b2:ca:d2:15:60:a1: + ec:3d:6a:4f:a9:f8:e8:06:7c:70:7f:2c:dc:da:ec: + 84:59 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: + CA:FALSE + X509v3 Subject Alternative Name: + DNS:ahaha.cn, DNS:bbs.ahaha.cn, DNS:ahahaha.cn + Signature Algorithm: sha256WithRSAEncryption + b2:4a:50:b0:6e:75:34:c2:a2:94:1d:15:45:23:b0:d5:20:4c: + d3:98:bd:30:bf:52:b7:98:b3:fd:d8:41:7f:7e:98:aa:6c:0a: + bf:91:c9:49:a8:02:21:ce:d4:b7:c4:d9:57:0d:55:3f:43:d7: + ff:89:a9:64:52:57:a6:f9:89:e1:2c:95:e6:13:ef:dc:6b:c9: + be:fa:e1:cf:c7:c4:3a:b4:c1:9f:6a:e5:0d:83:1e:86:38:4f: + 9b:52:f0:e7:79:a0:6d:11:5c:c6:f3:38:00:6a:9a:c2:db:bd: + 5a:68:9e:05:4d:fd:cc:60:cf:8d:19:e9:f7:37:10:34:6e:b6: + 38:1c:72:ff:ea:77:c8:82:92:3d:1a:f4:3d:f8:86:aa:25:26: + 2a:43:4c:8c:a1:eb:af:5b:a5:36:08:1a:6b:b4:d4:07:5e:04: + 4f:43:27:99:e8:b6:d4:48:d3:33:4d:e2:0a:b5:ca:08:4a:e3: + 3b:86:2c:57:a2:99:8f:83:13:9c:7e:88:af:79:50:49:80:f1: + 68:5b:b6:fa:c5:1f:13:fa:57:b4:e9:44:89:3f:8f:f8:30:21: + 79:10:0f:5c:53:1e:60:84:77:8e:4f:e5:c9:4a:6b:e1:77:af: + e6:73:e0:df:9c:e9:6e:86:59:1f:64:8e:f5:5b:ce:36:23:f8: + b7:89:ca:15 +-----BEGIN CERTIFICATE----- +MIIDhzCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQsFADByMQswCQYDVQQGEwJDTjES +MBAGA1UECAwJR3Vhbmdkb25nMR0wGwYDVQQKDBRHbG9iYWwgR29vZ2xlIENBIElu +YzEXMBUGA1UECwwOR29vZ2xlIDIwMTkgQ0ExFzAVBgNVBAMMDkdvb2dsZSAyMDE5 +IENBMB4XDTIyMDgyMzA4MjExMVoXDTIzMDgyMzA4MjExMVowXjELMAkGA1UEBhMC +Q04xEjAQBgNVBAgMCWNoYW5nY2h1bjEUMBIGA1UECgwLYWhhaGFoYSBJbmMxETAP +BgNVBAsMCGFoYWhhIElUMRIwEAYDVQQDDAlzZXJ2ZXIuY24wggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQC9XjmsIAMAddkFPO28YFuOxRNQRonqkfUVz5Uq +0/P4xqTbQdtFedFGoB0lTshcMtFl3IZ8A6BYWAKLpFFINybKfO7aDvh75CRTVuVc +3A8wQtxW80dJnVot5qSGBDpoqMXVigOgWG8Yl2LmugHRZyxfukNeDrWvpCAuaekD +sYf/sW1EttvCEhXbojkfLO5rQgr4pAlsT6Qwhx20ONcAP1anTW0Y0gl1lpBLiAC/ ++7+QSAKrEKHgwfNnhMcowO7jzJoPR8k+cuwDy9xgMMsH+MjM/rFaPZObFormcs/I +wls4qyOqy0jh6k2E/LLK0hVgoew9ak+p+OgGfHB/LNza7IRZAgMBAAGjPDA6MAkG +A1UdEwQCMAAwLQYDVR0RBCYwJIIIYWhhaGEuY26CDGJicy5haGFoYS5jboIKYWhh +aGFoYS5jbjANBgkqhkiG9w0BAQsFAAOCAQEAskpQsG51NMKilB0VRSOw1SBM05i9 +ML9St5iz/dhBf36YqmwKv5HJSagCIc7Ut8TZVw1VP0PX/4mpZFJXpvmJ4SyV5hPv +3GvJvvrhz8fEOrTBn2rlDYMehjhPm1Lw53mgbRFcxvM4AGqawtu9WmieBU39zGDP +jRnp9zcQNG62OBxy/+p3yIKSPRr0PfiGqiUmKkNMjKHrr1ulNggaa7TUB14ET0Mn +mei21EjTM03iCrXKCErjO4YsV6KZj4MTnH6Ir3lQSYDxaFu2+sUfE/pXtOlEiT+P ++DAheRAPXFMeYIR3jk/lyUpr4Xev5nPg35zpboZZH2SO9VvONiP4t4nKFQ== +-----END CERTIFICATE----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/agent/openssl.cnf b/test/unittest/tlssocket/client/ClientCertChain/agent/openssl.cnf new file mode 100755 index 0000000000000000000000000000000000000000..ea887495cc70b16e782cf8f6f11fda104d7e806c --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/agent/openssl.cnf @@ -0,0 +1,62 @@ +[ ca ] +default_ca = CA_default + +[ CA_default ] +dir = /home/ts/Sol_net/SSL/Cert/ca/agent/ +certs = $dir/certs +crl_dir = $dir/crl +database = $dir/index.txt +new_certs_dir = $dir/newcerts +certificate = $dir/key/cacert.crt +serial = $dir/serial +crlnumber = $dir/crlnumber +crl = $dir/crl.pem +private_key = $dir/key/cakey.pem +RANDFILE = $dir/key/.rand +unique_subject = no + +x509_extensions = usr_cert +copy_extensions = copy + +name_opt = ca_default +cert_opt = ca_default + +default_days = 365 +default_crl_days= 30 +default_md = sha256 +preserve = no +policy = policy_ca + +[ policy_ca ] +countryName = supplied +stateOrProvinceName = supplied +organizationName = supplied +organizationalUnitName = supplied +commonName = supplied +emailAddress = optional + +[ req ] +default_bits = 2048 +default_keyfile = privekey.pem +distinguished_name = req_distinguished_name +attributes = req_attributes +x509_extensions = v3_ca +string_mask = utf8only +utf8 = yes +prompt = no + +[ req_distinguished_name ] +countryName = CN +stateOrProvinceName = Guangdong +localityName = Guangzhou +organizationName = Global Google CA Inc +organizationalUnitName = Google 2019 CA +commonName = Google 2019 CA + +[ usr_cert ] +basicConstraints = CA:FALSE + +[ v3_ca ] +basicConstraints = CA:TRUE + +[ req_attributes ] diff --git a/test/unittest/tlssocket/client/ClientCertChain/agent/serial b/test/unittest/tlssocket/client/ClientCertChain/agent/serial new file mode 100644 index 0000000000000000000000000000000000000000..9e22bcb8e3440869e9e1303f3b7045d1fc8e58c5 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/agent/serial @@ -0,0 +1 @@ +02 diff --git a/test/unittest/tlssocket/client/ClientCertChain/agent/serial.old b/test/unittest/tlssocket/client/ClientCertChain/agent/serial.old new file mode 100644 index 0000000000000000000000000000000000000000..8a0f05e166aa61225bf6649cb345f87416b5f509 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/agent/serial.old @@ -0,0 +1 @@ +01 diff --git a/test/unittest/tlssocket/client/ClientCertChain/root/index.txt b/test/unittest/tlssocket/client/ClientCertChain/root/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..2a01c18c1f157542919973f403e54cc88cda3b1e --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/root/index.txt @@ -0,0 +1,2 @@ +V 230823073355Z 01 unknown /C=CN/ST=beijing/O=Global Google CA Inc/OU=Root CA/CN=Global Google Root CA +V 230823074434Z 02 unknown /C=CN/ST=Guangdong/O=Global Google CA Inc/OU=Google 2019 CA/CN=Google 2019 CA diff --git a/test/unittest/tlssocket/client/ClientCertChain/root/index.txt.attr b/test/unittest/tlssocket/client/ClientCertChain/root/index.txt.attr new file mode 100644 index 0000000000000000000000000000000000000000..3a7e39e6ee60a25017c2fd64fed55b665faa387c --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/root/index.txt.attr @@ -0,0 +1 @@ +unique_subject = no diff --git a/test/unittest/tlssocket/client/ClientCertChain/root/index.txt.attr.old b/test/unittest/tlssocket/client/ClientCertChain/root/index.txt.attr.old new file mode 100644 index 0000000000000000000000000000000000000000..3a7e39e6ee60a25017c2fd64fed55b665faa387c --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/root/index.txt.attr.old @@ -0,0 +1 @@ +unique_subject = no diff --git a/test/unittest/tlssocket/client/ClientCertChain/root/index.txt.old b/test/unittest/tlssocket/client/ClientCertChain/root/index.txt.old new file mode 100644 index 0000000000000000000000000000000000000000..f8c87a6fb82b553ccf3f14c3b8824ecb8e025ba4 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/root/index.txt.old @@ -0,0 +1 @@ +V 230823073355Z 01 unknown /C=CN/ST=beijing/O=Global Google CA Inc/OU=Root CA/CN=Global Google Root CA diff --git a/test/unittest/tlssocket/client/ClientCertChain/root/key/ca.csr b/test/unittest/tlssocket/client/ClientCertChain/root/key/ca.csr new file mode 100644 index 0000000000000000000000000000000000000000..07887030bfe73cd0da3ab0ef29e898127208c7a6 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/root/key/ca.csr @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICyDCCAbACAQAwgYIxCzAJBgNVBAYTAkNOMRAwDgYDVQQIDAdiZWlqaW5nMRAw +DgYDVQQHDAdiZWlqaW5nMR0wGwYDVQQKDBRHbG9iYWwgR29vZ2xlIENBIEluYzEQ +MA4GA1UECwwHUm9vdCBDQTEeMBwGA1UEAwwVR2xvYmFsIEdvb2dsZSBSb290IENB +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnd9o93t4CyHzbyRg784C +kCTfxNPz5CZsxxK/KM04LT+rdhFkzmv2B/01HrnsInIDTevSlEktgkRsclkUq+cM +cjI+rfqdUtokjemkENfdNGbffuAOZlOL7pEHms4qhSUJdz1fdRyhs6uGOyEo+EOq +8At9TfnfhTNKO//kA1klYqHp2pJjApO9+d9uxlen0uZ7NxSpumlxDMVPZv5nZlyN +1wRN2PMLwAt9SetolCj2MQ8NKgNwp5f5OJA21Es5S1OlLDJy8kGGMhM8QC0/6GPT +jIqDedMg9rzNlz6UkU48dI2a+inexKX34eIGVeZsQQ9gO5DeOoTvOnd5JwAjVWbK +gQIDAQABoAAwDQYJKoZIhvcNAQELBQADggEBAInIX1e1iq9hgYERhFNBkg1AX03D +derOguyxvsD+PenhCHeJzWczVhTVLq2OipGVKNd5ryfD16gz2e64hcaf0WMEx4oc +KE9WW5w8V4PX2ra/6jMME7uSXf7yo6hG2/dEzGwgDxCbSWJAfC18fUmjUZVo3HCy +z6XbbzlUMUuvztAU/NafuAOtZhB5+iecEcWEeBzbH1W3lAmf+3DL0TJ/0pDdLVZa +rSnzzH1kfiB27IfL/V6dcoSgBi/IK5bQ7XjEvtx1n78RlYtxLDCxJ80hByMf8QTl +4GozhLKToaRS1fL+ZyqBXQZyyKYVbZn98rr2dXVfumXtViwJxx3ZrDqZfJo= +-----END CERTIFICATE REQUEST----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/root/key/cacert.crt b/test/unittest/tlssocket/client/ClientCertChain/root/key/cacert.crt new file mode 100644 index 0000000000000000000000000000000000000000..7b1f269c4d4ca4d8d24a2515065720c2a1a19934 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/root/key/cacert.crt @@ -0,0 +1,73 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 1 (0x1) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=CN, ST=beijing, O=Global Google CA Inc, OU=Root CA, CN=Global Google Root CA + Validity + Not Before: Aug 23 07:33:55 2022 GMT + Not After : Aug 23 07:33:55 2023 GMT + Subject: C=CN, ST=beijing, O=Global Google CA Inc, OU=Root CA, CN=Global Google Root CA + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + RSA Public-Key: (2048 bit) + Modulus: + 00:9d:df:68:f7:7b:78:0b:21:f3:6f:24:60:ef:ce: + 02:90:24:df:c4:d3:f3:e4:26:6c:c7:12:bf:28:cd: + 38:2d:3f:ab:76:11:64:ce:6b:f6:07:fd:35:1e:b9: + ec:22:72:03:4d:eb:d2:94:49:2d:82:44:6c:72:59: + 14:ab:e7:0c:72:32:3e:ad:fa:9d:52:da:24:8d:e9: + a4:10:d7:dd:34:66:df:7e:e0:0e:66:53:8b:ee:91: + 07:9a:ce:2a:85:25:09:77:3d:5f:75:1c:a1:b3:ab: + 86:3b:21:28:f8:43:aa:f0:0b:7d:4d:f9:df:85:33: + 4a:3b:ff:e4:03:59:25:62:a1:e9:da:92:63:02:93: + bd:f9:df:6e:c6:57:a7:d2:e6:7b:37:14:a9:ba:69: + 71:0c:c5:4f:66:fe:67:66:5c:8d:d7:04:4d:d8:f3: + 0b:c0:0b:7d:49:eb:68:94:28:f6:31:0f:0d:2a:03: + 70:a7:97:f9:38:90:36:d4:4b:39:4b:53:a5:2c:32: + 72:f2:41:86:32:13:3c:40:2d:3f:e8:63:d3:8c:8a: + 83:79:d3:20:f6:bc:cd:97:3e:94:91:4e:3c:74:8d: + 9a:fa:29:de:c4:a5:f7:e1:e2:06:55:e6:6c:41:0f: + 60:3b:90:de:3a:84:ef:3a:77:79:27:00:23:55:66: + ca:81 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: + CA:TRUE + Signature Algorithm: sha256WithRSAEncryption + 61:3e:39:71:7f:b1:50:dd:71:97:cd:dc:a9:4b:72:96:0a:12: + c1:18:fd:35:b5:e0:97:1b:76:58:22:8d:cd:75:51:0f:ba:04: + 00:94:6a:46:d5:3a:c5:ac:ea:7d:9c:ec:6f:19:b6:f1:2b:06: + e9:bb:cb:49:24:34:0b:55:bd:02:19:24:19:85:bb:e4:a4:80: + f4:d6:90:82:7e:81:5c:9b:89:d4:15:ed:3a:b7:a2:37:59:40: + db:b4:18:25:90:2e:ae:82:f9:a8:0c:9d:bd:c7:8c:54:85:ed: + 07:d1:70:1d:ee:a1:92:bd:12:97:83:4d:9e:9e:b7:01:b5:56: + a5:1f:31:6e:a1:48:68:a4:4f:1c:fa:b0:38:27:47:12:eb:55: + a3:45:f7:e3:18:ba:d7:85:3c:1f:2c:1e:5e:38:75:5e:80:8a: + fd:1c:84:4f:9b:ef:85:b7:79:89:d7:43:eb:d4:fb:c5:51:5b: + 84:6f:0e:06:32:54:13:e4:a7:e2:20:2d:b8:fa:2d:09:f8:8f: + dd:01:19:39:cc:23:c0:d1:39:19:9a:f7:7c:53:63:bf:ea:be: + 04:9b:af:3e:6e:1e:77:c8:b9:0b:78:e9:0e:62:a7:51:db:1e: + c0:63:4d:4d:14:ff:ca:44:7f:15:e4:fa:98:1e:3d:58:c2:b6: + 5a:64:68:d0 +-----BEGIN CERTIFICATE----- +MIIDazCCAlOgAwIBAgIBATANBgkqhkiG9w0BAQsFADBwMQswCQYDVQQGEwJDTjEQ +MA4GA1UECAwHYmVpamluZzEdMBsGA1UECgwUR2xvYmFsIEdvb2dsZSBDQSBJbmMx +EDAOBgNVBAsMB1Jvb3QgQ0ExHjAcBgNVBAMMFUdsb2JhbCBHb29nbGUgUm9vdCBD +QTAeFw0yMjA4MjMwNzMzNTVaFw0yMzA4MjMwNzMzNTVaMHAxCzAJBgNVBAYTAkNO +MRAwDgYDVQQIDAdiZWlqaW5nMR0wGwYDVQQKDBRHbG9iYWwgR29vZ2xlIENBIElu +YzEQMA4GA1UECwwHUm9vdCBDQTEeMBwGA1UEAwwVR2xvYmFsIEdvb2dsZSBSb290 +IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnd9o93t4CyHzbyRg +784CkCTfxNPz5CZsxxK/KM04LT+rdhFkzmv2B/01HrnsInIDTevSlEktgkRsclkU +q+cMcjI+rfqdUtokjemkENfdNGbffuAOZlOL7pEHms4qhSUJdz1fdRyhs6uGOyEo ++EOq8At9TfnfhTNKO//kA1klYqHp2pJjApO9+d9uxlen0uZ7NxSpumlxDMVPZv5n +ZlyN1wRN2PMLwAt9SetolCj2MQ8NKgNwp5f5OJA21Es5S1OlLDJy8kGGMhM8QC0/ +6GPTjIqDedMg9rzNlz6UkU48dI2a+inexKX34eIGVeZsQQ9gO5DeOoTvOnd5JwAj +VWbKgQIDAQABoxAwDjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBh +Pjlxf7FQ3XGXzdypS3KWChLBGP01teCXG3ZYIo3NdVEPugQAlGpG1TrFrOp9nOxv +GbbxKwbpu8tJJDQLVb0CGSQZhbvkpID01pCCfoFcm4nUFe06t6I3WUDbtBglkC6u +gvmoDJ29x4xUhe0H0XAd7qGSvRKXg02enrcBtValHzFuoUhopE8c+rA4J0cS61Wj +RffjGLrXhTwfLB5eOHVegIr9HIRPm++Ft3mJ10Pr1PvFUVuEbw4GMlQT5KfiIC24 ++i0J+I/dARk5zCPA0TkZmvd8U2O/6r4Em68+bh53yLkLeOkOYqdR2x7AY01NFP/K +RH8V5PqYHj1YwrZaZGjQ +-----END CERTIFICATE----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/root/key/cakey.pem.unsecure b/test/unittest/tlssocket/client/ClientCertChain/root/key/cakey.pem.unsecure new file mode 100644 index 0000000000000000000000000000000000000000..be75b87eaa93295795803af3e2f1884ba03c8976 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/root/key/cakey.pem.unsecure @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAnd9o93t4CyHzbyRg784CkCTfxNPz5CZsxxK/KM04LT+rdhFk +zmv2B/01HrnsInIDTevSlEktgkRsclkUq+cMcjI+rfqdUtokjemkENfdNGbffuAO +ZlOL7pEHms4qhSUJdz1fdRyhs6uGOyEo+EOq8At9TfnfhTNKO//kA1klYqHp2pJj +ApO9+d9uxlen0uZ7NxSpumlxDMVPZv5nZlyN1wRN2PMLwAt9SetolCj2MQ8NKgNw +p5f5OJA21Es5S1OlLDJy8kGGMhM8QC0/6GPTjIqDedMg9rzNlz6UkU48dI2a+ine +xKX34eIGVeZsQQ9gO5DeOoTvOnd5JwAjVWbKgQIDAQABAoIBAQCaSI49ZcWAI7LS +iBvP32Vz1wV0RqrP6Zlex3xXdI8U8WcwYHlCnhF350V1fL8/PmrqSK+nyQgXiaTt +7w6bnJX2OBI3VndPU+5rXcy/xSXhozOBu5d2+ukCwWtMJ3U4X2SryieyvMNuYg8x +VAvE6+Ru6NuRS8PcWa6PilkbyJAXnZk9rHdBxnZgcs+RcgZ7Atw6xvqu54G6E+x9 +OEdrD1yR307MZlR09JcCGEEOG01FiCKeLkMJ/1zLpGHe+ClO7euvAPYMSDbbulwC +GmXd6O7tlyi0IEQHonn8xNhs4c44XkwoQtRF2YSI1Ctu5fXOMaLs60LdW2cpNFwP +/sNL513RAoGBANEhNxrmugBe6UL1FqUUBDxbe9KZZdDJKti+nleF1tKeakf4yWCK +0cyKWSBk45orBaohM/UShwEYQG6CnDmE0cn970W9H2hx7A28UoDr8Hr7Zqvu5Dej +uVIBjHEZw50iZLa5l4i1i79GEE1yX/NtUJJlVPLIQ3ipIcCIgO7HkdfFAoGBAMFB +VHNysBpFBiKntMINkZFc115braaQqw2VEgI/69RwCZUUY02TVgeeJ6faWxob0Kbk +LYhlVfKJzjMZaKZRFqwkwDVkf1fbLSRy12J3AFnfNNIAa0mXCJvGsERjS6HXptEo +9wtIf0LqbDUtXpYiC8qBTLhhn3O6NO2dYuu/s1eNAoGAVM0iOj9bJzFVZzhZEWF3 +gj4ajMB1P9+DB1bsgFMeVFO2hy7EAejowAdNsswWWvqdFmrWVcdIhVIfNnCyBsTs +CPt2nhHdfY3MiZlW3z5NSqFM9eUuF73FNRK5r1ciMkKzEkFZyC7N1ycDD1SUwfIO +3P5IHxbD/VagACGaHrlAU30CgYBy72jLlJ0Zso14lOdTNgCqRF4uVzYKxyWEWXEx +d1TJrqx0RoDcxVC4DR6mnJ3sBDju2Owfn60jJ0REbcsohzeFwAG0f4Wg+dB6SfbB +L+c8jBx8/RTR2oqbIur4cVms8nXbFZL/2ekeIg+i/M2xWqRKluXLDvxnNop9+0m2 +zfdajQKBgDES+8CMKgj8dNiy/S44mIhAxgg8vxjfYOYKphiemwG/nUnmFFHzkWPK +xDdGBWTsWi4nvrzErN8NDpoefmPD438n/1pFWD3cpELYLd+h8UK+zOGI4IkMC2BC +oUj1e5SD4AjV2nzm38DpNyMrpnq60uOJwJeaseNAqwcjxO6TEzhX +-----END RSA PRIVATE KEY----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/root/newcerts/01.pem b/test/unittest/tlssocket/client/ClientCertChain/root/newcerts/01.pem new file mode 100644 index 0000000000000000000000000000000000000000..7b1f269c4d4ca4d8d24a2515065720c2a1a19934 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/root/newcerts/01.pem @@ -0,0 +1,73 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 1 (0x1) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=CN, ST=beijing, O=Global Google CA Inc, OU=Root CA, CN=Global Google Root CA + Validity + Not Before: Aug 23 07:33:55 2022 GMT + Not After : Aug 23 07:33:55 2023 GMT + Subject: C=CN, ST=beijing, O=Global Google CA Inc, OU=Root CA, CN=Global Google Root CA + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + RSA Public-Key: (2048 bit) + Modulus: + 00:9d:df:68:f7:7b:78:0b:21:f3:6f:24:60:ef:ce: + 02:90:24:df:c4:d3:f3:e4:26:6c:c7:12:bf:28:cd: + 38:2d:3f:ab:76:11:64:ce:6b:f6:07:fd:35:1e:b9: + ec:22:72:03:4d:eb:d2:94:49:2d:82:44:6c:72:59: + 14:ab:e7:0c:72:32:3e:ad:fa:9d:52:da:24:8d:e9: + a4:10:d7:dd:34:66:df:7e:e0:0e:66:53:8b:ee:91: + 07:9a:ce:2a:85:25:09:77:3d:5f:75:1c:a1:b3:ab: + 86:3b:21:28:f8:43:aa:f0:0b:7d:4d:f9:df:85:33: + 4a:3b:ff:e4:03:59:25:62:a1:e9:da:92:63:02:93: + bd:f9:df:6e:c6:57:a7:d2:e6:7b:37:14:a9:ba:69: + 71:0c:c5:4f:66:fe:67:66:5c:8d:d7:04:4d:d8:f3: + 0b:c0:0b:7d:49:eb:68:94:28:f6:31:0f:0d:2a:03: + 70:a7:97:f9:38:90:36:d4:4b:39:4b:53:a5:2c:32: + 72:f2:41:86:32:13:3c:40:2d:3f:e8:63:d3:8c:8a: + 83:79:d3:20:f6:bc:cd:97:3e:94:91:4e:3c:74:8d: + 9a:fa:29:de:c4:a5:f7:e1:e2:06:55:e6:6c:41:0f: + 60:3b:90:de:3a:84:ef:3a:77:79:27:00:23:55:66: + ca:81 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: + CA:TRUE + Signature Algorithm: sha256WithRSAEncryption + 61:3e:39:71:7f:b1:50:dd:71:97:cd:dc:a9:4b:72:96:0a:12: + c1:18:fd:35:b5:e0:97:1b:76:58:22:8d:cd:75:51:0f:ba:04: + 00:94:6a:46:d5:3a:c5:ac:ea:7d:9c:ec:6f:19:b6:f1:2b:06: + e9:bb:cb:49:24:34:0b:55:bd:02:19:24:19:85:bb:e4:a4:80: + f4:d6:90:82:7e:81:5c:9b:89:d4:15:ed:3a:b7:a2:37:59:40: + db:b4:18:25:90:2e:ae:82:f9:a8:0c:9d:bd:c7:8c:54:85:ed: + 07:d1:70:1d:ee:a1:92:bd:12:97:83:4d:9e:9e:b7:01:b5:56: + a5:1f:31:6e:a1:48:68:a4:4f:1c:fa:b0:38:27:47:12:eb:55: + a3:45:f7:e3:18:ba:d7:85:3c:1f:2c:1e:5e:38:75:5e:80:8a: + fd:1c:84:4f:9b:ef:85:b7:79:89:d7:43:eb:d4:fb:c5:51:5b: + 84:6f:0e:06:32:54:13:e4:a7:e2:20:2d:b8:fa:2d:09:f8:8f: + dd:01:19:39:cc:23:c0:d1:39:19:9a:f7:7c:53:63:bf:ea:be: + 04:9b:af:3e:6e:1e:77:c8:b9:0b:78:e9:0e:62:a7:51:db:1e: + c0:63:4d:4d:14:ff:ca:44:7f:15:e4:fa:98:1e:3d:58:c2:b6: + 5a:64:68:d0 +-----BEGIN CERTIFICATE----- +MIIDazCCAlOgAwIBAgIBATANBgkqhkiG9w0BAQsFADBwMQswCQYDVQQGEwJDTjEQ +MA4GA1UECAwHYmVpamluZzEdMBsGA1UECgwUR2xvYmFsIEdvb2dsZSBDQSBJbmMx +EDAOBgNVBAsMB1Jvb3QgQ0ExHjAcBgNVBAMMFUdsb2JhbCBHb29nbGUgUm9vdCBD +QTAeFw0yMjA4MjMwNzMzNTVaFw0yMzA4MjMwNzMzNTVaMHAxCzAJBgNVBAYTAkNO +MRAwDgYDVQQIDAdiZWlqaW5nMR0wGwYDVQQKDBRHbG9iYWwgR29vZ2xlIENBIElu +YzEQMA4GA1UECwwHUm9vdCBDQTEeMBwGA1UEAwwVR2xvYmFsIEdvb2dsZSBSb290 +IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnd9o93t4CyHzbyRg +784CkCTfxNPz5CZsxxK/KM04LT+rdhFkzmv2B/01HrnsInIDTevSlEktgkRsclkU +q+cMcjI+rfqdUtokjemkENfdNGbffuAOZlOL7pEHms4qhSUJdz1fdRyhs6uGOyEo ++EOq8At9TfnfhTNKO//kA1klYqHp2pJjApO9+d9uxlen0uZ7NxSpumlxDMVPZv5n +ZlyN1wRN2PMLwAt9SetolCj2MQ8NKgNwp5f5OJA21Es5S1OlLDJy8kGGMhM8QC0/ +6GPTjIqDedMg9rzNlz6UkU48dI2a+inexKX34eIGVeZsQQ9gO5DeOoTvOnd5JwAj +VWbKgQIDAQABoxAwDjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBh +Pjlxf7FQ3XGXzdypS3KWChLBGP01teCXG3ZYIo3NdVEPugQAlGpG1TrFrOp9nOxv +GbbxKwbpu8tJJDQLVb0CGSQZhbvkpID01pCCfoFcm4nUFe06t6I3WUDbtBglkC6u +gvmoDJ29x4xUhe0H0XAd7qGSvRKXg02enrcBtValHzFuoUhopE8c+rA4J0cS61Wj +RffjGLrXhTwfLB5eOHVegIr9HIRPm++Ft3mJ10Pr1PvFUVuEbw4GMlQT5KfiIC24 ++i0J+I/dARk5zCPA0TkZmvd8U2O/6r4Em68+bh53yLkLeOkOYqdR2x7AY01NFP/K +RH8V5PqYHj1YwrZaZGjQ +-----END CERTIFICATE----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/root/newcerts/02.pem b/test/unittest/tlssocket/client/ClientCertChain/root/newcerts/02.pem new file mode 100644 index 0000000000000000000000000000000000000000..bd53701bf5d8e1d68c08babe5bd2c3b305538b3d --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/root/newcerts/02.pem @@ -0,0 +1,73 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 2 (0x2) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=CN, ST=beijing, O=Global Google CA Inc, OU=Root CA, CN=Global Google Root CA + Validity + Not Before: Aug 23 07:44:34 2022 GMT + Not After : Aug 23 07:44:34 2023 GMT + Subject: C=CN, ST=Guangdong, O=Global Google CA Inc, OU=Google 2019 CA, CN=Google 2019 CA + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + RSA Public-Key: (2048 bit) + Modulus: + 00:d3:17:8b:68:c9:27:1f:64:16:5a:c7:91:b2:fa: + 9b:b5:7b:81:3b:a8:b3:19:36:da:08:49:94:fb:a3: + e9:10:30:4d:7a:11:8f:96:a4:83:4a:16:0c:b2:d1: + 3c:32:70:2d:42:b8:95:d0:cb:6b:7f:81:69:8e:53: + 9e:61:4f:29:d2:cb:4a:9e:b9:4b:7d:30:de:76:c3: + a0:8d:70:4b:a5:5e:73:88:14:d4:a3:42:63:6d:3a: + 29:49:5b:97:d7:22:9c:cc:3c:12:cd:81:b2:47:91: + f4:b2:32:b9:b1:21:f6:c0:b3:70:c5:07:ee:bd:8c: + e6:f2:6d:42:5f:d9:9e:c7:e4:d6:4b:bc:09:42:da: + 96:f7:31:5c:0d:1c:e9:67:3c:3b:dd:1f:fd:50:72: + 54:9c:74:b6:70:aa:b7:79:a9:fe:9e:7b:87:1e:91: + bb:df:b4:6a:cc:08:63:6d:72:ff:9f:f3:f3:5e:90: + 40:07:de:eb:bf:55:70:80:68:3a:54:9f:60:ac:55: + e7:6f:fd:60:f3:44:4c:6f:64:0a:e6:08:e6:fe:c4: + e5:13:47:2b:33:b4:99:40:2e:40:b1:82:82:f0:1c: + c3:97:e4:81:4c:23:2b:17:a0:fc:6e:be:d9:dd:50: + 7c:b4:1d:2a:56:04:97:ce:a6:94:cf:c3:c1:be:7e: + 45:6b + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: + CA:TRUE + Signature Algorithm: sha256WithRSAEncryption + 8a:f3:81:7d:d1:f4:df:85:ba:74:a8:ee:c2:31:e4:96:e1:64: + 38:aa:7a:7a:c2:47:d8:e5:f9:94:1c:27:62:34:f9:7d:49:d8: + a8:ed:c7:7f:7e:cd:4a:c0:61:ff:94:ab:63:9a:eb:b2:bb:34: + ff:3f:d7:66:40:14:80:fc:fd:72:ad:27:f6:61:8e:12:ef:2d: + 39:b1:94:9b:1d:a7:60:4b:d4:52:80:82:08:5c:83:e5:3a:dd: + 57:a7:c2:35:ed:39:54:5b:4a:c2:68:da:30:a4:66:81:0d:b1: + af:9e:aa:ec:39:19:22:be:df:de:2b:5e:ae:8d:27:e3:78:8e: + b4:36:9a:1b:91:32:d3:d0:05:b3:8d:bf:29:ff:64:f9:7e:7c: + ea:5b:54:d4:3e:fa:c4:9e:ce:12:ee:37:ae:c7:38:85:d6:ba: + f5:3d:dc:a6:9c:83:e1:77:6b:0a:74:e1:19:e4:e3:5a:b6:ff: + bb:09:5b:1d:7d:c1:a0:66:fc:ef:d5:83:20:c1:44:9b:5c:c6: + a2:21:af:df:be:07:ea:a6:b1:6d:5f:fd:3f:eb:ab:87:e9:bd: + b8:3c:8e:f4:dd:52:64:c5:fd:cf:e9:dd:94:7b:99:e7:5c:99: + b7:23:68:2e:ca:77:bc:5c:48:3e:dd:d9:18:f0:82:9c:fd:f3: + 24:6a:18:5f +-----BEGIN CERTIFICATE----- +MIIDbTCCAlWgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBwMQswCQYDVQQGEwJDTjEQ +MA4GA1UECAwHYmVpamluZzEdMBsGA1UECgwUR2xvYmFsIEdvb2dsZSBDQSBJbmMx +EDAOBgNVBAsMB1Jvb3QgQ0ExHjAcBgNVBAMMFUdsb2JhbCBHb29nbGUgUm9vdCBD +QTAeFw0yMjA4MjMwNzQ0MzRaFw0yMzA4MjMwNzQ0MzRaMHIxCzAJBgNVBAYTAkNO +MRIwEAYDVQQIDAlHdWFuZ2RvbmcxHTAbBgNVBAoMFEdsb2JhbCBHb29nbGUgQ0Eg +SW5jMRcwFQYDVQQLDA5Hb29nbGUgMjAxOSBDQTEXMBUGA1UEAwwOR29vZ2xlIDIw +MTkgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDTF4toyScfZBZa +x5Gy+pu1e4E7qLMZNtoISZT7o+kQME16EY+WpINKFgyy0TwycC1CuJXQy2t/gWmO +U55hTynSy0qeuUt9MN52w6CNcEulXnOIFNSjQmNtOilJW5fXIpzMPBLNgbJHkfSy +MrmxIfbAs3DFB+69jObybUJf2Z7H5NZLvAlC2pb3MVwNHOlnPDvdH/1QclScdLZw +qrd5qf6ee4cekbvftGrMCGNtcv+f8/NekEAH3uu/VXCAaDpUn2CsVedv/WDzRExv +ZArmCOb+xOUTRysztJlALkCxgoLwHMOX5IFMIysXoPxuvtndUHy0HSpWBJfOppTP +w8G+fkVrAgMBAAGjEDAOMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEB +AIrzgX3R9N+FunSo7sIx5JbhZDiqenrCR9jl+ZQcJ2I0+X1J2Kjtx39+zUrAYf+U +q2Oa67K7NP8/12ZAFID8/XKtJ/ZhjhLvLTmxlJsdp2BL1FKAgghcg+U63VenwjXt +OVRbSsJo2jCkZoENsa+equw5GSK+394rXq6NJ+N4jrQ2mhuRMtPQBbONvyn/ZPl+ +fOpbVNQ++sSezhLuN67HOIXWuvU93Kacg+F3awp04Rnk41q2/7sJWx19waBm/O/V +gyDBRJtcxqIhr9++B+qmsW1f/T/rq4fpvbg8jvTdUmTF/c/p3ZR7medcmbcjaC7K +d7xcSD7d2Rjwgpz98yRqGF8= +-----END CERTIFICATE----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/root/openssl.cnf b/test/unittest/tlssocket/client/ClientCertChain/root/openssl.cnf new file mode 100644 index 0000000000000000000000000000000000000000..c8cc0917b9199f315b68d3c28dc41accb5751703 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/root/openssl.cnf @@ -0,0 +1,62 @@ +[ ca ] +default_ca = CA_default + +[ CA_default ] +dir = /home/ts/Sol_net/SSL/Cert/ca/root +certs = $dir/certs +crl_dir = $dir/crl +database = $dir/index.txt +new_certs_dir = $dir/newcerts +certificate = $dir/key/cacert.crt +serial = $dir/serial +crlnumber = $dir/crlnumber +crl = $dir/crl.pem +private_key = $dir/key/cakey.pem +RANDFILE = $dir/key/.rand +unique_subject = no + +x509_extensions = usr_cert +copy_extensions = copy + +name_opt = ca_default +cert_opt = ca_default + +default_days = 365 +default_crl_days= 30 +default_md = sha256 +preserve = no +policy = policy_ca + +[ policy_ca ] +countryName = supplied +stateOrProvinceName = supplied +organizationName = supplied +organizationalUnitName = supplied +commonName = supplied +emailAddress = optional + +[ req ] +default_bits = 2048 +default_keyfile = privkey.pem +distinguished_name = req_distinguished_name +attributes = req_attributes +x509_extensions = v3_ca +string_mask = utf8only +utf8 = yes +prompt = no + +[ req_distinguished_name ] +countryName = CN +stateOrProvinceName = beijing +localityName = beijing +organizationName = Global Google CA Inc +organizationalUnitName = Root CA +commonName = Global Google Root CA + +[ usr_cert ] +basicConstraints = CA:TRUE + +[ v3_ca ] +basicConstraints = CA:TRUE + +[ req_attributes ] diff --git a/test/unittest/tlssocket/client/ClientCertChain/root/serial b/test/unittest/tlssocket/client/ClientCertChain/root/serial new file mode 100644 index 0000000000000000000000000000000000000000..75016ea3625245b1aac79cc5586c3f33ce8b7c78 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/root/serial @@ -0,0 +1 @@ +03 diff --git a/test/unittest/tlssocket/client/ClientCertChain/root/serial.old b/test/unittest/tlssocket/client/ClientCertChain/root/serial.old new file mode 100644 index 0000000000000000000000000000000000000000..9e22bcb8e3440869e9e1303f3b7045d1fc8e58c5 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/root/serial.old @@ -0,0 +1 @@ +02 diff --git a/test/unittest/tlssocket/client/ClientCertChain/server/openssl.cnf b/test/unittest/tlssocket/client/ClientCertChain/server/openssl.cnf new file mode 100644 index 0000000000000000000000000000000000000000..7cb048d3c0cd1aa41f493c3b1cc219a368b0c43a --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/server/openssl.cnf @@ -0,0 +1,27 @@ +[ req ] +prompt = no +distinguished_name = server_distinguished_name +req_extensions = req_ext +x509_extensions = v3_req +attributes = req_attributes + +[ server_distinguished_name ] +commonName = server.cn +stateOrProvinceName = changchun +countryName = CN +organizationName = ahahaha Inc +organizationalUnitName = ahaha IT + +[ v3_req ] +basicConstraints = CA:FALSE +keyUsage = nonRepudiation, digitalSignature, keyEncipherment + +[ req_attributes ] + +[ req_ext ] +subjectAltName = @alternate_names + +[ alternate_names ] +DNS.1 = ahaha.cn +DNS.2 = bbs.ahaha.cn +DNS.3 = ahahaha.cn diff --git a/test/unittest/tlssocket/client/ClientCertChain/server/privekey.pem.unsecure b/test/unittest/tlssocket/client/ClientCertChain/server/privekey.pem.unsecure new file mode 100644 index 0000000000000000000000000000000000000000..fdd979106953e10a424de334cb321b2424097449 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/server/privekey.pem.unsecure @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAvV45rCADAHXZBTztvGBbjsUTUEaJ6pH1Fc+VKtPz+Mak20Hb +RXnRRqAdJU7IXDLRZdyGfAOgWFgCi6RRSDcmynzu2g74e+QkU1blXNwPMELcVvNH +SZ1aLeakhgQ6aKjF1YoDoFhvGJdi5roB0WcsX7pDXg61r6QgLmnpA7GH/7FtRLbb +whIV26I5Hyzua0IK+KQJbE+kMIcdtDjXAD9Wp01tGNIJdZaQS4gAv/u/kEgCqxCh +4MHzZ4THKMDu48yaD0fJPnLsA8vcYDDLB/jIzP6xWj2TmxaK5nLPyMJbOKsjqstI +4epNhPyyytIVYKHsPWpPqfjoBnxwfyzc2uyEWQIDAQABAoIBAELq5ChuG4FzI6CV +OlGCH3ihLcUFWEE7GMd/VnAO/DziPWl5qTmw5YI2nHYNlAH4t0RunFuAkI4Hc8bS +5yJE0wFlCqal+asWILwOjfi1jux4BBL53ywlXbOwuFzfa6CGW3qtTcDA32lqPbnY +60GLWwPs91dqjUunDPQ52uzCNJPnDFJ6Vliyu92UuQoWNky3x7ibviJ2lQ+WmaJ9 +bqS04D7ifM6xnEOXCsM7vfEVtvKTW9nzlnf7xkLhvulVVU6crKgOILQjg9xbfsDT +52/NggBW5duzEmppYG48tl52EFMstBB29btQjs5uaDfHKqA73uiPon53NO/Pwt5v +6pyFXIECgYEA4gltcoSTuoOUKNQEeH2aVokBzTyfhjkSM3H8tzLaf6EcqnjMY1+V +B2Pwdq5vXSdwzzdkdpedTndXSvJK+5tQ8eUmm95OS9G9L9+roNvQfZX5oP59b2D3 +nl4flqma+fratw0jtfgzTwA58n8a61HJRJEVg8YHzbk16P6+adwURakCgYEA1nhw +/IYHdvE+/jBwDaJrqmUMxs0n04boj0tSDc4KVIXpWs3CTA9Qn1SI5uFHftOCLggt +rF5DwjaJUwN3QjhxoMAUaZsf+NbQQvoQGYoYVX8xTMXnLtsMJ+4WOGmNuzrGJDL4 +1G1U8Zi40UXO8rTC+foDS2iPZyNcrI10mD4hFzECgYEA1PDktrnHIjLK5Ru3intp +ZpRzqhGuhxhE2UpNNZkm1o3FH6PliMiG8QtpgaUbLLr3P3+DmWWDwGQVTHmtwhKz +0u55zOVFBZB1liA047mxVF5xaQXWzZKgNAWf5KOraEy2tzQdrFRCoe4oqRatGXtX +DM1RY26v81LEQteaMsguIOECgYBzsxfo8vk17mF4SXM5t8RzcP4ahXSVxXLSUuTa +M6wY+wDvjo7h72Uj/zu3qhKi1cGlyZ2yHkxZiog8s2Lz43VRLi4U5q2x1VkWuMZU +sM392Zcj/qOAAIWnSObN2guu1L8tqh3Yo36usyAJLaq9/kwtBPYgCTFLh6UoJUug +EexSEQKBgQCMIxQ5smNNEdwaK6Xg4/MKn5YPH59qlZTLqwd+4/UA7V02VB7rEh4F +rvDkAjJDY0aukbpdpKBiR3ryoKgyuCdFSOJQLPLm6Ac/kvGkDdGa1Q3CPtg7wuSC +NwReWWNScEJmFqAC9HC7zTrFjew5iyRYTE81MBBDOmTMsAuetLMIGw== +-----END RSA PRIVATE KEY----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/server/secondServer.crt b/test/unittest/tlssocket/client/ClientCertChain/server/secondServer.crt new file mode 100644 index 0000000000000000000000000000000000000000..4f8bba606ddbfd154c60558999f056c82ad759d5 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/server/secondServer.crt @@ -0,0 +1,75 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 1 (0x1) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=CN, ST=Guangdong, O=Global Google CA Inc, OU=Google 2019 CA, CN=Google 2019 CA + Validity + Not Before: Aug 23 08:21:11 2022 GMT + Not After : Aug 23 08:21:11 2023 GMT + Subject: C=CN, ST=changchun, O=ahahaha Inc, OU=ahaha IT, CN=server.cn + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + RSA Public-Key: (2048 bit) + Modulus: + 00:bd:5e:39:ac:20:03:00:75:d9:05:3c:ed:bc:60: + 5b:8e:c5:13:50:46:89:ea:91:f5:15:cf:95:2a:d3: + f3:f8:c6:a4:db:41:db:45:79:d1:46:a0:1d:25:4e: + c8:5c:32:d1:65:dc:86:7c:03:a0:58:58:02:8b:a4: + 51:48:37:26:ca:7c:ee:da:0e:f8:7b:e4:24:53:56: + e5:5c:dc:0f:30:42:dc:56:f3:47:49:9d:5a:2d:e6: + a4:86:04:3a:68:a8:c5:d5:8a:03:a0:58:6f:18:97: + 62:e6:ba:01:d1:67:2c:5f:ba:43:5e:0e:b5:af:a4: + 20:2e:69:e9:03:b1:87:ff:b1:6d:44:b6:db:c2:12: + 15:db:a2:39:1f:2c:ee:6b:42:0a:f8:a4:09:6c:4f: + a4:30:87:1d:b4:38:d7:00:3f:56:a7:4d:6d:18:d2: + 09:75:96:90:4b:88:00:bf:fb:bf:90:48:02:ab:10: + a1:e0:c1:f3:67:84:c7:28:c0:ee:e3:cc:9a:0f:47: + c9:3e:72:ec:03:cb:dc:60:30:cb:07:f8:c8:cc:fe: + b1:5a:3d:93:9b:16:8a:e6:72:cf:c8:c2:5b:38:ab: + 23:aa:cb:48:e1:ea:4d:84:fc:b2:ca:d2:15:60:a1: + ec:3d:6a:4f:a9:f8:e8:06:7c:70:7f:2c:dc:da:ec: + 84:59 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: + CA:FALSE + X509v3 Subject Alternative Name: + DNS:ahaha.cn, DNS:bbs.ahaha.cn, DNS:ahahaha.cn + Signature Algorithm: sha256WithRSAEncryption + b2:4a:50:b0:6e:75:34:c2:a2:94:1d:15:45:23:b0:d5:20:4c: + d3:98:bd:30:bf:52:b7:98:b3:fd:d8:41:7f:7e:98:aa:6c:0a: + bf:91:c9:49:a8:02:21:ce:d4:b7:c4:d9:57:0d:55:3f:43:d7: + ff:89:a9:64:52:57:a6:f9:89:e1:2c:95:e6:13:ef:dc:6b:c9: + be:fa:e1:cf:c7:c4:3a:b4:c1:9f:6a:e5:0d:83:1e:86:38:4f: + 9b:52:f0:e7:79:a0:6d:11:5c:c6:f3:38:00:6a:9a:c2:db:bd: + 5a:68:9e:05:4d:fd:cc:60:cf:8d:19:e9:f7:37:10:34:6e:b6: + 38:1c:72:ff:ea:77:c8:82:92:3d:1a:f4:3d:f8:86:aa:25:26: + 2a:43:4c:8c:a1:eb:af:5b:a5:36:08:1a:6b:b4:d4:07:5e:04: + 4f:43:27:99:e8:b6:d4:48:d3:33:4d:e2:0a:b5:ca:08:4a:e3: + 3b:86:2c:57:a2:99:8f:83:13:9c:7e:88:af:79:50:49:80:f1: + 68:5b:b6:fa:c5:1f:13:fa:57:b4:e9:44:89:3f:8f:f8:30:21: + 79:10:0f:5c:53:1e:60:84:77:8e:4f:e5:c9:4a:6b:e1:77:af: + e6:73:e0:df:9c:e9:6e:86:59:1f:64:8e:f5:5b:ce:36:23:f8: + b7:89:ca:15 +-----BEGIN CERTIFICATE----- +MIIDhzCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQsFADByMQswCQYDVQQGEwJDTjES +MBAGA1UECAwJR3Vhbmdkb25nMR0wGwYDVQQKDBRHbG9iYWwgR29vZ2xlIENBIElu +YzEXMBUGA1UECwwOR29vZ2xlIDIwMTkgQ0ExFzAVBgNVBAMMDkdvb2dsZSAyMDE5 +IENBMB4XDTIyMDgyMzA4MjExMVoXDTIzMDgyMzA4MjExMVowXjELMAkGA1UEBhMC +Q04xEjAQBgNVBAgMCWNoYW5nY2h1bjEUMBIGA1UECgwLYWhhaGFoYSBJbmMxETAP +BgNVBAsMCGFoYWhhIElUMRIwEAYDVQQDDAlzZXJ2ZXIuY24wggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQC9XjmsIAMAddkFPO28YFuOxRNQRonqkfUVz5Uq +0/P4xqTbQdtFedFGoB0lTshcMtFl3IZ8A6BYWAKLpFFINybKfO7aDvh75CRTVuVc +3A8wQtxW80dJnVot5qSGBDpoqMXVigOgWG8Yl2LmugHRZyxfukNeDrWvpCAuaekD +sYf/sW1EttvCEhXbojkfLO5rQgr4pAlsT6Qwhx20ONcAP1anTW0Y0gl1lpBLiAC/ ++7+QSAKrEKHgwfNnhMcowO7jzJoPR8k+cuwDy9xgMMsH+MjM/rFaPZObFormcs/I +wls4qyOqy0jh6k2E/LLK0hVgoew9ak+p+OgGfHB/LNza7IRZAgMBAAGjPDA6MAkG +A1UdEwQCMAAwLQYDVR0RBCYwJIIIYWhhaGEuY26CDGJicy5haGFoYS5jboIKYWhh +aGFoYS5jbjANBgkqhkiG9w0BAQsFAAOCAQEAskpQsG51NMKilB0VRSOw1SBM05i9 +ML9St5iz/dhBf36YqmwKv5HJSagCIc7Ut8TZVw1VP0PX/4mpZFJXpvmJ4SyV5hPv +3GvJvvrhz8fEOrTBn2rlDYMehjhPm1Lw53mgbRFcxvM4AGqawtu9WmieBU39zGDP +jRnp9zcQNG62OBxy/+p3yIKSPRr0PfiGqiUmKkNMjKHrr1ulNggaa7TUB14ET0Mn +mei21EjTM03iCrXKCErjO4YsV6KZj4MTnH6Ir3lQSYDxaFu2+sUfE/pXtOlEiT+P ++DAheRAPXFMeYIR3jk/lyUpr4Xev5nPg35zpboZZH2SO9VvONiP4t4nKFQ== +-----END CERTIFICATE----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/server/secondServer.csr b/test/unittest/tlssocket/client/ClientCertChain/server/secondServer.csr new file mode 100644 index 0000000000000000000000000000000000000000..bd91165e56a711ad1960d58fe6a2fa7242650c46 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/server/secondServer.csr @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIC4zCCAcsCAQAwXjESMBAGA1UEAwwJc2VydmVyLmNuMRIwEAYDVQQIDAljaGFu +Z2NodW4xCzAJBgNVBAYTAkNOMRQwEgYDVQQKDAthaGFoYWhhIEluYzERMA8GA1UE +CwwIYWhhaGEgSVQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9Xjms +IAMAddkFPO28YFuOxRNQRonqkfUVz5Uq0/P4xqTbQdtFedFGoB0lTshcMtFl3IZ8 +A6BYWAKLpFFINybKfO7aDvh75CRTVuVc3A8wQtxW80dJnVot5qSGBDpoqMXVigOg +WG8Yl2LmugHRZyxfukNeDrWvpCAuaekDsYf/sW1EttvCEhXbojkfLO5rQgr4pAls +T6Qwhx20ONcAP1anTW0Y0gl1lpBLiAC/+7+QSAKrEKHgwfNnhMcowO7jzJoPR8k+ +cuwDy9xgMMsH+MjM/rFaPZObFormcs/Iwls4qyOqy0jh6k2E/LLK0hVgoew9ak+p ++OgGfHB/LNza7IRZAgMBAAGgQDA+BgkqhkiG9w0BCQ4xMTAvMC0GA1UdEQQmMCSC +CGFoYWhhLmNuggxiYnMuYWhhaGEuY26CCmFoYWhhaGEuY24wDQYJKoZIhvcNAQEL +BQADggEBACc2KPRz24/76x2BUfZZ0237T+obyvYkFBl+wvcHZTd3jEKOzcIuqynS +yo8nTNwi5SLLSVNAc3iCBgccOU9yCVh9EdKMoW8Jt1HseTxyfllDnA4ihrTZfNUm +hAA4a0+4IUnIKwGv2N+tfL8QPNl670/ShqZdAWWbygN6kSVmtc/6tR/RZuMLnKPY +McTsORKzm8OAKtO3EUAoTapFEtleaz4JR1T1e0lb9W/vVqwMKxOnJQwJULdgytFh +4bq/OIdglSZtz+w4lhqkBetEWb8PUYHGPYnTdbwzEsa7cDKrWxaE6WFSeTwjmmEh +BYRLtG2cck3JlYwBh/l7IirBSgPalMU= +-----END CERTIFICATE REQUEST----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/serverSecond/openssl.cnf b/test/unittest/tlssocket/client/ClientCertChain/serverSecond/openssl.cnf new file mode 100644 index 0000000000000000000000000000000000000000..cc4eb244c50f852914d178f95f9510607e44dd66 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/serverSecond/openssl.cnf @@ -0,0 +1,27 @@ +[ req ] +prompt = no +distinguished_name = server_distinguished_name +req_extensions = req_ext +x509_extensions = v3_req +attributes = req_attributes + +[ server_distinguished_name ] +commonName = second.cn +stateOrProvinceName = changchun +countryName = CN +organizationName = second Inc +organizationalUnitName = Second IT + +[ v3_req ] +basicConstraints = CA:FALSE +keyUsage = nonRepudiation, digitalSignature, keyEncipherment + +[ req_attributes ] + +[ req_ext ] +subjectAltName = @alternate_names + +[ alternate_names ] +DNS.1 = second.cn +DNS.2 = bbs.second.cn +DNS.3 = second.cn diff --git a/test/unittest/tlssocket/client/ClientCertChain/serverSecond/privekey.pem.unsecure b/test/unittest/tlssocket/client/ClientCertChain/serverSecond/privekey.pem.unsecure new file mode 100644 index 0000000000000000000000000000000000000000..f2a24d3f8f8f72197392b7e5a160940295486c9f --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/serverSecond/privekey.pem.unsecure @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAveY7cQFL45DkuiOWzYsdJ62wRPESAFAKRqNBDRrEpPsSzUWf +B4aT5v8pzl7aVbjIMKVhw/yewWJ9HTFpMBhFwHnRDi5ukGG/pMnzRTlTf8RMn0hE +XIxbXowDBJ7zeufcniVCX88PcQiluAWMIOLoGPB/YFNe9jwxZAvzvAFg1ZE+cHzu +U/POSYHx6E9BeHLl2RB9wk4KKeuTlopYQChbQGgbU55DJ07pQ773AavhRyyS7vHz +cWBMsAEo0Gy/zxxs5jZnkRWmZ/5bM6DOT6WmkcXiFYpimLGTO+ML9y/kIVyLYgk4 +G3ghh6tRhRPXaIAS+DHV3d/X9/gz6CDv6ERYoQIDAQABAoIBADW92WaiukpdsA1p +kvz6eLbI9dCc9L436KCTBQ7jW3FhSLHlGRt1H5hI8BjiSSHnWGhD9YYUkQ0jhUrk +t+MPi3XsQ5ii1VFxCF5ndLxLe/D1qcWOGyKh6h24vAXrwfYvdgUfgEhC/hi8HMIW +d9C6xnqAXVvyXDaNVGD+7Oxw62mk4zv1xcm5wNvKVqbmYSvp4zG3WercTaykSIvV ++8zf+jDxEhNFnJHo6X9jGMVPLNsQGmX1kZT+Z8o1AqXFsE8bcCOEJ28IADUgp0fi +UB+p82QSeqsWxBqgonYQxF7Hd/k+hhKWxHNiIqJbMqaePwVEdpZ0sodX1SgophTV +RYAqtEECgYEA5tm1QJUorKtBFPzA4/TzrY2qlvW+CTGc5IojXR1PsIn51Y1WbBC6 +Qs/6ciqyyuCiHT+xZBwRar47qWf6ya0NiGYe+2crwvSFNoTyxZ01xIGqmc0Q5KXe ++9qUMhTatt8gDOGqUPouauuvVmXn9Bf6TfmUJG6XiKgV/Cmub/2lQhkCgYEA0pZr +yIeTLj1+Q/DUDfNP+LXrmaqQMIyCH8YnFEXd91jC88uOv0j3yjYIkHvR+2KfFqbR +s85i3zsKEmWORRLrhse5TVbuqTOcFhXcc9yvsUiaZUnncTQAvx9XZx7ODRMbVeRj +RxzHt/SICZ4Bq5XuFDzHnMHxOKJbn6UA/rBba8kCgYBOxqQPcdb7dUU0QDwijghJ +hTpdYWaEBKYhZvJCaCo1eCAFO8HuBpdJDWfNZby1dopbqMyD+QAIiPobCRyPjbo8 +fXy9FavdT0vWGvAtd0RN1mG9Mjk9jUzWbPR9UpiAJwvs2WUhVP5aBitDNGs+5J/J +1A01kXesbo9yCVc5aDjooQKBgQC2cHy2QMZAtCOUpqp/34Az/x86hKrgdIozDs9C +X/kZ1bsnzP1BOOz7MW6gBbV4LQuYazOXq8C6loJ2R6dGrkp//L3Lg/nFeqHJ/Gx9 +r/5B/51LDQjGaQAQlA17mBN4/kmbUv6zV/qqot3MPyhBR+X3gGSKqPbbUsU//Ipt +G8pICQKBgQC4IdeiLIVNEas7o/g21TohvrogzjmXqgL5chgQPnnbGRexn5HMddGo +xDrcIdOnTrDs/wFT2Lmurcl/6ZyDJfFXKP9U1FEdpeeai1tEDUDaj0hL21KNwq67 +GUC0fxWr2k5HYgHBqAtXgQo6TLqtrfpDaOIsklovAYtNU88SvEelQg== +-----END RSA PRIVATE KEY----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/serverSecond/second.crt b/test/unittest/tlssocket/client/ClientCertChain/serverSecond/second.crt new file mode 100644 index 0000000000000000000000000000000000000000..75034d5640f4665e0f282897442355f8be8ce3ac --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/serverSecond/second.crt @@ -0,0 +1,75 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 2 (0x2) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=CN, ST=Guangdong, O=Global Google CA Inc, OU=Google 2019 CA, CN=Google 2019 CA + Validity + Not Before: Aug 25 11:09:48 2022 GMT + Not After : Aug 25 11:09:48 2023 GMT + Subject: C=CN, ST=changchun, O=second Inc, OU=Second IT, CN=second.cn + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + RSA Public-Key: (2048 bit) + Modulus: + 00:bd:e6:3b:71:01:4b:e3:90:e4:ba:23:96:cd:8b: + 1d:27:ad:b0:44:f1:12:00:50:0a:46:a3:41:0d:1a: + c4:a4:fb:12:cd:45:9f:07:86:93:e6:ff:29:ce:5e: + da:55:b8:c8:30:a5:61:c3:fc:9e:c1:62:7d:1d:31: + 69:30:18:45:c0:79:d1:0e:2e:6e:90:61:bf:a4:c9: + f3:45:39:53:7f:c4:4c:9f:48:44:5c:8c:5b:5e:8c: + 03:04:9e:f3:7a:e7:dc:9e:25:42:5f:cf:0f:71:08: + a5:b8:05:8c:20:e2:e8:18:f0:7f:60:53:5e:f6:3c: + 31:64:0b:f3:bc:01:60:d5:91:3e:70:7c:ee:53:f3: + ce:49:81:f1:e8:4f:41:78:72:e5:d9:10:7d:c2:4e: + 0a:29:eb:93:96:8a:58:40:28:5b:40:68:1b:53:9e: + 43:27:4e:e9:43:be:f7:01:ab:e1:47:2c:92:ee:f1: + f3:71:60:4c:b0:01:28:d0:6c:bf:cf:1c:6c:e6:36: + 67:91:15:a6:67:fe:5b:33:a0:ce:4f:a5:a6:91:c5: + e2:15:8a:62:98:b1:93:3b:e3:0b:f7:2f:e4:21:5c: + 8b:62:09:38:1b:78:21:87:ab:51:85:13:d7:68:80: + 12:f8:31:d5:dd:df:d7:f7:f8:33:e8:20:ef:e8:44: + 58:a1 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: + CA:FALSE + X509v3 Subject Alternative Name: + DNS:second.cn, DNS:bbs.second.cn, DNS:second.cn + Signature Algorithm: sha256WithRSAEncryption + bd:08:98:88:91:bd:4b:32:4e:bc:f9:7f:45:d5:6e:fe:e9:08: + aa:97:ea:97:41:63:cf:29:ed:67:d9:56:cc:28:06:9e:0b:fe: + 98:3f:83:49:bf:16:89:be:61:c4:4e:21:c3:3f:a0:e7:9a:00: + 6c:a9:37:d9:35:ad:ce:2f:a1:14:e7:a0:db:9d:d2:2c:cb:24: + ac:1a:e8:a7:52:40:ce:e2:dd:ee:b3:ee:06:db:b6:bd:2a:65: + 47:5c:28:f9:95:fb:fe:bf:60:2e:9e:e1:f5:6d:90:01:ce:66: + 28:c6:ee:ed:9c:06:1d:b6:e8:b5:4b:80:8b:e1:5f:36:64:58: + 7b:4b:ef:b4:8a:55:aa:ab:4b:77:ab:a2:3b:83:d3:3a:68:1a: + 1c:75:ab:c9:94:ac:32:9f:59:17:6a:bc:58:a5:27:82:7f:8b: + 15:33:18:30:76:85:39:87:24:99:c1:16:98:4a:3f:ac:27:2f: + cf:27:33:2d:5d:30:0d:eb:10:fa:46:bd:ab:c8:ea:2c:a9:1c: + d7:89:5f:cf:b2:68:95:cd:5d:4d:15:90:bf:f8:f5:db:0c:f4: + 4f:be:6f:bc:a3:95:ce:89:45:e9:06:49:bd:26:ce:44:78:48: + cc:c8:f7:d0:f1:e9:21:6f:ce:0d:79:78:a1:8c:58:08:7a:4b: + 27:72:e5:3f +-----BEGIN CERTIFICATE----- +MIIDiDCCAnCgAwIBAgIBAjANBgkqhkiG9w0BAQsFADByMQswCQYDVQQGEwJDTjES +MBAGA1UECAwJR3Vhbmdkb25nMR0wGwYDVQQKDBRHbG9iYWwgR29vZ2xlIENBIElu +YzEXMBUGA1UECwwOR29vZ2xlIDIwMTkgQ0ExFzAVBgNVBAMMDkdvb2dsZSAyMDE5 +IENBMB4XDTIyMDgyNTExMDk0OFoXDTIzMDgyNTExMDk0OFowXjELMAkGA1UEBhMC +Q04xEjAQBgNVBAgMCWNoYW5nY2h1bjETMBEGA1UECgwKc2Vjb25kIEluYzESMBAG +A1UECwwJU2Vjb25kIElUMRIwEAYDVQQDDAlzZWNvbmQuY24wggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQC95jtxAUvjkOS6I5bNix0nrbBE8RIAUApGo0EN +GsSk+xLNRZ8HhpPm/ynOXtpVuMgwpWHD/J7BYn0dMWkwGEXAedEOLm6QYb+kyfNF +OVN/xEyfSERcjFtejAMEnvN659yeJUJfzw9xCKW4BYwg4ugY8H9gU172PDFkC/O8 +AWDVkT5wfO5T885JgfHoT0F4cuXZEH3CTgop65OWilhAKFtAaBtTnkMnTulDvvcB +q+FHLJLu8fNxYEywASjQbL/PHGzmNmeRFaZn/lszoM5PpaaRxeIVimKYsZM74wv3 +L+QhXItiCTgbeCGHq1GFE9dogBL4MdXd39f3+DPoIO/oRFihAgMBAAGjPTA7MAkG +A1UdEwQCMAAwLgYDVR0RBCcwJYIJc2Vjb25kLmNugg1iYnMuc2Vjb25kLmNugglz +ZWNvbmQuY24wDQYJKoZIhvcNAQELBQADggEBAL0ImIiRvUsyTrz5f0XVbv7pCKqX +6pdBY88p7WfZVswoBp4L/pg/g0m/Fom+YcROIcM/oOeaAGypN9k1rc4voRTnoNud +0izLJKwa6KdSQM7i3e6z7gbbtr0qZUdcKPmV+/6/YC6e4fVtkAHOZijG7u2cBh22 +6LVLgIvhXzZkWHtL77SKVaqrS3erojuD0zpoGhx1q8mUrDKfWRdqvFilJ4J/ixUz +GDB2hTmHJJnBFphKP6wnL88nMy1dMA3rEPpGvavI6iypHNeJX8+yaJXNXU0VkL/4 +9dsM9E++b7yjlc6JRekGSb0mzkR4SMzI99Dx6SFvzg15eKGMWAh6Sydy5T8= +-----END CERTIFICATE----- diff --git a/test/unittest/tlssocket/client/ClientCertChain/serverSecond/second.csr b/test/unittest/tlssocket/client/ClientCertChain/serverSecond/second.csr new file mode 100644 index 0000000000000000000000000000000000000000..af38a6892a751251dd89d67f979eb4ea031a3b58 --- /dev/null +++ b/test/unittest/tlssocket/client/ClientCertChain/serverSecond/second.csr @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIC5DCCAcwCAQAwXjESMBAGA1UEAwwJc2Vjb25kLmNuMRIwEAYDVQQIDAljaGFu +Z2NodW4xCzAJBgNVBAYTAkNOMRMwEQYDVQQKDApzZWNvbmQgSW5jMRIwEAYDVQQL +DAlTZWNvbmQgSVQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC95jtx +AUvjkOS6I5bNix0nrbBE8RIAUApGo0ENGsSk+xLNRZ8HhpPm/ynOXtpVuMgwpWHD +/J7BYn0dMWkwGEXAedEOLm6QYb+kyfNFOVN/xEyfSERcjFtejAMEnvN659yeJUJf +zw9xCKW4BYwg4ugY8H9gU172PDFkC/O8AWDVkT5wfO5T885JgfHoT0F4cuXZEH3C +Tgop65OWilhAKFtAaBtTnkMnTulDvvcBq+FHLJLu8fNxYEywASjQbL/PHGzmNmeR +FaZn/lszoM5PpaaRxeIVimKYsZM74wv3L+QhXItiCTgbeCGHq1GFE9dogBL4MdXd +39f3+DPoIO/oRFihAgMBAAGgQTA/BgkqhkiG9w0BCQ4xMjAwMC4GA1UdEQQnMCWC +CXNlY29uZC5jboINYmJzLnNlY29uZC5jboIJc2Vjb25kLmNuMA0GCSqGSIb3DQEB +CwUAA4IBAQAYJLxoUcyxLvqai37VlQqL63iuicTZ2PIWRJi31mn2pUzWEEaU7bz+ +4VuX/9sBgqWCR+2b3PXhpEENqaw1/wN4XoY7x5Pv5aIXmyD9LrXubnZlpgtN+L/d +JeBC5046m+2SCDE605q5dv6NhoxGg1KzyrYeDNBkHYxZfFI/UhiNICeyw4720JkN +iukooXovaRpzuRST78/pGBSxQycoJUWBDeA+nOFfU8M7TXeUkMyMA99DBKin1on2 +ZHYadASFNwQwEMZviV27rGRgDwKUjbfp2Ea9qLlCzvHFBYWtEDVNphTw79Z98bSi +uCutnkdY9wBaP+2+tjL9LF32nbk9bDHo +-----END CERTIFICATE REQUEST----- diff --git a/test/unittest/tlssocket/client/TlsSocketCertChainTest.cpp b/test/unittest/tlssocket/client/TlsSocketCertChainTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c067cb94bbf0e735ba0ffcba5850960c09b7d545 --- /dev/null +++ b/test/unittest/tlssocket/client/TlsSocketCertChainTest.cpp @@ -0,0 +1,391 @@ +/* + * Copyright (c) 2022 Huawei Device 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 "gtest/gtest.h" +#include "netstack_log.h" +#include "net_address.h" +#include "socket_state_base.h" +#include "tls.h" +#include "tls_configuration.h" +#include "tls_certificate.h" +#include "tls_key.h" +#include "tls_socket_internal.h" +#include "tls_socket.h" + +namespace OHOS { +namespace NetStack { + +static constexpr const char *IP_ADDRESS = "10.14.0.7"; +std::string PRIVATE_KEY_PEM_CHAIN = "ClientCertChain/privekey.pem.unsecure"; +std::string CA_PATH_CHAIN = "ClientCertChain/cacert.crt"; +std::string MID_CA_PATH_CHAIN = "ClientCertChain/caMidcert.crt"; +std::string CLIENT_CRT_CHAIN = "ClientCertChain/secondServer.crt"; + +class TlsSocketTest : public testing::Test { +public: + static void SetUpTestCase() {} + + static void TearDownTestCase() {} + + virtual void SetUp() {} + + virtual void TearDown() {} +}; + +std::string ChangeToFileChain(std::string &fileName) +{ + std::ifstream file; + file.open(fileName); + std::stringstream ss; + ss << file.rdbuf(); + std::string infos = ss.str(); + file.close(); + return infos; +} + +void TlsSocketConnect(TLSConnectOptions &options) +{ + std::vector caVec= {ChangeToFileChain(CA_PATH_CHAIN), ChangeToFileChain(MID_CA_PATH_CHAIN)}; + + std::vector protocolVec = {"TlsV1_2"}; + std::string signatureAlgorithmVec = {"RSA-SHA256"}; + std::vector alpnProtocols = {"spdy/1", "http/1.1"}; + + TLSSecureOptions secureOption; + NetAddress address; + + address.SetAddress(IP_ADDRESS); + address.SetPort(7838); + address.SetFamilyBySaFamily(AF_INET); + + secureOption.SetKey(ChangeToFileChain(PRIVATE_KEY_PEM_CHAIN)); + secureOption.SetCaChain(caVec); + secureOption.SetCert(ChangeToFileChain(CLIENT_CRT_CHAIN)); + secureOption.SetCipherSuite("AES256-SHA256"); + secureOption.SetProtocolChain(protocolVec); + secureOption.SetUseRemoteCipherPrefer(true); + secureOption.SetSignatureAlgorithms(signatureAlgorithmVec); + secureOption.SetPassWd("123456"); + + options.SetNetAddress(address); + options.SetTlsSecureOptions(secureOption); + options.SetAlpnProtocols(alpnProtocols); +} + +HWTEST_F(TlsSocketTest, tlsSocketCertChainConnect, testing::ext::TestSize.Level2) +{ + TLSConnectOptions options; + TLSSocket server; + + TlsSocketConnect(options); + + server.Connect(options, [](bool ok){ EXPECT_TRUE(ok); }); + const std::string data = "how do you do?"; + TCPSendOptions tcpSendOptions; + tcpSendOptions.SetData(data); + server.Send(tcpSendOptions, [](bool ok) {if (ok) {EXPECT_TRUE(ok);}}); + sleep(2); + (void)server.Close([](bool ok) {if (ok) {;}}); +} + +HWTEST_F(TlsSocketTest, tlsSocketCertChainConnectOther, testing::ext::TestSize.Level2) +{ + TLSConnectOptions options; + TLSSocket server; + + TlsSocketConnect(options); + + server.Connect(options, [](bool ok){ EXPECT_TRUE(ok); }); + std::vector cipherSuite; + server.GetCipherSuite([&cipherSuite](bool ok, const std::vector &suite) {if (ok) {cipherSuite = suite;}}); + const std::string data = "how do you do?"; + TCPSendOptions tcpSendOptions; + tcpSendOptions.SetData(data); + server.Send(tcpSendOptions, [](bool ok) {if (ok) {EXPECT_TRUE(ok);}}); + sleep(2); + (void)server.Close([](bool ok) {if (ok) {;}}); +} + +HWTEST_F(TlsSocketTest, tlsConnetOptionsSend, testing::ext::TestSize.Level2) +{ + TLSConnectOptions options; + TLSSocket server; + + TlsSocketConnect(options); + + server.Connect(options, [](bool ok){ EXPECT_TRUE(ok); }); + std::vector cipherSuite; + server.GetCipherSuite([&cipherSuite](bool ok, const std::vector &suite) {if (ok) {cipherSuite = suite;}}); + const std::string data = "how do you do? This is UT test tlsConnetOptionsSend"; + TCPSendOptions tcpSendOptions; + tcpSendOptions.SetData(data); + server.Send(tcpSendOptions, [](bool ok) {if (ok) {EXPECT_TRUE(ok);}}); + + sleep(2); + + (void)server.Close([](bool ok) {if (ok) {;}}); +} + +HWTEST_F(TlsSocketTest, tlsOptionGet, testing::ext::TestSize.Level2) +{ + TLSConnectOptions options; + TLSSecureOptions secureOption; + NetAddress address; + TLSSocket server; + std::vector cipherSuite; + std::vector caVec = {ChangeToFileChain(CA_PATH_CHAIN), ChangeToFileChain(MID_CA_PATH_CHAIN)}; + std::vector protocolVec = {"TlsV1_2"}; + std::string signatureAlgorithmVec = {"RSA-SHA256"}; + std::vector alpnProtocols = {"spdy/1", "http/1.1"}; + + address.SetAddress("10.14.0.91"); + address.SetPort(7838); + address.SetFamilyBySaFamily(AF_INET); + secureOption.SetKey(ChangeToFileChain(PRIVATE_KEY_PEM_CHAIN)); + (void)secureOption.GetKey(); + (void)options.GetTlsSecureOptions().GetKey(); + + secureOption.SetCaChain(caVec); + secureOption.SetCert(ChangeToFileChain(CLIENT_CRT_CHAIN)); + secureOption.SetCipherSuite("AES256-SHA256"); + secureOption.SetProtocolChain(protocolVec); + secureOption.SetUseRemoteCipherPrefer(true); + secureOption.SetSignatureAlgorithms(signatureAlgorithmVec); + secureOption.SetPassWd("123456"); + options.SetNetAddress(address); + options.SetTlsSecureOptions(secureOption); + options.SetAlpnProtocols(alpnProtocols); + + for (int i = 0; i < caVec.size(); i++) { + std::cout << "setcaVec: "<< caVec[i] << std::endl; + } + std::cout << "setCert: " << CLIENT_CRT_CHAIN << std::endl; + std::cout << "setKey: " << PRIVATE_KEY_PEM_CHAIN << std::endl; + std::cout << "setCipherSuite: " << "AES256-SHA256" << std::endl; + for (int i = 0; i < caVec.size(); i++) { + std::cout << "setProtocolChain: "<< protocolVec[i].c_str() << std::endl; + } + std::cout << "setUseRemoteCipherPrefer: " << "true" << std::endl; + std::cout << "setSignatureAlgorithms: " << signatureAlgorithmVec << std::endl; + std::cout << "SetPassWd: " << "123456" << std::endl; + + TLSSecureOptions tLSSecureOptions = options.GetTlsSecureOptions(); + std::vector testCaChain = tLSSecureOptions.GetCaChain(); + std::string getCert = tLSSecureOptions.GetCert(); + std::string getKey = tLSSecureOptions.GetKey(); + std::string getPasswd = tLSSecureOptions.GetPasswd(); + std::vector getProtocolChain = tLSSecureOptions.GetProtocolChain(); + bool getIsUseRemoteCipherPrefer = tLSSecureOptions.UseRemoteCipherPrefer(); + std::string getSignatureAlgorithms = tLSSecureOptions.GetSignatureAlgorithms(); + + for (int i = 0; i < caVec.size(); i++) { + std::cout << "getcaVec: "<< testCaChain[i] << std::endl; + } + std::cout << "getsetCert: " << getCert << std::endl; + std::cout << "getsetKey: " << getKey << std::endl; + std::cout << "getCipherSuite: " << "AES256-SHA256" << std::endl; + for (int i = 0; i < caVec.size(); i++) { + std::cout << "getProtocolChain: "<< getProtocolChain[i] << std::endl; + } + std::cout << "getUseRemoteCipherPrefer: " << getIsUseRemoteCipherPrefer << std::endl; + std::cout << "getSignatureAlgorithms: " << getSignatureAlgorithms << std::endl; + std::cout << "getSetPassWd: " << getPasswd << std::endl; + sleep(1); +} + +HWTEST_F(TlsSocketTest, tlsSocketGcertInternal, testing::ext::TestSize.Level2) +{ + std::cout << "TlsSocketTest, tlsSocketGetState begin " << std::endl; + TLSSocket server; + TLSConnectOptions options; + TCPSendOptions tcpSendOptions; + const std::string data = "how do you do? This is UT test tlsSocketGcertInternal"; + + TlsSocketConnect(options); + + server.Connect(options, [] (bool ok){ EXPECT_TRUE(ok); }); + + tcpSendOptions.SetData(data); + + server.Send(tcpSendOptions, [] (bool ok) { EXPECT_TRUE(ok); }); + + bool IsGetCertificate; + std::string certInternal; + server.GetCertificate([&IsGetCertificate, &certInternal] (bool ok, const std::string &cert) { + IsGetCertificate = ok; + certInternal = cert; + }); + std::cout << "GetCertificate IsGetCertificate: " << IsGetCertificate < algorithmsInternal; + server.GetSignatureAlgorithms([&IsGetSignatureAlgorithms, &algorithmsInternal] (bool ok, const std::vector &algorithms) { + IsGetSignatureAlgorithms = ok; + algorithmsInternal = algorithms; + }); + std::cout << "GetSignatureAlgorithms IsGetSignatureAlgorithms: " << IsGetSignatureAlgorithms < +#include +#include +#include +#include +#include + +#include "gtest/gtest.h" +#include "netstack_log.h" +#include "net_address.h" +#include "socket_state_base.h" +#include "tls.h" +#include "tls_configuration.h" +#include "tls_certificate.h" +#include "tls_key.h" +#include "tls_socket_internal.h" +#include "tls_socket.h" + +namespace OHOS { +namespace NetStack { +static constexpr const char *IP_ADDRESS = "10.14.0.7"; +std::string PRIVATE_KEY_PEM = "ClientCert/client_rsa_private.pem.unsecure"; +std::string CA_DER = "ClientCert/ca.crt"; +std::string CLIENT_CRT = "ClientCert/client.crt"; + +// static constexpr const char *PRIVATE_KEY_PEM = "ClientCertChain/privekey.pem.unsecure"; +// static constexpr const char *CA_PATH = "ClientCertChain/cacert.crt"; +// static constexpr const char *MID_CA_PATH = "ClientCertChain/caMidcert.crt"; +// static constexpr const char *CLIENT_CRT = "ClientCertChain/secondServer.crt"; + +class TlsSocketTest : public testing::Test { +public: + static void SetUpTestCase() {} + + static void TearDownTestCase() {} + + virtual void SetUp() {} + + virtual void TearDown() {} +}; + +std::string ChangeToFile(std::string &fileName) +{ + std::ifstream file; + file.open(fileName); + std::stringstream ss; + ss << file.rdbuf(); + std::string infos = ss.str(); + file.close(); + return infos; +} + +void TlsSocketConnect(TLSConnectOptions &options) +{ + std::vector caVec= {ChangeToFile(CA_DER)}; + + std::vector protocolVec = {"TlsV1_2"}; + std::string signatureAlgorithmVec = {"RSA-SHA256"}; + std::vector alpnProtocols = {"spdy/1", "http/1.1"}; + + TLSSecureOptions secureOption; + NetAddress address; + + address.SetAddress(IP_ADDRESS); + address.SetPort(7838); + address.SetFamilyBySaFamily(AF_INET); + + secureOption.SetKey(ChangeToFile(PRIVATE_KEY_PEM)); + secureOption.SetCaChain(caVec); + secureOption.SetCert(ChangeToFile(CLIENT_CRT)); + secureOption.SetCipherSuite("AES256-SHA256"); + secureOption.SetProtocolChain(protocolVec); + secureOption.SetUseRemoteCipherPrefer(true); + secureOption.SetSignatureAlgorithms(signatureAlgorithmVec); + secureOption.SetPassWd("123456"); + + options.SetNetAddress(address); + options.SetTlsSecureOptions(secureOption); + options.SetAlpnProtocols(alpnProtocols); +} + +HWTEST_F(TlsSocketTest, tlsConnetOptionsSend, testing::ext::TestSize.Level2) +{ + TLSConnectOptions options; + TLSSocket server; + + TlsSocketConnect(options); + server.Connect(options, [](bool ok){ EXPECT_TRUE(ok); }); + std::vector cipherSuite; + server.GetCipherSuite([&cipherSuite](bool ok, const std::vector &suite) {if (ok) {cipherSuite = suite;}}); + (void)server.GetCertificate([](bool ok, const std::string cert) {}); + const std::string data = "how do you do?"; + TCPSendOptions tcpSendOptions; + tcpSendOptions.SetData(data); + server.Send(tcpSendOptions, [](bool ok) {if (ok) {EXPECT_TRUE(ok);}}); + sleep(2); + (void)server.Close([](bool ok) {if (ok) {;}}); +} + +HWTEST_F(TlsSocketTest, tlsSocketCertChainConnect, testing::ext::TestSize.Level2) +{ + TLSConnectOptions options; + TLSSocket server; + + TlsSocketConnect(options); + + server.Connect(options, [](bool ok){ EXPECT_TRUE(ok); }); + const std::string data = "how do you do?"; + TCPSendOptions tcpSendOptions; + tcpSendOptions.SetData(data); + server.Send(tcpSendOptions, [](bool ok) {if (ok) {EXPECT_TRUE(ok);}}); + sleep(2); + (void)server.Close([](bool ok) {if (ok) {;}}); +} + +HWTEST_F(TlsSocketTest, tlsSocketCertChainConnectOther, testing::ext::TestSize.Level2) +{ + TLSConnectOptions options; + TLSSocket server; + + TlsSocketConnect(options); + + server.Connect(options, [](bool ok){ EXPECT_TRUE(ok); }); + std::vector cipherSuite; + server.GetCipherSuite([&cipherSuite](bool ok, const std::vector &suite) {if (ok) {cipherSuite = suite;}}); + const std::string data = "how do you do?"; + TCPSendOptions tcpSendOptions; + tcpSendOptions.SetData(data); + server.Send(tcpSendOptions, [](bool ok) {if (ok) {EXPECT_TRUE(ok);}}); + sleep(2); + (void)server.Close([](bool ok) {if (ok) {;}}); +} + +HWTEST_F(TlsSocketTest, tlsConnetOptionsSend2, testing::ext::TestSize.Level2) +{ + TLSConnectOptions options; + TLSSocket server; + + TlsSocketConnect(options); + + server.Connect(options, [](bool ok){ EXPECT_TRUE(ok); }); + std::vector cipherSuite; + server.GetCipherSuite([&cipherSuite](bool ok, const std::vector &suite) {if (ok) {cipherSuite = suite;}}); + const std::string data = "how do you do? This is UT test tlsConnetOptionsSend"; + TCPSendOptions tcpSendOptions; + tcpSendOptions.SetData(data); + server.Send(tcpSendOptions, [](bool ok) {if (ok) {EXPECT_TRUE(ok);}}); + + sleep(2); + + (void)server.Close([](bool ok) {if (ok) {;}}); +} + +HWTEST_F(TlsSocketTest, tlsOptionGet, testing::ext::TestSize.Level2) +{ + TLSConnectOptions options; + TLSSecureOptions secureOption; + NetAddress address; + TLSSocket server; + std::vector cipherSuite; + std::vector caVec = {ChangeToFile(CA_DER)}; + std::vector protocolVec = {"TlsV1_2"}; + std::string signatureAlgorithmVec = {"RSA-SHA256"}; + std::vector alpnProtocols = {"spdy/1", "http/1.1"}; + + address.SetAddress("10.14.0.91"); + address.SetPort(7838); + address.SetFamilyBySaFamily(AF_INET); + secureOption.SetKey(PRIVATE_KEY_PEM);// + (void)secureOption.GetKey(); + (void)options.GetTlsSecureOptions().GetKey(); + + secureOption.SetCaChain(caVec);// + secureOption.SetCert(CLIENT_CRT);// + secureOption.SetCipherSuite("AES256-SHA256");// + secureOption.SetProtocolChain(protocolVec);// + secureOption.SetUseRemoteCipherPrefer(true);// + secureOption.SetSignatureAlgorithms(signatureAlgorithmVec);// + secureOption.SetPassWd("123456");// + options.SetNetAddress(address); + options.SetTlsSecureOptions(secureOption); + options.SetAlpnProtocols(alpnProtocols); + + for (int i = 0; i < caVec.size(); i++) { + std::cout << "setcaVec: "<< caVec[i] << std::endl; + } + std::cout << "setCert: " << CLIENT_CRT << std::endl; + std::cout << "setKey: " << PRIVATE_KEY_PEM << std::endl; + std::cout << "setCipherSuite: " << "AES256-SHA256" << std::endl; + for (int i = 0; i < caVec.size(); i++) { + std::cout << "setProtocolChain: "<< protocolVec[i].c_str() << std::endl; + } + std::cout << "setUseRemoteCipherPrefer: " << "true" << std::endl; + std::cout << "setSignatureAlgorithms: " << signatureAlgorithmVec << std::endl; + std::cout << "SetPassWd: " << "123456" << std::endl; + + TLSSecureOptions tLSSecureOptions = options.GetTlsSecureOptions(); + std::vector testCaChain = tLSSecureOptions.GetCaChain(); + std::string getCert = tLSSecureOptions.GetCert(); + std::string getKey = tLSSecureOptions.GetKey(); + std::string getPasswd = tLSSecureOptions.GetPasswd(); + std::vector getProtocolChain = tLSSecureOptions.GetProtocolChain(); + bool getIsUseRemoteCipherPrefer = tLSSecureOptions.UseRemoteCipherPrefer(); + std::string getSignatureAlgorithms = tLSSecureOptions.GetSignatureAlgorithms(); + + for (int i = 0; i < caVec.size(); i++) { + std::cout << "getcaVec: "<< testCaChain[i] << std::endl; + } + std::cout << "getsetCert: " << getCert << std::endl; + std::cout << "getsetKey: " << getKey << std::endl; + std::cout << "getCipherSuite: " << "AES256-SHA256" << std::endl; + for (int i = 0; i < caVec.size(); i++) { + std::cout << "getProtocolChain: "<< getProtocolChain[i] << std::endl; + } + std::cout << "getUseRemoteCipherPrefer: " << getIsUseRemoteCipherPrefer << std::endl; + std::cout << "getSignatureAlgorithms: " << getSignatureAlgorithms << std::endl; + std::cout << "getSetPassWd: " << getPasswd << std::endl; + sleep(1); +} + +HWTEST_F(TlsSocketTest, tlsSocketGcertInternal, testing::ext::TestSize.Level2) +{ + std::cout << "TlsSocketTest, tlsSocketGetState begin " << std::endl; + TLSSocket server; + TLSConnectOptions options; + TCPSendOptions tcpSendOptions; + const std::string data = "how do you do? This is UT test tlsSocketGcertInternal"; + + TlsSocketConnect(options); + + server.Connect(options, [] (bool ok){ EXPECT_TRUE(ok); }); + + tcpSendOptions.SetData(data); + + server.Send(tcpSendOptions, [] (bool ok) { EXPECT_TRUE(ok); }); + + bool IsGetCertificate; + std::string certInternal; + server.GetCertificate([&IsGetCertificate, &certInternal] (bool ok, const std::string &cert) { + IsGetCertificate = ok; + certInternal = cert; + }); + std::cout << "GetCertificate IsGetCertificate: " << IsGetCertificate < algorithmsInternal; + server.GetSignatureAlgorithms([&IsGetSignatureAlgorithms, &algorithmsInternal] (bool ok, const std::vector &algorithms) { + IsGetSignatureAlgorithms = ok; + algorithmsInternal = algorithms; + }); + std::cout << "GetSignatureAlgorithms IsGetSignatureAlgorithms: " << IsGetSignatureAlgorithms < #include "napi/native_api.h" -#include "netstack_event_listener.h" +#include "event_listener.h" #include "uv.h" namespace OHOS::NetStack { diff --git a/utils/module_template/include/netstack_module_template.h b/utils/napi_utils/include/module_template.h similarity index 98% rename from utils/module_template/include/netstack_module_template.h rename to utils/napi_utils/include/module_template.h index a35f2ed6f419de694cfdb9ea761cbbc07b832283..b5a3241a926ab5f67cc33305967d93fbdee39224 100644 --- a/utils/module_template/include/netstack_module_template.h +++ b/utils/napi_utils/include/module_template.h @@ -24,9 +24,9 @@ #include "napi/native_api.h" #include "napi/native_api.h" #include "napi/native_common.h" -#include "netstack_base_context.h" +#include "base_context.h" #include "netstack_log.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" namespace OHOS::NetStack { class EventManager; } diff --git a/utils/napi_utils/include/netstack_napi_utils.h b/utils/napi_utils/include/napi_utils.h similarity index 92% rename from utils/napi_utils/include/netstack_napi_utils.h rename to utils/napi_utils/include/napi_utils.h index 6c5872ee18b19e9fe2ad49d13add300f6cdcc36e..6907e521cfb0e1a9afea6ee12446391d77f35bc8 100644 --- a/utils/napi_utils/include/netstack_napi_utils.h +++ b/utils/napi_utils/include/napi_utils.h @@ -103,6 +103,13 @@ void DefineProperties(napi_env env, napi_value object, const std::initializer_list &properties); +/* array */ +napi_value CreateArray(napi_env env, size_t length); +void SetArrayElement(napi_env env, napi_value array, uint32_t index, napi_value value); +bool IsArray(napi_env env, napi_value value); +uint32_t GetArrayLength(napi_env env, napi_value arr); +napi_value GetArrayElement(napi_env env, napi_value arr, uint32_t index); + /* JSON */ napi_value JsonStringify(napi_env env, napi_value object); diff --git a/utils/base_context/src/netstack_base_context.cpp b/utils/napi_utils/src/base_context.cpp similarity index 96% rename from utils/base_context/src/netstack_base_context.cpp rename to utils/napi_utils/src/base_context.cpp index 5f163d6d0826d428266525068eb7e37b11cc871f..0c81709a748a0f8396834a57c60f98e756912732 100644 --- a/utils/base_context/src/netstack_base_context.cpp +++ b/utils/napi_utils/src/base_context.cpp @@ -13,12 +13,12 @@ * limitations under the License. */ -#include "netstack_base_context.h" +#include "base_context.h" #include "napi/native_api.h" #include "napi/native_common.h" -#include "netstack_event_manager.h" -#include "netstack_napi_utils.h" +#include "event_manager.h" +#include "napi_utils.h" #include "node_api.h" namespace OHOS::NetStack { @@ -177,4 +177,4 @@ void BaseContext::ParseParams(napi_value *params, size_t paramsCount) } SetParseOK(true); } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/utils/event_manager/src/netstack_event_listener.cpp b/utils/napi_utils/src/event_listener.cpp similarity index 98% rename from utils/event_manager/src/netstack_event_listener.cpp rename to utils/napi_utils/src/event_listener.cpp index c9c70ab6f4386915317e2c8b75e8cef80883a47c..c5c817eb6ee01007ddc743ef4f58b183979b397e 100644 --- a/utils/event_manager/src/netstack_event_listener.cpp +++ b/utils/napi_utils/src/event_listener.cpp @@ -13,11 +13,11 @@ * limitations under the License. */ -#include "netstack_event_listener.h" +#include "event_listener.h" #include "napi/native_api.h" #include "napi/native_common.h" -#include "netstack_napi_utils.h" +#include "napi_utils.h" namespace OHOS::NetStack { EventListener::EventListener(napi_env env, std::string type, napi_value callback, bool once, bool asyncCallback) diff --git a/utils/event_manager/src/netstack_event_manager.cpp b/utils/napi_utils/src/event_manager.cpp similarity index 98% rename from utils/event_manager/src/netstack_event_manager.cpp rename to utils/napi_utils/src/event_manager.cpp index af2e1428d4a2cdf3c2ef011b3609ff6ebef352bc..005531032cd1c7777e5d564e09bb088ab4988f8e 100644 --- a/utils/event_manager/src/netstack_event_manager.cpp +++ b/utils/napi_utils/src/event_manager.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "netstack_event_manager.h" +#include "event_manager.h" #include @@ -111,4 +111,4 @@ UvWorkWrapper::UvWorkWrapper(void *theData, napi_env theEnv, std::string eventTy : data(theData), env(theEnv), type(std::move(eventType)), manager(eventManager) { } -} // namespace OHOS::NetStack \ No newline at end of file +} // namespace OHOS::NetStack diff --git a/utils/module_template/src/netstack_module_template.cpp b/utils/napi_utils/src/module_template.cpp similarity index 98% rename from utils/module_template/src/netstack_module_template.cpp rename to utils/napi_utils/src/module_template.cpp index 42d170f5224b75a847673f58196fa06699a31c8d..9a5cc190e915c6cdc7818f7cb1961733eeb3ff5f 100644 --- a/utils/module_template/src/netstack_module_template.cpp +++ b/utils/napi_utils/src/module_template.cpp @@ -13,14 +13,14 @@ * limitations under the License. */ -#include "netstack_module_template.h" +#include "module_template.h" #include #include #include #include -#include "netstack_event_manager.h" +#include "event_manager.h" #include "netstack_log.h" namespace OHOS::NetStack::ModuleTemplate { @@ -175,4 +175,4 @@ napi_value NewInstanceNoManager(napi_env env, napi_callback_info info, const std return result; } -} // namespace OHOS::NetStack::ModuleTemplate \ No newline at end of file +} // namespace OHOS::NetStack::ModuleTemplate diff --git a/utils/napi_utils/src/netstack_napi_utils.cpp b/utils/napi_utils/src/napi_utils.cpp similarity index 92% rename from utils/napi_utils/src/netstack_napi_utils.cpp rename to utils/napi_utils/src/napi_utils.cpp index c07b8740a3746722cc7aaf700e86669c616a4ca2..0f5345a0693ef7ebadaf27d1b8babf29336eec12 100644 --- a/utils/napi_utils/src/netstack_napi_utils.cpp +++ b/utils/napi_utils/src/napi_utils.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "netstack_napi_utils.h" +#include "napi_utils.h" #include #include @@ -28,7 +28,7 @@ #include "napi/native_api.h" #include "napi/native_common.h" #include "node_api.h" -#include "netstack_base_context.h" +#include "base_context.h" namespace OHOS::NetStack::NapiUtils { static constexpr const int MAX_STRING_LENGTH = 65536; @@ -335,6 +335,46 @@ void DefineProperties(napi_env env, (void)napi_define_properties(env, object, properties.size(), descriptors); } +/* array */ +napi_value CreateArray(napi_env env, size_t length) +{ + if (length == 0) { + napi_value res = nullptr; + NAPI_CALL(env, napi_create_array(env, &res)); + return res; + } + napi_value res = nullptr; + NAPI_CALL(env, napi_create_array_with_length(env, length, &res)); + return res; +} + +void SetArrayElement(napi_env env, napi_value array, uint32_t index, napi_value value) +{ + (void)napi_set_element(env, array, index, value); +} + +bool IsArray(napi_env env, napi_value value) +{ + bool result = false; + NAPI_CALL_BASE(env, napi_is_array(env, value, &result), false); + return result; +} + +uint32_t GetArrayLength(napi_env env, napi_value arr) +{ + uint32_t arrayLength = 0; + NAPI_CALL_BASE(env, napi_get_array_length(env, arr, &arrayLength), 0); + return arrayLength; +} + +napi_value GetArrayElement(napi_env env, napi_value arr, uint32_t index) +{ + napi_value elementValue = nullptr; + NAPI_CALL(env, napi_get_element(env, arr, index, &elementValue)); + return elementValue; +} + + /* JSON */ napi_value JsonStringify(napi_env env, napi_value object) {