1/*
2 * Copyright (c) 1999-2001,2005-2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24/*
25 * sslContext.h - Private SSL typedefs: SSLContext and its components
26 */
27
28#ifndef _SSLCONTEXT_H_
29#define _SSLCONTEXT_H_ 1
30
31#include "SecureTransport.h"
32#include "sslBuildFlags.h"
33
34#include <tls_handshake.h>
35#include <tls_record.h>
36#include <tls_stream_parser.h>
37
38#ifdef USE_CDSA_CRYPTO
39#include <Security/cssmtype.h>
40#else
41#if TARGET_OS_IPHONE
42#include <Security/SecDH.h>
43#include <Security/SecKeyInternal.h>
44#else
45#include "../sec/Security/SecDH.h"  // hack to get SecDH.
46// typedef struct OpaqueSecDHContext *SecDHContext;
47#endif
48#include <corecrypto/ccec.h>
49#endif
50
51#include <CoreFoundation/CFRuntime.h>
52#include <AssertMacros.h>
53
54#include "sslPriv.h"
55#include "tls_ssl.h"
56#include "sslDigests.h"
57#include "sslRecord.h"
58#include "cipherSpecs.h"
59
60#include <dispatch/dispatch.h>
61
62#ifdef __cplusplus
63extern "C" {
64#endif
65
66typedef struct
67{   SSLReadFunc         read;
68    SSLWriteFunc        write;
69    SSLConnectionRef   	ioRef;
70} IOContext;
71
72//FIXME should not need this.
73typedef enum
74{
75    SSL_HdskStateUninit = 0,			/* No Handshake yet */
76    SSL_HdskStatePending,               /* Handshake in Progress */
77    SSL_HdskStateReady,                 /* Handshake is done */
78    SSL_HdskStateGracefulClose,
79    SSL_HdskStateErrorClose,
80    SSL_HdskStateNoNotifyClose,			/* server disconnected with no
81                                         *   notify msg */
82} SSLHandshakeState;
83
84#define SSLChangeHdskState(ctx, newState) { ctx->state=newState; }
85
86struct SSLContext
87{
88	CFRuntimeBase		_base;
89    IOContext           ioCtx;
90
91
92    const struct SSLRecordFuncs *recFuncs;
93    SSLRecordContextRef recCtx;
94
95    tls_handshake_t hdsk;
96
97    int readCipher_ready;
98    int writeCipher_ready;
99
100    SSLHandshakeState   state;
101
102	/*
103	 * Prior to successful protocol negotiation, negProtocolVersion
104	 * is SSL_Version_Undetermined. Subsequent to successful
105	 * negotiation, negProtocolVersion contains the actual over-the-wire
106	 * protocol value.
107	 *
108	 * The Boolean versionEnable flags are set by
109	 * SSLSetProtocolVersionEnabled or SSLSetProtocolVersion and
110	 * remain invariant once negotiation has started. If there
111	 * were a large number of these and/or we were adding new
112	 * protocol versions on a regular basis, we'd probably want
113	 * to implement these as a word of flags. For now, in the
114	 * real world, this is the most straightforward implementation.
115	 */
116    SSLProtocolVersion  negProtocolVersion;	/* negotiated */
117    SSLProtocolVersion  clientReqProtocol;	/* requested by client in hello msg */
118    SSLProtocolVersion  minProtocolVersion;
119    SSLProtocolVersion  maxProtocolVersion;
120    Boolean             isDTLS;             /* if this is a Datagram Context */
121    SSLProtocolSide     protocolSide;		/* ConnectionEnd enum { server, client } in rfc5246. */
122
123    SSLBuffer           dtlsCookie;         /* DTLS ClientHello cookie */
124
125
126    uint16_t            selectedCipher;			/* currently selected */
127
128
129    tls_private_key_t   signingPrivKeyRef;  /* our private signing key */
130
131    tls_private_key_t   encryptPrivKeyRef;  /* our private encrypt key, for
132                                              * server-initiated key exchange */
133
134
135    /* Server DH Parameters */
136    SSLBuffer			dhParamsEncoded;	/* PKCS3 encoded blob - prime + generator */
137
138    /*
139  	 * Various cert chains.
140  	 * For all three, the root is the last in the chain.
141  	 */
142	SSLCertificate      *localCert;
143    SSLCertificate      *encryptCert;
144    CFArrayRef          peerCert;
145
146	/*
147	 * The arrays we are given via SSLSetCertificate() and SSLSetEncryptionCertificate().
148	 * We keep them here, refcounted, solely for the associated getters.
149	 */
150	CFArrayRef			localCertArray;
151	CFArrayRef			encryptCertArray;
152
153	/* peer certs as SecTrustRef */
154	SecTrustRef			peerSecTrust;
155
156    CFMutableArrayRef   trustedCerts;
157    Boolean             trustedCertsOnly;
158
159    /*
160     * trusted leaf certs as specified in SSLSetTrustedLeafCertificates()
161     */
162    CFArrayRef			trustedLeafCerts;
163
164	Boolean					allowExpiredCerts;
165	Boolean					allowExpiredRoots;
166	Boolean					enableCertVerify;
167
168    SSLBuffer		    sessionID;
169    SSLBuffer			peerID;
170    SSLBuffer			resumableSession;       /* We keep a copy for now - but eventually this should go away if we get refcounted SSLBuffers */
171
172    uint16_t            *validCipherSuites;		/* context's valid suites */
173    unsigned            numValidCipherSuites;	/* size of validCipherSuites */
174
175
176    uint16_t            *ecdhCurves;
177    unsigned            ecdhNumCurves;
178
179	/* server-side only */
180    SSLAuthenticate		clientAuth;				/* kNeverAuthenticate, etc. */
181    //Boolean				tryClientAuth;
182
183	/* client and server */
184	SSLClientCertificateState	clientCertState;
185
186    DNListElem          *acceptableDNList;		/* client and server */
187	CFMutableArrayRef	acceptableCAs;			/* server only - SecCertificateRefs */
188
189    bool                certRequested;
190    bool                certSent;
191    bool                certReceived;
192    bool                x509Requested;
193
194    unsigned            sessionMatch;
195
196
197	/* Transport layer fields */
198    SSLBuffer			receivedDataBuffer;
199    size_t              receivedDataPos;
200
201	Boolean				allowAnyRoot;		// don't require known roots
202	Boolean				sentFatalAlert;		// this session terminated by fatal alert
203	Boolean				rsaBlindingEnable;
204	Boolean				oneByteRecordEnable;    /* enable 1/n-1 data splitting for TLSv1 and SSLv3 */
205
206	/* optional session cache timeout (in seconds) override - 0 means default */
207	uint32_t 			sessionCacheTimeout;
208
209	/* optional SessionTicket */
210	SSLBuffer			sessionTicket;
211
212	/* optional callback to obtain master secret, with its opaque arg */
213	SSLInternalMasterSecretFunction	masterSecretCallback;
214	const void 			*masterSecretArg;
215
216	#if 	SSL_PAC_SERVER_ENABLE
217	/* server PAC resume sets serverRandom early to allow for secret acquisition */
218	uint8_t				serverRandomValid;
219	#endif
220
221	Boolean				anonCipherEnable;
222
223	/* optional switches to enable additional returns from SSLHandshake */
224    Boolean             breakOnServerAuth;
225    Boolean             breakOnCertRequest;
226    Boolean             breakOnClientAuth;
227    Boolean             signalServerAuth;
228    Boolean             signalCertRequest;
229    Boolean             signalClientAuth;
230
231	/* true iff ECDSA/ECDH ciphers are configured */
232	Boolean				ecdsaEnable;
233
234    /* List of peer-specified supported_signature_algorithms */
235	unsigned					 numPeerSigAlgs;
236	const tls_signature_and_hash_algorithm *peerSigAlgs;
237
238	/* List of server-specified client auth types */
239	unsigned					numAuthTypes;
240	const tls_client_auth_type *clientAuthTypes;
241
242	/* client auth type actually negotiated */
243	tls_client_auth_type	negAuthType;
244
245    /* Timeout for DTLS retransmit */
246    CFAbsoluteTime      timeout_deadline;
247    CFAbsoluteTime      timeout_duration;
248    size_t              mtu;
249
250    /* RFC 5746: Secure renegotiation */
251    Boolean             secure_renegotiation;
252    Boolean             secure_renegotiation_received;
253    SSLBuffer           ownVerifyData;
254    SSLBuffer           peerVerifyData;
255
256    /* RFC 4279: TLS PSK */
257    SSLBuffer           pskSharedSecret;
258    SSLBuffer           pskIdentity;
259
260    /* TLS False Start */
261    Boolean             falseStartEnabled; //FalseStart enabled (by API call)
262    /* Fallback behavior */
263    Boolean             fallbackEnabled; // Fallback behavior enabled.
264    /* NPN */
265    SSLNPNFunc      npnFunc;
266    void            *npnFuncInfo;
267};
268
269OSStatus SSLUpdateNegotiatedClientAuthType(SSLContextRef ctx);
270
271Boolean sslIsSessionActive(const SSLContext *ctx);
272
273static inline bool sslVersionIsLikeTls12(SSLContext *ctx)
274{
275    check(ctx->negProtocolVersion!=SSL_Version_Undetermined);
276    return ctx->isDTLS ? ctx->negProtocolVersion > DTLS_Version_1_0 : ctx->negProtocolVersion >= TLS_Version_1_2;
277}
278
279/* This is implemented in tls_callbacks.c */
280    int sslGetSessionID(SSLContext *myCtx, SSLBuffer *sessionID);
281
282#ifdef __cplusplus
283}
284#endif
285
286#endif /* _SSLCONTEXT_H_ */
287