API参考
载入中...
搜索中...
未找到
tls.h
1/*
2 * This file is part of the openHiTLS project.
3 *
4 * openHiTLS is licensed under the Mulan PSL v2.
5 * You can use this software according to the terms and conditions of the Mulan PSL v2.
6 * You may obtain a copy of Mulan PSL v2 at:
7 *
8 * http://license.coscl.org.cn/MulanPSL2
9 *
10 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13 * See the Mulan PSL v2 for more details.
14 */
15
16#ifndef TLS_H
17#define TLS_H
18
19#include <stdint.h>
20#include <stdbool.h>
21#include "hitls_build.h"
22#include "cipher_suite.h"
23#include "tls_config.h"
24#include "hitls_error.h"
25
26#ifdef __cplusplus
27extern "C" {
28#endif
29
30#define MAX_DIGEST_SIZE 64UL /* The longest known value is SHA512 */
31
32#define DTLS_DEFAULT_PMTU 1500uL
33
34/* RFC 6083 4.1. Mapping of DTLS Records:
35 The supported maximum length of SCTP user messages MUST be at least
36 2^14 + 2048 + 13 = 18445 bytes (2^14 + 2048 is the maximum length of
37 the DTLSCiphertext.fragment, and 13 is the size of the DTLS record
38 header). */
39#define DTLS_SCTP_PMTU 18445uL
40
41#define IS_DTLS_VERSION(version) (((version) & 0x8u) == 0x8u)
42
43#define IS_SUPPORT_STREAM(versionBits) (((versionBits) & STREAM_VERSION_BITS) != 0x0u)
44#define IS_SUPPORT_DATAGRAM(versionBits) (((versionBits) & DATAGRAM_VERSION_BITS) != 0x0u)
45#define IS_SUPPORT_TLCP(versionBits) (((versionBits) & TLCP_VERSION_BITS) != 0x0u)
46#define IS_SUPPORT_TLS(versionBits) (((versionBits) & TLS_VERSION_MASK) != 0x0u)
47
48#define MAC_KEY_LEN 32u /* the length of mac key */
49
50#define UNPROCESSED_APP_MSG_COUNT_MAX 50 /* number of APP data cached */
51
52#define RANDOM_SIZE 32u /* the size of random number */
53
54typedef struct TlsCtx TLS_Ctx;
55typedef struct HsCtx HS_Ctx;
56typedef struct CcsCtx CCS_Ctx;
57typedef struct AlertCtx ALERT_Ctx;
58typedef struct RecCtx REC_Ctx;
59
60typedef enum {
61 CCS_CMD_RECV_READY, /* CCS allowed to be received */
62 CCS_CMD_RECV_EXIT_READY, /* CCS cannot be received */
63 CCS_CMD_RECV_ACTIVE_CIPHER_SPEC, /* CCS active change cipher spec */
64} CCS_Cmd;
65
66/* Check whether the CCS message is received */
67typedef bool (*IsRecvCcsCallback)(const TLS_Ctx *ctx);
68/* Send a CCS message */
69typedef int32_t (*SendCcsCallback)(TLS_Ctx *ctx);
70/* Control the CCS */
71typedef int32_t (*CtrlCcsCallback)(TLS_Ctx *ctx, CCS_Cmd cmd);
72
73typedef enum {
74 ALERT_LEVEL_WARNING = 1,
75 ALERT_LEVEL_FATAL = 2,
76 ALERT_LEVEL_UNKNOWN = 255,
77} ALERT_Level;
78
79typedef enum {
80 ALERT_CLOSE_NOTIFY = 0,
81 ALERT_UNEXPECTED_MESSAGE = 10,
82 ALERT_BAD_RECORD_MAC = 20,
83 ALERT_DECRYPTION_FAILED = 21,
84 ALERT_RECORD_OVERFLOW = 22,
85 ALERT_DECOMPRESSION_FAILURE = 30,
86 ALERT_HANDSHAKE_FAILURE = 40,
87 ALERT_NO_CERTIFICATE_RESERVED = 41,
88 ALERT_BAD_CERTIFICATE = 42,
89 ALERT_UNSUPPORTED_CERTIFICATE = 43,
90 ALERT_CERTIFICATE_REVOKED = 44,
91 ALERT_CERTIFICATE_EXPIRED = 45,
92 ALERT_CERTIFICATE_UNKNOWN = 46,
93 ALERT_ILLEGAL_PARAMETER = 47,
94 ALERT_UNKNOWN_CA = 48,
95 ALERT_ACCESS_DENIED = 49,
96 ALERT_DECODE_ERROR = 50,
97 ALERT_DECRYPT_ERROR = 51,
98 ALERT_EXPORT_RESTRICTION_RESERVED = 60,
99 ALERT_PROTOCOL_VERSION = 70,
100 ALERT_INSUFFICIENT_SECURITY = 71,
101 ALERT_INTERNAL_ERROR = 80,
102 ALERT_INAPPROPRIATE_FALLBACK = 86,
103 ALERT_USER_CANCELED = 90,
104 ALERT_NO_RENEGOTIATION = 100,
105 ALERT_MISSING_EXTENSION = 109,
106 ALERT_UNSUPPORTED_EXTENSION = 110,
107 ALERT_CERTIFICATE_UNOBTAINABLE = 111,
108 ALERT_UNRECOGNIZED_NAME = 112,
109 ALERT_BAD_CERTIFICATE_STATUS_RESPONSE = 113,
110 ALERT_BAD_CERTIFICATE_HASH_VALUE = 114,
111 ALERT_UNKNOWN_PSK_IDENTITY = 115,
112 ALERT_CERTIFICATE_REQUIRED = 116,
113 ALERT_NO_APPLICATION_PROTOCOL = 120,
114 ALERT_UNKNOWN = 255
115} ALERT_Description;
116
118typedef enum {
119 CM_STATE_IDLE,
120 CM_STATE_HANDSHAKING,
121 CM_STATE_TRANSPORTING,
122 CM_STATE_RENEGOTIATION,
123 CM_STATE_ALERTING,
124 CM_STATE_ALERTED,
125#ifdef HITLS_TLS_PROTO_CLOSE_STATE
126 CM_STATE_CLOSED,
127#endif
128 CM_STATE_END
129} CM_State;
130
132typedef enum {
133 PHA_NONE, /* not support pha */
134 PHA_EXTENSION, /* pha extension send or received */
135 PHA_PENDING, /* try to send certificate request */
136 PHA_REQUESTED /* certificate request has been sent or received */
137} PHA_State;
138
139/* Describes the handshake status */
140typedef enum {
141 TLS_IDLE, /* initial state */
142 TLS_CONNECTED, /* Handshake succeeded */
143 TRY_SEND_HELLO_REQUEST, /* sends hello request message */
144 TRY_SEND_CLIENT_HELLO, /* sends client hello message */
145 TRY_SEND_HELLO_VERIFY_REQUEST, /* sends hello verify request message */
146 TRY_SEND_HELLO_RETRY_REQUEST, /* sends hello retry request message */
147 TRY_SEND_SERVER_HELLO, /* sends server hello message */
148 TRY_SEND_ENCRYPTED_EXTENSIONS, /* sends encrypted extensions message */
149 TRY_SEND_CERTIFICATE, /* sends certificate message */
150 TRY_SEND_SERVER_KEY_EXCHANGE, /* sends server key exchange message */
151 TRY_SEND_CERTIFICATE_REQUEST, /* sends certificate request message */
152 TRY_SEND_SERVER_HELLO_DONE, /* sends server hello done message */
153 TRY_SEND_CLIENT_KEY_EXCHANGE, /* sends client key exchange message */
154 TRY_SEND_CERTIFICATE_VERIFY, /* sends certificate verify message */
155 TRY_SEND_NEW_SESSION_TICKET, /* sends new session ticket message */
156 TRY_SEND_CHANGE_CIPHER_SPEC, /* sends change cipher spec message */
157 TRY_SEND_END_OF_EARLY_DATA, /* sends end of early data message */
158 TRY_SEND_FINISH, /* sends finished message */
159 TRY_SEND_KEY_UPDATE, /* sends keyupdate message */
160 TRY_RECV_CLIENT_HELLO, /* attempts to receive client hello message */
161 TRY_RECV_HELLO_VERIFY_REQUEST, /* attempts to receive hello verify request message */
162 TRY_RECV_SERVER_HELLO, /* attempts to receive server hello message */
163 TRY_RECV_ENCRYPTED_EXTENSIONS, /* attempts to receive encrypted extensions message */
164 TRY_RECV_CERTIFICATE, /* attempts to receive certificate message */
165 TRY_RECV_SERVER_KEY_EXCHANGE, /* attempts to receive server key exchange message */
166 TRY_RECV_CERTIFICATE_REQUEST, /* attempts to receive certificate request message */
167 TRY_RECV_SERVER_HELLO_DONE, /* attempts to receive server hello done message */
168 TRY_RECV_CLIENT_KEY_EXCHANGE, /* attempts to receive client key exchange message */
169 TRY_RECV_CERTIFICATE_VERIFY, /* attempts to receive certificate verify message */
170 TRY_RECV_NEW_SESSION_TICKET, /* attempts to receive new session ticket message */
171 TRY_RECV_END_OF_EARLY_DATA, /* attempts to receive end of early data message */
172 TRY_RECV_FINISH, /* attempts to receive finished message */
173 TRY_RECV_KEY_UPDATE, /* attempts to receive keyupdate message */
174 TRY_RECV_HELLO_REQUEST, /* attempts to receive hello request message */
175 HS_STATE_BUTT = 255 /* enumerated Maximum Value */
176} HITLS_HandshakeState;
177
178typedef enum {
179 TLS_PROCESS_STATE_A,
180 TLS_PROCESS_STATE_B
181} HitlsProcessState;
182
183typedef void (*SendAlertCallback)(const TLS_Ctx *ctx, ALERT_Level level, ALERT_Description description);
184
185typedef void (*ClearAlertCallBack)(TLS_Ctx *ctx, uint32_t recordType);
186
187typedef bool (*GetAlertFlagCallback)(const TLS_Ctx *ctx);
188
189typedef int32_t (*UnexpectMsgHandleCallback)(TLS_Ctx *ctx, uint32_t msgType, const uint8_t *data, uint32_t dataLen,
190 bool isPlain);
191
193typedef struct TLSCtxConfig {
194 void *userData; /* user data */
195 uint16_t linkMtu; /* Maximum transport unit of a path (bytes),
196 including IP header and udp/tcp header */
197 uint16_t pmtu; /* Maximum transport unit of a path (bytes) */
198
199 uint8_t reserved[1]; /* four-byte alignment */
200
201 TLS_Config tlsConfig; /* tls configure context */
202} TLS_CtxConfig;
203
204typedef struct {
205 uint32_t algRemainTime; /* current key usage times */
206 uint8_t preMacKey[MAC_KEY_LEN]; /* previous random key */
207 uint8_t macKey[MAC_KEY_LEN]; /* random key used by the current algorithm */
208} CookieInfo;
209
210typedef struct {
211 uint16_t version; /* negotiated version */
212 uint16_t clientVersion; /* version field of client hello */
213 uint32_t cookieSize; /* cookie length */
214 uint8_t *cookie; /* cookie data */
215 CookieInfo cookieInfo; /* cookie info with calculation and verification */
216 CipherSuiteInfo cipherSuiteInfo; /* cipher suite info */
217 HITLS_SignHashAlgo signScheme; /* sign algorithm used by the local */
218 uint8_t *alpnSelected; /* alpn proto */
219 uint32_t alpnSelectedSize;
220 uint8_t clientVerifyData[MAX_DIGEST_SIZE]; /* client verify data */
221 uint8_t serverVerifyData[MAX_DIGEST_SIZE]; /* server verify data */
222 uint8_t clientRandom[RANDOM_SIZE]; /* client random number */
223 uint8_t serverRandom[RANDOM_SIZE]; /* server random number */
224 uint32_t clientVerifyDataSize; /* client verify data size */
225 uint32_t serverVerifyDataSize; /* server verify data size */
226 uint32_t renegotiationNum; /* the number of renegotiation */
227 uint32_t certReqSendTime; /* certificate request sending times */
228 uint32_t tls13BasicKeyExMode; /* TLS13_KE_MODE_PSK_ONLY || TLS13_KE_MODE_PSK_WITH_DHE ||
229 TLS13_CERT_AUTH_WITH_DHE */
230
231 uint16_t negotiatedGroup; /* negotiated group */
232 uint16_t recordSizeLimit; /* read record size limit */
233 uint16_t renegoRecordSizeLimit;
234 uint16_t peerRecordSizeLimit; /* write record size limit */
235 bool isResume; /* whether to resume the session */
236 bool isRenegotiation; /* whether to renegotiate */
237
238 bool isSecureRenegotiation; /* whether security renegotiation */
239 bool isExtendedMasterSecret; /* whether to calculate the extended master sercret */
240 bool isEncryptThenMac; /* Whether to enable EncryptThenMac */
241 bool isEncryptThenMacRead; /* Whether to enable EncryptThenMacRead */
242 bool isEncryptThenMacWrite; /* Whether to enable EncryptThenMacWrite */
243 bool isTicket; /* whether to negotiate tickets, only below tls1.3 */
244 bool isSniStateOK; /* Whether server successfully processes the server_name callback */
245#ifdef HITLS_TLS_FEATURE_SNI
246 uint8_t *serverName;
247 uint32_t serverNameSize;
248#endif
250
251typedef struct {
252 uint16_t *groups; /* all groups sent by the peer end */
253 uint32_t groupsSize; /* size of a group */
254 uint16_t *cipherSuites; /* all cipher suites sent by the peer end */
255 uint16_t cipherSuitesSize; /* size of a cipher suites */
256 HITLS_SignHashAlgo peerSignHashAlg; /* peer signature algorithm */
257 uint16_t *signatureAlgorithms;
258 uint16_t signatureAlgorithmsSize;
259 HITLS_ERROR verifyResult; /* record the certificate verification result of the peer end */
260 HITLS_TrustedCAList *caList; /* peer trusted ca list */
261} PeerInfo;
262
263struct TlsCtx {
264 bool isClient; /* is Client */
265 bool userShutDown; /* record whether the local end invokes the HITLS_Close */
266 bool userRenego; /* record whether the local end initiates renegotiation */
267 uint8_t rwstate; /* record the current internal read and write state */
268 CM_State preState;
269 CM_State state;
270
271 uint32_t shutdownState; /* Record the shutdown state */
272
273 void *rUio; /* read uio */
274 void *uio; /* write uio */
275 void *bUio; /* Storing uio */
276 HS_Ctx *hsCtx; /* handshake context */
277 CCS_Ctx *ccsCtx; /* ChangeCipherSpec context */
278 ALERT_Ctx *alertCtx; /* alert context */
279 REC_Ctx *recCtx; /* record context */
280 struct {
281 IsRecvCcsCallback isRecvCCS;
282 SendCcsCallback sendCCS; /* send a CCS message */
283 CtrlCcsCallback ctrlCCS; /* controlling CCS */
284 SendAlertCallback sendAlert; /* set the alert message to be sent */
285 ClearAlertCallBack clearAlert; /* Clear the number of consecutive received warnings */
286 GetAlertFlagCallback getAlertFlag; /* get alert state */
287 UnexpectMsgHandleCallback unexpectedMsgProcessCb; /* the callback for unexpected messages */
288 } method;
289
290 PeerInfo peerInfo; /* Temporarily save the messages sent by the peer end */
291 TLS_CtxConfig config; /* private configuration */
292 TLS_Config *globalConfig; /* global configuration */
293 TLS_NegotiatedInfo negotiatedInfo; /* TLS negotiation information */
294 HITLS_Session *session; /* session information */
295
296 uint8_t clientAppTrafficSecret[MAX_DIGEST_SIZE]; /* TLS1.3 client app traffic secret */
297 uint8_t serverAppTrafficSecret[MAX_DIGEST_SIZE]; /* TLS1.3 server app traffic secret */
298 uint8_t resumptionMasterSecret[MAX_DIGEST_SIZE]; /* TLS1.3 session resume secret */
299 uint8_t exporterMasterSecret[MAX_DIGEST_SIZE]; /* TLS1.3 export the master secret */
300
301 uint32_t bytesLeftToRead; /* bytes left to read after hs header has parsed */
302 uint32_t keyUpdateType; /* TLS1.3 key update type */
303 bool isKeyUpdateRequest; /* TLS1.3 Check whether there are unsent key update messages */
304 bool haveClientPointFormats; /* whether the EC point format extension in the client hello is processed */
305 uint8_t peekFlag; /* peekFlag equals 0, read mode; otherwise, peek mode */
306 bool hasParsedHsMsgHeader; /* has parsed current hs msg header */
307 int32_t errorCode; /* Record the tls error code */
308
309 HITLS_HASH_Ctx *phaHash; /* tls1.3 pha: Handshake main process hash */
310 HITLS_HASH_Ctx *phaCurHash; /* tls1.3 pha: Temporarily store the current pha hash */
311 PHA_State phaState; /* tls1.3 pha state */
312 uint8_t *certificateReqCtx; /* tls1.3 pha certificate_request_context */
313 uint32_t certificateReqCtxSize; /* tls1.3 pha certificate_request_context */
314 bool isDtlsListen;
315 bool plainAlertForbid; /* tls1.3 forbid to receive plain alert message */
316 bool allowAppOut; /* whether user used HITLS_read to start renegotiation */
317 bool noQueryMtu; /* Don't query the mtu from bio */
318 bool needQueryMtu; /* whether need query mtu from bio */
319 bool mtuModified; /* whether mtu has been modified */
320 /* To reduce the calculation amount for determining timeout, use the end time instead of the start time. If the end
321 * time is exceeded, the receiving times out. */
322 BSL_TIME deadline; /* End time */
323};
324
325typedef struct {
326 uint8_t **buf; // &hsCtx->msgbuf
327 uint32_t *bufLen; // &hsCtx->bufferLen
328 uint32_t *bufOffset; // &hsCtx->msgLen
329} PackPacket;
330
331#define LIBCTX_FROM_CTX(ctx) (((ctx) == NULL) ? NULL : (ctx)->config.tlsConfig.libCtx)
332#define ATTRIBUTE_FROM_CTX(ctx) (((ctx) == NULL) ? NULL : (ctx)->config.tlsConfig.attrName)
333
334#define CUSTOM_EXT_FROM_CTX(ctx) (((ctx) == NULL) ? NULL : (ctx)->config.tlsConfig.customExts)
335
336#define GET_VERSION_FROM_CTX(ctx) \
337 ((ctx)->negotiatedInfo.version > 0 ? (ctx)->negotiatedInfo.version : (ctx)->config.tlsConfig.maxVersion)
338
339#ifdef __cplusplus
340}
341#endif
342
343#endif /* TLS_H */
HITLS_SignHashAlgo
Certificate Signature Algorithm Enumeration
定义 hitls_cert_type.h:177
struct BslList HITLS_TrustedCAList
Describes the list of trusted CAs
定义 hitls_cert_type.h:67
定义 alert.c:36
Basic time data structure definition.
定义 bsl_sal.h:583
定义 change_cipher_spec.c:32
定义 tls.h:204
定义 hs_ctx.h:152
定义 tls.h:325
定义 tls.h:251
定义 record.h:60
定义 tls.h:193
定义 tls.h:210
定义 tls.h:263