2 * Copyright (c) 2008-2013 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
25 * Trivial SSL server example, using SecureTransport / OS X version.
27 * Written by Doug Mitchell.
29 #include <Security/SecureTransport.h>
30 #include <Security/SecureTransportPriv.h>
31 #include "sslAppUtils.h"
33 #include "utilities/fileIo.h"
35 #include <Security/SecBase.h>
42 #include <sys/param.h>
44 #include <Security/Security.h>
45 #include <Security/SecCertificatePriv.h>
47 #include <CoreFoundation/CoreFoundation.h>
48 #include "SecurityTool/print_cert.h"
51 #include <securityd/spi.h>
54 /* Set true when PR-3074739 is merged to TOT */
55 #define SET_DH_PARAMS_ENABLE 1
57 /* true when using SSLCopyPeerCertificates() per Radar 3311892 */
58 #define USE_COPY_PEER_CERTS 1
61 * Defaults, overridable by user.
63 #define SERVER_MESSAGE "HTTP/1.0 200 OK\015\012Content-Type: text/html\015\012\015\012" \
64 "<HTML><HEAD><TITLE>SecureTransport Test Server</TITLE></HEAD>" \
65 "<BODY><H2>Secure connection established.</H2>" \
66 "Message from the 'sslServer' sample application.\015\012</BODY>" \
69 /* For ease of debugging, pick a non-privileged port */
70 #define DEFAULT_PORT 1200
71 // #define DEFAULT_PORT 443
73 #define DEFAULT_HOST "localhost"
75 #define DEFAULT_KC "certkc"
77 static void usage(char **argv
)
79 printf("Usage: %s [option ...]\n", argv
[0]);
81 printf(" P=port Port to listen on; default is %d\n", DEFAULT_PORT
);
82 printf(" k=keychain Contains server cert and keys.\n");
83 printf(" y=keychain Encryption-only cert and keys.\n");
84 printf(" e Allow Expired Certs\n");
85 printf(" r Allow any root cert\n");
86 printf(" E Allow Expired Roots\n");
87 printf(" x Disable Cert Verification\n");
88 printf(" f=fileBase Write Peer Certs to fileBase*\n");
89 printf(" c Display peer certs\n");
90 printf(" d Display received data\n");
91 printf(" C=cipherSuite (e=40-bit d=DES D=40-bit DES 3=3DES 4=RC4 $=40-bit RC4\n"
92 " 2=RC2 a=AES128 A=AES256 h=DH H=Anon DH r=DHE/RSA s=DH/DSS\n"
94 printf(" 2 SSLv2 only (default is best fit)\n");
95 printf(" 3 SSLv3 only (default is best fit)\n");
96 printf(" t TLSv1 only (default is best fit)\n");
97 printf(" o TLSv1, SSLv3 use kSSLProtocol__X__Only\n");
98 printf(" g={prot...} Specify legal protocols; prot = any combo of [23t]\n");
99 printf(" T=[nrsj] Verify client cert state = "
100 "none/requested/sent/rejected\n");
101 printf(" R Disable resumable session support\n");
102 printf(" i=timeout Session cache timeout\n");
103 printf(" u=[nat] Authentication: n=never; a=always; t=try\n");
104 printf(" b Non-blocking I/O\n");
105 printf(" a fileNmae Add fileName to list of trusted roots\n");
106 printf(" A fileName fileName is ONLY trusted root\n");
107 printf(" U filename Add filename to acceptable DNList (multiple times OK)\n");
108 printf(" D filename Diffie-Hellman parameters from filename\n");
109 printf(" z=password Unlock server keychain with password.\n");
110 printf(" H Do SecIndentityRef search instead of specific keychain\n");
111 printf(" M Complete cert chain (default assumes that our identity is root)\n");
112 printf(" 4 Disable anonymous ciphers\n");
113 printf(" p Pause after each phase\n");
114 printf(" l[=loops] Loop, performing multiple transactions\n");
115 printf(" q Quiet/diagnostic mode (site names and errors only)\n");
120 /* snag a copy of current connection's peer certs so we can
121 * examine them later after the connection is closed */
122 static OSStatus
copyPeerCerts(
124 CFArrayRef
*peerCerts
) // mallocd & RETURNED
126 #if USE_COPY_PEER_CERTS
127 OSStatus ortn
= SSLCopyPeerCertificates(ctx
, peerCerts
);
129 OSStatus ortn
= SSLGetPeerCertificates(ctx
, peerCerts
);
132 printf("***Error obtaining peer certs: %s\n",
133 sslGetSSLErrString(ortn
));
138 /* free the cert array obtained via SSLGetPeerCertificates() */
139 static void freePeerCerts(
140 CFArrayRef peerCerts
)
142 if(peerCerts
== NULL
) {
146 #if USE_COPY_PEER_CERTS
148 /* Voila! Problem fixed. */
149 CFRelease(peerCerts
);
155 SecCertificateRef certData
;
158 numCerts
= CFArrayGetCount(peerCerts
);
159 for(i
=0; i
<numCerts
; i
++) {
160 certData
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
163 CFRelease(peerCerts
);
167 /* print reply received from server */
168 static void dumpAscii(
172 char *cp
= (char *)rcvBuf
;
176 for(i
=0; i
<len
; i
++) {
189 if(isprint(c
) && (c
!= '\n')) {
193 printf("<%02X>", ((unsigned)c
) & 0xff);
202 static void doPause(const char *prompt
) {
204 printf("%s. ", prompt
);
207 printf("Continue (n/anything)? ");
215 * Perform one SSL diagnostic server-side session. Returns nonzero on error.
216 * Normally no output to stdout except initial "waiting for connection" message,
217 * unless there is a really screwed up error (i.e., something not directly related
218 * to the SSL connection).
220 #define RCV_BUF_SIZE 256
222 static OSStatus
sslServe(
224 unsigned short portNum
,
225 SSLProtocol tryVersion
, // only used if acceptedProts NULL
226 const char *acceptedProts
,
227 CFArrayRef serverCerts
, // required
228 char *password
, // optional
231 bool allowExpiredRoot
,
232 bool disableCertVerify
,
235 char cipherRestrict
, // '2', 'd'. etc...'\0' for no
237 SSLAuthenticate authenticate
,
238 unsigned char *dhParams
, // optional D-H parameters
239 unsigned dhParamsLen
,
240 CFArrayRef acceptableDNList
, // optional
241 bool resumableEnable
,
242 uint32_t sessionCacheTimeout
,// optional
243 bool disableAnonCiphers
,
244 bool silent
, // no stdout
246 SSLProtocol
*negVersion
, // RETURNED
247 SSLCipherSuite
*negCipher
, // RETURNED
248 SSLClientCertificateState
*certState
, // RETURNED
249 Boolean
*sessionWasResumed
, // RETURNED
250 unsigned char *sessionID
, // mallocd by caller, RETURNED
251 size_t *sessionIDLength
, // RETURNED
252 CFArrayRef
*peerCerts
, // mallocd & RETURNED
258 SSLContextRef ctx
= NULL
;
260 uint8_t rcvBuf
[RCV_BUF_SIZE
];
261 const char *outMsg
= SERVER_MESSAGE
;
263 *negVersion
= kSSLProtocolUnknown
;
264 *negCipher
= SSL_NULL_WITH_NULL_NULL
;
268 signal(SIGPIPE
, sigpipe
);
271 /* first wait for a connection */
273 printf("Waiting for client connection on port %u...", portNum
);
276 ortn
= AcceptClientConnection(listenSock
, &acceptSock
, &peerId
);
278 printf("AcceptClientConnection returned %d; aborting\n", (int)ortn
);
283 * Set up a SecureTransport session.
284 * First the standard calls.
286 ortn
= SSLNewContext(true, &ctx
);
288 printSslErrStr("SSLNewContext", ortn
);
291 ortn
= SSLSetIOFuncs(ctx
, SocketRead
, SocketWrite
);
293 printSslErrStr("SSLSetIOFuncs", ortn
);
296 ortn
= SSLSetConnection(ctx
, (SSLConnectionRef
)(intptr_t)acceptSock
);
298 printSslErrStr("SSLSetConnection", ortn
);
302 /* have to do these options befor setting server certs */
304 ortn
= SSLSetAllowsExpiredCerts(ctx
, true);
306 printSslErrStr("SSLSetAllowExpiredCerts", ortn
);
311 ortn
= SSLSetAllowsAnyRoot(ctx
, true);
313 printSslErrStr("SSLSetAllowAnyRoot", ortn
);
319 ortn
= sslAddTrustedRoot(ctx
, anchorFile
, replaceAnchors
);
321 printf("***Error obtaining anchor file %s\n", anchorFile
);
325 if(serverCerts
!= NULL
) {
326 if(anchorFile
== NULL
) {
327 /* no specific anchors, so assume we want to trust this one */
328 ortn
= addIdentityAsTrustedRoot(ctx
, serverCerts
);
333 ortn
= SSLSetCertificate(ctx
, serverCerts
);
335 printSslErrStr("SSLSetCertificate", ortn
);
339 if(allowExpiredRoot
) {
340 ortn
= SSLSetAllowsExpiredRoots(ctx
, true);
342 printSslErrStr("SSLSetAllowsExpiredRoots", ortn
);
346 if(disableCertVerify
) {
347 ortn
= SSLSetEnableCertVerify(ctx
, false);
349 printSslErrStr("SSLSetEnableCertVerify", ortn
);
355 * SecureTransport options.
358 ortn
= SSLSetProtocolVersionEnabled(ctx
, kSSLProtocolAll
, false);
360 printSslErrStr("SSLSetProtocolVersionEnabled(all off)", ortn
);
363 for(const char *cp
= acceptedProts
; *cp
; cp
++) {
364 SSLProtocol prot
= kSSLProtocolUnknown
;
367 prot
= kSSLProtocol2
;
370 prot
= kSSLProtocol3
;
373 prot
= kTLSProtocol1
;
378 ortn
= SSLSetProtocolVersionEnabled(ctx
, prot
, true);
380 printSslErrStr("SSLSetProtocolVersionEnabled", ortn
);
386 ortn
= SSLSetProtocolVersion(ctx
, tryVersion
);
388 printSslErrStr("SSLSetProtocolVersion", ortn
);
392 if(resumableEnable
) {
393 ortn
= SSLSetPeerID(ctx
, &peerId
, sizeof(PeerSpec
));
395 printSslErrStr("SSLSetPeerID", ortn
);
399 if(cipherRestrict
!= '\0') {
400 ortn
= sslSetCipherRestrictions(ctx
, cipherRestrict
);
405 if(authenticate
!= kNeverAuthenticate
) {
406 ortn
= SSLSetClientSideAuthenticate(ctx
, authenticate
);
408 printSslErrStr("SSLSetClientSideAuthenticate", ortn
);
413 ortn
= SSLSetDiffieHellmanParams(ctx
, dhParams
, dhParamsLen
);
415 printSslErrStr("SSLSetDiffieHellmanParams", ortn
);
419 if(sessionCacheTimeout
) {
420 ortn
= SSLSetSessionCacheTimeout(ctx
, sessionCacheTimeout
);
422 printSslErrStr("SSLSetSessionCacheTimeout", ortn
);
426 if(disableAnonCiphers
) {
427 ortn
= SSLSetAllowAnonymousCiphers(ctx
, false);
429 printSslErrStr("SSLSetAllowAnonymousCiphers", ortn
);
432 /* quickie test of the getter */
434 ortn
= SSLGetAllowAnonymousCiphers(ctx
, &e
);
436 printSslErrStr("SSLGetAllowAnonymousCiphers", ortn
);
440 printf("***SSLGetAllowAnonymousCiphers() returned true; expected false\n");
446 if(acceptableDNList) {
447 ortn = SSLSetCertificateAuthorities(ctx, acceptableDNList, TRUE);
449 printSslErrStr("SSLSetCertificateAuthorities", ortn);
457 doPause("SSLContext initialized");
460 /* Perform SSL/TLS handshake */
462 { ortn
= SSLHandshake(ctx
);
463 if((ortn
== errSSLWouldBlock
) && !silent
) {
464 /* keep UI responsive */
467 } while (ortn
== errSSLWouldBlock
);
469 /* this works even if handshake failed due to cert chain invalid */
470 copyPeerCerts(ctx
, peerCerts
);
472 SSLGetClientCertificateState(ctx
, certState
);
473 SSLGetNegotiatedCipher(ctx
, negCipher
);
474 SSLGetNegotiatedProtocolVersion(ctx
, negVersion
);
475 *sessionIDLength
= MAX_SESSION_ID_LENGTH
;
476 ortn
= SSLGetResumableSessionInfo(ctx
, sessionWasResumed
, sessionID
, sessionIDLength
);
485 doPause("SSLContext handshake complete");
488 /* wait for one complete line or user says they've had enough */
489 while(ortn
== errSecSuccess
) {
490 length
= sizeof(rcvBuf
);
491 ortn
= SSLRead(ctx
, rcvBuf
, length
, &length
);
493 /* keep UI responsive */
497 /* print what we have */
498 printf("client request: ");
499 dumpAscii(rcvBuf
, length
);
502 /* allow user to bail */
506 printf("\nMore client request (y/anything): ");
513 /* poor person's line completion scan */
514 for(unsigned i
=0; i
<length
; i
++) {
515 if((rcvBuf
[i
] == '\n') || (rcvBuf
[i
] == '\r')) {
516 /* a labelled break would be nice here.... */
520 if (ortn
== errSSLWouldBlock
) {
521 ortn
= errSecSuccess
;
527 doPause("Client GET msg received");
530 /* send out canned response */
531 length
= strlen(outMsg
);
532 ortn
= SSLWrite(ctx
, outMsg
, length
, &length
);
534 printSslErrStr("SSLWrite", ortn
);
537 doPause("Server response sent");
541 * always do close, even on error - to flush outgoing write queue
543 OSStatus cerr
= SSLClose(ctx
);
544 if(ortn
== errSecSuccess
) {
548 endpointShutdown(acceptSock
);
551 SSLDisposeContext(ctx
);
553 /* FIXME - dispose of serverCerts */
557 static void showPeerCerts(
558 CFArrayRef peerCerts
,
562 SecCertificateRef certRef
;
565 if(peerCerts
== NULL
) {
568 numCerts
= CFArrayGetCount(peerCerts
);
569 for(i
=0; i
<numCerts
; i
++) {
570 certRef
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
571 printf("\n================== Server Cert %lu ===================\n\n", i
);
572 print_cert(certRef
, verbose
);
573 printf("\n=============== End of Server Cert %lu ===============\n", i
);
577 static void writePeerCerts(
578 CFArrayRef peerCerts
,
579 const char *fileBase
)
582 SecCertificateRef certRef
;
586 if(peerCerts
== NULL
) {
589 numCerts
= CFArrayGetCount(peerCerts
);
590 for(i
=0; i
<numCerts
; i
++) {
591 sprintf(fileName
, "%s%02d.cer", fileBase
, (int)i
);
592 certRef
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
593 writeFileSizet(fileName
, SecCertificateGetBytePtr(certRef
),
594 SecCertificateGetLength(certRef
));
596 printf("...wrote %lu certs to fileBase %s\n", numCerts
, fileBase
);
599 static void showSSLResult(
600 SSLProtocol tryVersion
,
603 SSLProtocol negVersion
,
604 SSLCipherSuite negCipher
,
605 Boolean sessionWasResumed
,
606 unsigned char *sessionID
,
607 size_t sessionIDLength
,
608 CFArrayRef peerCerts
,
609 bool displayPeerCerts
,
610 SSLClientCertificateState certState
,
611 char *fileBase
) // non-NULL: write certs to file
613 CFIndex numPeerCerts
;
617 printf(" Allowed SSL versions : %s\n", acceptedProts
);
620 printf(" Attempted SSL version : %s\n",
621 sslGetProtocolVersionString(tryVersion
));
623 printf(" Result : %s\n", sslGetSSLErrString(err
));
624 printf(" Negotiated SSL version : %s\n",
625 sslGetProtocolVersionString(negVersion
));
626 printf(" Negotiated CipherSuite : %s\n",
627 sslGetCipherSuiteString(negCipher
));
628 if(certState
!= kSSLClientCertNone
) {
629 printf(" Client Cert State : %s\n",
630 sslGetClientCertStateString(certState
));
632 printf(" Resumed Session : ");
633 if(sessionWasResumed
) {
634 for(unsigned dex
=0; dex
<sessionIDLength
; dex
++) {
635 printf("%02X ", sessionID
[dex
]);
636 if(((dex
% 8) == 7) && (dex
!= (sessionIDLength
- 1))) {
643 printf("NOT RESUMED\n");
645 if(peerCerts
== NULL
) {
649 numPeerCerts
= CFArrayGetCount(peerCerts
);
651 printf(" Number of peer certs : %lu\n", numPeerCerts
);
652 if(numPeerCerts
!= 0) {
653 if(displayPeerCerts
) {
654 showPeerCerts(peerCerts
, false);
656 if(fileBase
!= NULL
) {
657 writePeerCerts(peerCerts
, fileBase
);
663 static int verifyClientCertState(
664 bool verifyCertState
,
665 SSLClientCertificateState expectState
,
666 SSLClientCertificateState gotState
)
668 if(!verifyCertState
) {
671 if(expectState
== gotState
) {
674 printf("***Expected clientCertState %s; got %s\n",
675 sslGetClientCertStateString(expectState
),
676 sslGetClientCertStateString(gotState
));
680 int main(int argc
, char **argv
)
684 char fullFileBase
[100];
685 SSLProtocol negVersion
;
686 SSLCipherSuite negCipher
;
687 Boolean sessionWasResumed
;
688 unsigned char sessionID
[MAX_SESSION_ID_LENGTH
];
689 size_t sessionIDLength
;
690 CFArrayRef peerCerts
= NULL
;
693 CFArrayRef serverCerts
= nil
; // required
694 SecKeychainRef serverKc
= nil
;
697 SSLClientCertificateState certState
; // obtained from sslServe
699 /* user-spec'd parameters */
700 unsigned short portNum
= DEFAULT_PORT
;
701 bool allowExpired
= false;
702 bool allowAnyRoot
= false;
703 char *fileBase
= NULL
;
704 bool displayCerts
= false;
705 char cipherRestrict
= '\0';
706 SSLProtocol attemptProt
= kTLSProtocol1
;
707 bool protXOnly
= false; // kSSLProtocol3Only,
709 char *acceptedProts
= NULL
; // "23t" ==> SSLSetProtocolVersionEnabled
711 bool resumableEnable
= true;
713 char *keyChainName
= NULL
;
715 SSLAuthenticate authenticate
= kNeverAuthenticate
;
716 bool nonBlocking
= false;
717 bool allowExpiredRoot
= false;
718 bool disableCertVerify
= false;
719 char *anchorFile
= NULL
;
720 bool replaceAnchors
= false;
721 bool vfyCertState
= false;
722 SSLClientCertificateState expectCertState
= kSSLClientCertNone
;
723 char *password
= NULL
;
724 char *dhParamsFile
= NULL
;
725 unsigned char *dhParams
= NULL
;
726 unsigned dhParamsLen
= 0;
727 bool doIdSearch
= false;
728 bool completeCertChain
= false;
729 uint32_t sessionCacheTimeout
= 0;
730 bool disableAnonCiphers
= false;
731 CFMutableArrayRef acceptableDNList
= NULL
;
733 for(arg
=1; arg
<argc
; arg
++) {
737 portNum
= atoi(&argp
[2]);
740 keyChainName
= &argp
[2];
746 allowExpiredRoot
= true;
749 disableCertVerify
= true;
753 /* requires another arg */
756 anchorFile
= argv
[arg
];
760 /* requires another arg */
763 anchorFile
= argv
[arg
];
764 replaceAnchors
= true;
773 expectCertState
= kSSLClientCertNone
;
776 expectCertState
= kSSLClientCertRequested
;
779 expectCertState
= kSSLClientCertSent
;
782 expectCertState
= kSSLClientCertRejected
;
800 cipherRestrict
= argp
[2];
803 attemptProt
= kSSLProtocol2
;
806 attemptProt
= kSSLProtocol3
;
809 attemptProt
= kTLSProtocol1
;
818 acceptedProts
= &argp
[2];
821 resumableEnable
= false;
831 case 'a': authenticate
= kAlwaysAuthenticate
; break;
832 case 'n': authenticate
= kNeverAuthenticate
; break;
833 case 't': authenticate
= kTryAuthenticate
; break;
834 default: usage(argv
);
839 /* requires another arg */
842 dhParamsFile
= argv
[arg
];
851 completeCertChain
= true;
854 sessionCacheTimeout
= atoi(&argp
[2]);
857 disableAnonCiphers
= true;
868 /* requires another arg */
871 if(cspReadFile(argv
[arg
], &caCert
, &caCertLen
)) {
872 printf("***Error reading file %s. Aborting.\n", argv
[arg
]);
875 if(acceptableDNList
== NULL
) {
876 acceptableDNList
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
878 certData
.Data
= caCert
;
879 certData
.Length
= caCertLen
;
880 ortn
= SecCertificateCreateFromData(&certData
,
882 CSSM_CERT_ENCODING_DER
,
885 cssmPerror("SecCertificateCreateFromData", ortn
);
888 CFArrayAppendValue(acceptableDNList
, secCert
);
893 if(argp
[1] == '\0') {
894 /* no loop count --> loop forever */
898 else if(argp
[1] != '=') {
901 loops
= atoi(&argp
[2]);
910 securityd_init(NULL
);
914 /* get server cert and optional encryption cert as CFArrayRef */
916 serverCerts
= getSslCerts(keyChainName
, false, completeCertChain
,
917 anchorFile
, &serverKc
);
918 if(serverCerts
== nil
) {
925 OSStatus ortn
= sslIdentityPicker(NULL
, anchorFile
, true, NULL
, &serverCerts
);
927 printf("***IdentitySearch failure; aborting.\n");
932 OSStatus ortn
= SecKeychainUnlock(serverKc
, strlen(password
), password
, true);
934 printf("SecKeychainUnlock returned %d\n", (int)ortn
);
942 switch(attemptProt
) {
944 attemptProt
= kTLSProtocol1Only
;
947 attemptProt
= kSSLProtocol3Only
;
955 int r
= cspReadFile(dhParamsFile
, &dhParams
, &dhParamsLen
);
957 printf("***Error reading diffie-hellman params from %s; aborting\n",
965 /* one-time only server port setup */
966 err
= ListenForClients(portNum
, nonBlocking
, &listenSock
);
968 printf("ListenForClients returned %d; aborting\n", (int)err
);
972 for(loopNum
=1; ; loopNum
++) {
973 err
= sslServe(listenSock
,
1007 SSLProtocol tryProt
= attemptProt
;
1008 showSSLResult(tryProt
,
1019 fileBase
? fullFileBase
: NULL
);
1021 errCount
+= verifyClientCertState(vfyCertState
, expectCertState
,
1023 freePeerCerts(peerCerts
);
1024 if(loops
&& (loopNum
== loops
)) {
1029 endpointShutdown(listenSock
);
1032 CFRelease(serverKc
);