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_server.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 TLSContextServer::verifyMode_ = TWO_WAY_MODE;
CreateConfiguration(const TLSConfiguration & configuration)32 std::unique_ptr<TLSContextServer> TLSContextServer::CreateConfiguration(const TLSConfiguration &configuration)
33 {
34 auto tlsContext = std::make_unique<TLSContextServer>();
35 if (!InitTlsContext(tlsContext.get(), configuration)) {
36 NETSTACK_LOGE("Failed to init tls context");
37 return nullptr;
38 }
39 return tlsContext;
40 }
41
InitEnvServer()42 void InitEnvServer()
43 {
44 SSL_library_init();
45 OpenSSL_add_all_algorithms();
46 SSL_load_error_strings();
47 }
48
SetCipherList(TLSContextServer * tlsContext,const TLSConfiguration & configuration)49 bool TLSContextServer::SetCipherList(TLSContextServer *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(TLSContextServer * tlsContext)63 void TLSContextServer::GetCiphers(TLSContextServer *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(TLSContextServer * tlsContext,const TLSConfiguration & configuration)84 bool TLSContextServer::SetSignatureAlgorithms(TLSContextServer *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(TLSContextServer * tlsContext)102 void TLSContextServer::UseRemoteCipher(TLSContextServer *tlsContext)
103 {
104 if (!tlsContext) {
105 NETSTACK_LOGE("TLSContextServer::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(TLSContextServer * tlsContext)115 void TLSContextServer::SetMinAndMaxProtocol(TLSContextServer *tlsContext)
116 {
117 if (!tlsContext) {
118 NETSTACK_LOGE("TLSContextServer::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(TLSContextServer * tlsContext,const TLSConfiguration & configuration)165 bool TLSContextServer::SetCaAndVerify(TLSContextServer *tlsContext, const TLSConfiguration &configuration)
166 {
167 NETSTACK_LOGI("SetCaAndVerify ");
168
169 if (!tlsContext) {
170 NETSTACK_LOGE("tlsContext is null");
171 return false;
172 }
173 for (const auto &cert : configuration.GetCaCertificate()) {
174 TLSCertificate ca(cert, CA_CERT);
175 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(tlsContext->ctx_), static_cast<X509 *>(ca.handle()))) {
176 NETSTACK_LOGE("Failed to add x509 cert");
177 return false;
178 }
179 }
180
181 NETSTACK_LOGI("SetCaAndVerify ok");
182 return true;
183 }
184
SetLocalCertificate(TLSContextServer * tlsContext,const TLSConfiguration & configuration)185 bool TLSContextServer::SetLocalCertificate(TLSContextServer *tlsContext, const TLSConfiguration &configuration)
186 {
187 if (!tlsContext) {
188 NETSTACK_LOGE("tlsContext is null");
189 return false;
190 }
191 if (!SSL_CTX_use_certificate(tlsContext->ctx_, static_cast<X509 *>(configuration.GetLocalCertificate().handle()))) {
192 NETSTACK_LOGD("The local certificate is unavailable");
193 return false;
194 }
195 return true;
196 }
197
SetKeyAndCheck(TLSContextServer * tlsContext,const TLSConfiguration & configuration)198 bool TLSContextServer::SetKeyAndCheck(TLSContextServer *tlsContext, const TLSConfiguration &configuration)
199 {
200 if (!tlsContext) {
201 NETSTACK_LOGE("The parameter tlsContext is null");
202 return false;
203 }
204 if (configuration.GetPrivateKey().Algorithm() == OPAQUE) {
205 tlsContext->pkey_ = reinterpret_cast<EVP_PKEY *>(configuration.GetPrivateKey().handle());
206 } else {
207 tlsContext->pkey_ = EVP_PKEY_new();
208 if (configuration.GetPrivateKey().Algorithm() == ALGORITHM_RSA) {
209 EVP_PKEY_set1_RSA(tlsContext->pkey_, reinterpret_cast<RSA *>(configuration.GetPrivateKey().handle()));
210 } else if (tlsContext->tlsConfiguration_.GetPrivateKey().Algorithm() == ALGORITHM_DSA) {
211 EVP_PKEY_set1_DSA(tlsContext->pkey_, reinterpret_cast<DSA *>(configuration.GetPrivateKey().handle()));
212 }
213 }
214
215 if (configuration.GetPrivateKey().Algorithm() == OPAQUE) {
216 tlsContext->pkey_ = nullptr;
217 }
218 auto pkey_ = tlsContext->pkey_;
219 if (!SSL_CTX_use_PrivateKey(tlsContext->ctx_, pkey_)) {
220 NETSTACK_LOGE("SSL_CTX_use_PrivateKey is error");
221 return false;
222 }
223
224 if (!configuration.GetPrivateKey().GetKeyPass().Length()) {
225 SSL_CTX_set_default_passwd_cb_userdata(tlsContext->ctx_,
226 reinterpret_cast<void *>(const_cast<char *>(
227 tlsContext->tlsConfiguration_.GetPrivateKey().GetKeyPass().Data())));
228 }
229 // Check if the certificate matches the private key.
230 if (!SSL_CTX_check_private_key(tlsContext->ctx_)) {
231 NETSTACK_LOGE("Check if the certificate matches the private key is error");
232 return false;
233 }
234 return true;
235 }
236
SetVerify(TLSContextServer * tlsContext)237 void TLSContextServer::SetVerify(TLSContextServer *tlsContext)
238 {
239 if (!tlsContext) {
240 NETSTACK_LOGE("tlsContext is null");
241 return;
242 }
243
244 NETSTACK_LOGE("TLSContextServer::SetVerify tlsContext %{public}d",
245 tlsContext->tlsConfiguration_.GetVerifyMode());
246 if (tlsContext->tlsConfiguration_.GetVerifyMode() == ONE_WAY_MODE) {
247 SSL_CTX_set_verify(tlsContext->ctx_, SSL_VERIFY_PEER, nullptr);
248 verifyMode_ = ONE_WAY_MODE;
249 } else {
250 verifyMode_ = TWO_WAY_MODE;
251 SSL_CTX_set_verify(tlsContext->ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
252 }
253
254 NETSTACK_LOGD("Authentication mode is %{public}s",
255 verifyMode_ ? "two-way authentication" : "one-way authentication");
256 }
257
InitTlsContext(TLSContextServer * tlsContext,const TLSConfiguration & configuration)258 bool TLSContextServer::InitTlsContext(TLSContextServer *tlsContext, const TLSConfiguration &configuration)
259 {
260 if (!tlsContext) {
261 NETSTACK_LOGE("tlsContext is null");
262 return false;
263 }
264 InitEnvServer();
265 tlsContext->tlsConfiguration_ = configuration;
266 tlsContext->ctx_ = SSL_CTX_new(TLS_server_method());
267 if (tlsContext->ctx_ == nullptr) {
268 NETSTACK_LOGE("ctx is nullptr");
269 return false;
270 }
271 if (!configuration.GetCipherSuite().empty()) {
272 if (!SetCipherList(tlsContext, configuration)) {
273 NETSTACK_LOGE("Failed to set cipher suite");
274 return false;
275 }
276 }
277 if (!configuration.GetSignatureAlgorithms().empty()) {
278 if (!SetSignatureAlgorithms(tlsContext, configuration)) {
279 NETSTACK_LOGE("Failed to set signature algorithms");
280 return false;
281 }
282 }
283 GetCiphers(tlsContext);
284 UseRemoteCipher(tlsContext);
285 SetMinAndMaxProtocol(tlsContext);
286 SetVerify(tlsContext);
287 if (!SetCaAndVerify(tlsContext, configuration)) {
288 return false;
289 }
290 if (!SetLocalCertificate(tlsContext, configuration)) {
291 return false;
292 }
293 if (!SetKeyAndCheck(tlsContext, configuration)) {
294 return false;
295 }
296 return true;
297 }
CreateSsl()298 SSL *TLSContextServer::CreateSsl()
299 {
300 ctxSsl_ = SSL_new(ctx_);
301 return ctxSsl_;
302 }
303
CloseCtx()304 void TLSContextServer::CloseCtx()
305 {
306 SSL_CTX_free(ctx_);
307 }
308 } // namespace TlsSocket
309 } // namespace NetStack
310 } // namespace OHOS
311