1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "tls_context.h"
17
18 #include <cerrno>
19 #include <cinttypes>
20 #include <string>
21
22 #include <openssl/err.h>
23 #include <openssl/evp.h>
24 #include <openssl/ssl.h>
25
26 #include "netstack_log.h"
27
28 namespace OHOS {
29 namespace NetStack {
30 namespace TlsSocket {
31 VerifyMode TLSContext::verifyMode_ = TWO_WAY_MODE;
CreateConfiguration(const TLSConfiguration & configuration)32 std::unique_ptr<TLSContext> TLSContext::CreateConfiguration(const TLSConfiguration &configuration)
33 {
34 auto tlsContext = std::make_unique<TLSContext>();
35 if (!InitTlsContext(tlsContext.get(), configuration)) {
36 NETSTACK_LOGE("Failed to init tls context");
37 return nullptr;
38 }
39 return tlsContext;
40 }
41
InitEnv()42 void InitEnv()
43 {
44 SSL_library_init();
45 OpenSSL_add_all_algorithms();
46 SSL_load_error_strings();
47 }
48
SetCipherList(TLSContext * tlsContext,const TLSConfiguration & configuration)49 bool TLSContext::SetCipherList(TLSContext *tlsContext, const TLSConfiguration &configuration)
50 {
51 if (!tlsContext) {
52 NETSTACK_LOGE("tlsContext is null");
53 return false;
54 }
55 NETSTACK_LOGD("GetCipherSuite = %{public}s", configuration.GetCipherSuite().c_str());
56 if (SSL_CTX_set_cipher_list(tlsContext->ctx_, configuration.GetCipherSuite().c_str()) <= 0) {
57 NETSTACK_LOGE("Error setting the cipher list");
58 return false;
59 }
60 return true;
61 }
62
GetCiphers(TLSContext * tlsContext)63 void TLSContext::GetCiphers(TLSContext *tlsContext)
64 {
65 if (!tlsContext) {
66 NETSTACK_LOGE("tlsContext is null");
67 return;
68 }
69 std::vector<CipherSuite> cipherSuiteVec;
70 STACK_OF(SSL_CIPHER) *sk = SSL_CTX_get_ciphers(tlsContext->ctx_);
71 if (!sk) {
72 NETSTACK_LOGE("sk is null");
73 return;
74 }
75 CipherSuite cipherSuite;
76 for (int i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
77 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(sk, i);
78 cipherSuite.cipherId_ = SSL_CIPHER_get_id(cipher);
79 cipherSuite.cipherName_ = SSL_CIPHER_get_name(cipher);
80 cipherSuiteVec.push_back(cipherSuite);
81 }
82 }
83
SetSignatureAlgorithms(TLSContext * tlsContext,const TLSConfiguration & configuration)84 bool TLSContext::SetSignatureAlgorithms(TLSContext *tlsContext, const TLSConfiguration &configuration)
85 {
86 if (!tlsContext) {
87 NETSTACK_LOGE("tlsContext is null");
88 return false;
89 }
90 if (configuration.GetSignatureAlgorithms().empty()) {
91 NETSTACK_LOGE("configuration get signature algorithms is empty");
92 return false;
93 }
94
95 if (!SSL_CTX_set1_sigalgs_list(tlsContext->ctx_, configuration.GetSignatureAlgorithms().c_str())) {
96 NETSTACK_LOGE("Error setting the Signature Algorithms");
97 return false;
98 }
99 return true;
100 }
101
UseRemoteCipher(TLSContext * tlsContext)102 void TLSContext::UseRemoteCipher(TLSContext *tlsContext)
103 {
104 if (!tlsContext) {
105 NETSTACK_LOGE("TLSContext::UseRemoteCipher: tlsContext is null");
106 return;
107 }
108 if (tlsContext->tlsConfiguration_.GetUseRemoteCipherPrefer()) {
109 SSL_CTX_set_options(tlsContext->ctx_, SSL_OP_CIPHER_SERVER_PREFERENCE);
110 }
111 NETSTACK_LOGI("SSL_CTX_get_options = %{public}" PRIx64,
112 static_cast<uint64_t>(SSL_CTX_get_options(tlsContext->ctx_)));
113 }
114
SetMinAndMaxProtocol(TLSContext * tlsContext)115 void TLSContext::SetMinAndMaxProtocol(TLSContext *tlsContext)
116 {
117 if (!tlsContext) {
118 NETSTACK_LOGE("TLSContext::SetMinAndMaxProtocol: tlsContext is null");
119 return;
120 }
121 const long anyVersion = TLS_ANY_VERSION;
122 long minVersion = anyVersion;
123 long maxVersion = anyVersion;
124
125 switch (tlsContext->tlsConfiguration_.GetMinProtocol()) {
126 case TLS_V1_2:
127 minVersion = TLS1_2_VERSION;
128 break;
129 case TLS_V1_3:
130 minVersion = TLS1_3_VERSION;
131 break;
132 case UNKNOW_PROTOCOL:
133 break;
134 default:
135 break;
136 }
137
138 switch (tlsContext->tlsConfiguration_.GetMaxProtocol()) {
139 case TLS_V1_2:
140 maxVersion = TLS1_2_VERSION;
141 break;
142 case TLS_V1_3:
143 maxVersion = TLS1_3_VERSION;
144 break;
145 case UNKNOW_PROTOCOL:
146 break;
147 default:
148 break;
149 }
150
151 if (minVersion != anyVersion && !SSL_CTX_set_min_proto_version(tlsContext->ctx_, minVersion)) {
152 NETSTACK_LOGE("Error while setting the minimal protocol version");
153 return;
154 }
155
156 if (maxVersion != anyVersion && !SSL_CTX_set_max_proto_version(tlsContext->ctx_, maxVersion)) {
157 NETSTACK_LOGE("Error while setting the maximum protocol version");
158 return;
159 }
160
161 NETSTACK_LOGD("minProtocol = %{public}lx, maxProtocol = %{public}lx",
162 SSL_CTX_get_min_proto_version(tlsContext->ctx_), SSL_CTX_get_max_proto_version(tlsContext->ctx_));
163 }
164
SetCaAndVerify(TLSContext * tlsContext,const TLSConfiguration & configuration)165 bool TLSContext::SetCaAndVerify(TLSContext *tlsContext, const TLSConfiguration &configuration)
166 {
167 if (!tlsContext) {
168 NETSTACK_LOGE("tlsContext is null");
169 return false;
170 }
171 for (const auto &cert : configuration.GetCaCertificate()) {
172 TLSCertificate ca(cert, CA_CERT);
173 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(tlsContext->ctx_), static_cast<X509 *>(ca.handle()))) {
174 NETSTACK_LOGE("Failed to add x509 cert");
175 return false;
176 }
177 }
178 return true;
179 }
180
SetLocalCertificate(TLSContext * tlsContext,const TLSConfiguration & configuration)181 bool TLSContext::SetLocalCertificate(TLSContext *tlsContext, const TLSConfiguration &configuration)
182 {
183 if (!tlsContext) {
184 NETSTACK_LOGE("tlsContext is null");
185 return false;
186 }
187 if (!SSL_CTX_use_certificate(tlsContext->ctx_, static_cast<X509 *>(configuration.GetLocalCertificate().handle()))) {
188 NETSTACK_LOGD("The local certificate is unavailable");
189 return false;
190 }
191 return true;
192 }
193
SetKeyAndCheck(TLSContext * tlsContext,const TLSConfiguration & configuration)194 bool TLSContext::SetKeyAndCheck(TLSContext *tlsContext, const TLSConfiguration &configuration)
195 {
196 if (!tlsContext) {
197 NETSTACK_LOGE("The parameter tlsContext is null");
198 return false;
199 }
200 if (configuration.GetPrivateKey().Algorithm() == OPAQUE) {
201 tlsContext->pkey_ = reinterpret_cast<EVP_PKEY *>(configuration.GetPrivateKey().handle());
202 } else {
203 tlsContext->pkey_ = EVP_PKEY_new();
204 if (configuration.GetPrivateKey().Algorithm() == ALGORITHM_RSA) {
205 EVP_PKEY_set1_RSA(tlsContext->pkey_, reinterpret_cast<RSA *>(configuration.GetPrivateKey().handle()));
206 } else if (tlsContext->tlsConfiguration_.GetPrivateKey().Algorithm() == ALGORITHM_DSA) {
207 EVP_PKEY_set1_DSA(tlsContext->pkey_, reinterpret_cast<DSA *>(configuration.GetPrivateKey().handle()));
208 }
209 }
210
211 if (configuration.GetPrivateKey().Algorithm() == OPAQUE) {
212 tlsContext->pkey_ = nullptr;
213 }
214 auto pkey_ = tlsContext->pkey_;
215 if (!SSL_CTX_use_PrivateKey(tlsContext->ctx_, pkey_)) {
216 NETSTACK_LOGE("SSL_CTX_use_PrivateKey is error");
217 return false;
218 }
219
220 if (!configuration.GetPrivateKey().GetKeyPass().Length()) {
221 SSL_CTX_set_default_passwd_cb_userdata(tlsContext->ctx_,
222 reinterpret_cast<void *>(const_cast<char *>(
223 tlsContext->tlsConfiguration_.GetPrivateKey().GetKeyPass().Data())));
224 }
225 // Check if the certificate matches the private key.
226 if (!SSL_CTX_check_private_key(tlsContext->ctx_)) {
227 NETSTACK_LOGE("Check if the certificate matches the private key is error");
228 return false;
229 }
230 return true;
231 }
232
SetVerify(TLSContext * tlsContext)233 void TLSContext::SetVerify(TLSContext *tlsContext)
234 {
235 if (!tlsContext) {
236 NETSTACK_LOGE("tlsContext is null");
237 return;
238 }
239
240 if (tlsContext->tlsConfiguration_.GetCaCertificate().empty() ||
241 !tlsContext->tlsConfiguration_.GetCertificate().data.Length() ||
242 !tlsContext->tlsConfiguration_.GetPrivateKey().GetKeyData().Length()) {
243 verifyMode_ = ONE_WAY_MODE;
244 SSL_CTX_set_verify(tlsContext->ctx_, SSL_VERIFY_PEER, nullptr);
245 } else {
246 verifyMode_ = TWO_WAY_MODE;
247 SSL_CTX_set_verify(tlsContext->ctx_, SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
248 }
249 NETSTACK_LOGD("Authentication mode is %{public}s",
250 verifyMode_ ? "two-way authentication" : "one-way authentication");
251 }
252
InitTlsContext(TLSContext * tlsContext,const TLSConfiguration & configuration)253 bool TLSContext::InitTlsContext(TLSContext *tlsContext, const TLSConfiguration &configuration)
254 {
255 if (!tlsContext) {
256 NETSTACK_LOGE("tlsContext is null");
257 return false;
258 }
259 InitEnv();
260 tlsContext->tlsConfiguration_ = configuration;
261 tlsContext->ctx_ = SSL_CTX_new(TLS_client_method());
262 if (tlsContext->ctx_ == nullptr) {
263 NETSTACK_LOGE("ctx is nullptr");
264 return false;
265 }
266 if (!configuration.GetCipherSuite().empty()) {
267 if (!SetCipherList(tlsContext, configuration)) {
268 NETSTACK_LOGE("Failed to set cipher suite");
269 return false;
270 }
271 }
272 if (!configuration.GetSignatureAlgorithms().empty()) {
273 if (!SetSignatureAlgorithms(tlsContext, configuration)) {
274 NETSTACK_LOGE("Failed to set signature algorithms");
275 return false;
276 }
277 }
278 GetCiphers(tlsContext);
279 UseRemoteCipher(tlsContext);
280 SetMinAndMaxProtocol(tlsContext);
281 SetVerify(tlsContext);
282 if (!SetCaAndVerify(tlsContext, configuration)) {
283 return false;
284 }
285 if (!verifyMode_) {
286 NETSTACK_LOGD("one way authentication");
287 return true;
288 }
289 if (!SetLocalCertificate(tlsContext, configuration)) {
290 return false;
291 }
292 if (!SetKeyAndCheck(tlsContext, configuration)) {
293 return false;
294 }
295 return true;
296 }
CreateSsl()297 SSL *TLSContext::CreateSsl()
298 {
299 ctxSsl_ = SSL_new(ctx_);
300 return ctxSsl_;
301 }
302
CloseCtx()303 void TLSContext::CloseCtx()
304 {
305 SSL_CTX_free(ctx_);
306 }
307 } // namespace TlsSocket
308 } // namespace NetStack
309 } // namespace OHOS
310