Remove debugging code.
[trust_router.git] / gsscon / gsscon_active.c
1 /*
2  * Copyright (c) 2012, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  * This code was adapted from the MIT Kerberos Consortium's
34  * GSS example code, which was distributed under the following
35  * license:
36  *
37  * Copyright 2004-2006 Massachusetts Institute of Technology.
38  * All Rights Reserved.
39  *
40  * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
41  * distribute this software and its documentation for any purpose and
42  * without fee is hereby granted, provided that the above copyright
43  * notice appear in all copies and that both that copyright notice and
44  * this permission notice appear in supporting documentation, and that
45  * the name of M.I.T. not be used in advertising or publicity pertaining
46  * to distribution of the software without specific, written prior
47  * permission.  Furthermore if you modify this software you must label
48  * your software as modified software and not distribute it in such a
49  * fashion that it might be confused with the original M.I.T. software.
50  * M.I.T. makes no representations about the suitability of
51  * this software for any purpose.  It is provided "as is" without express
52  * or implied warranty.
53  */
54
55 #include <stdio.h>
56 #include <stdlib.h>
57
58 #include <gsscon.h>
59
60 /* ---------------------------------------------------------------------------
61 */
62
63 int gsscon_connect (const char *inHost, unsigned int inPort, const char *inServiceName, int *outFD, gss_ctx_id_t *outGSSContext)
64 {
65     int err = 0;
66     int fd = -1;
67     OM_uint32 majorStatus;
68     OM_uint32 minorStatus = 0, minorStatusToo = 0;
69     struct hostent *hp = NULL;
70     struct sockaddr_in saddr;
71     gss_name_t serviceName = NULL;
72     gss_name_t clientName = NULL;
73     gss_cred_id_t clientCredentials = GSS_C_NO_CREDENTIAL;
74     gss_ctx_id_t gssContext = GSS_C_NO_CONTEXT;
75     OM_uint32 actualFlags = 0;
76     char *inputTokenBuffer = NULL;
77     size_t inputTokenBufferLength = 0;
78     gss_buffer_desc inputToken;  /* buffer received from the server */
79     gss_buffer_desc nameBuffer;
80     gss_buffer_t inputTokenPtr = GSS_C_NO_BUFFER;
81     char *name;
82
83     if (!inServiceName) { err = EINVAL; }
84     if (!outGSSContext) { err = EINVAL; }
85     
86     if (!err) {
87         hp = gethostbyname (inHost);
88         if (hp == NULL) { err = errno; }
89     }
90     
91     if (!err) {
92         saddr.sin_family = hp->h_addrtype;
93         memcpy ((char *) &saddr.sin_addr, hp->h_addr, sizeof (saddr.sin_addr));
94         saddr.sin_port = htons(inPort);
95         
96         fd = socket (AF_INET, SOCK_STREAM, 0);
97         if (fd < 0) { err = errno; }
98     }
99     
100     if (!err) {
101         fprintf (stderr, "gss_connect: Connecting to host '%s' on port %d\n", inHost, inPort);
102         err = connect (fd, (struct sockaddr *) &saddr, sizeof (saddr));
103         if (err < 0) { err = errno; }
104     }
105     
106     if (!err) {
107         *outFD = fd;
108         fd = -1; /* takes ownership */
109     } else {
110         gsscon_print_error (err, "OpenConnection failed");
111     }
112     
113     if (fd >= 0) { close (fd); }
114
115     if (!err) {
116       majorStatus = gss_acquire_cred (&minorStatus, clientName, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, 
117                                                 GSS_C_INITIATE, &clientCredentials, NULL, NULL); 
118       if (majorStatus != GSS_S_COMPLETE) { 
119         gsscon_print_gss_errors ("gss_acquire_cred", majorStatus, minorStatus);
120         err = minorStatus ? minorStatus : majorStatus; 
121       }
122     }
123     
124     /*
125      * Here is where the client picks the service principal it will
126      * try to use to connect to the server.  In the case of the
127      * gssClientSample, the service principal is passed in on the
128      * command line, however, in a real world example, this would be
129      * unacceptable from a user interface standpoint since the user
130      * shouldn't need to know the server's service principal.
131      * 
132      * In traditional Kerberos setups, the service principal would be
133      * constructed from the type of the service (eg: "imap"), the DNS
134      * hostname of the server (eg: "mailserver.domain.com") and the
135      * client's local realm (eg: "DOMAIN.COM") to form a full
136      * principal string (eg: "imap/mailserver.domain.com@DOMAIN.COM").
137      *
138      * Now that many sites do not have DNS, this setup is becoming
139      * less common.  However you decide to generate the service
140      * principal, you need to adhere to the following constraint: The
141      * service principal must be constructed by the client, typed in
142      * by the user or administrator, or transmitted to the client in a
143      * secure manner from a trusted third party -- such as through an
144      * encrypted connection to a directory server.  You should not
145      * have the server send the client the service principal name as
146      * part of the authentication negotiation.
147      *
148      * The reason you can't let the server tell the client which
149      * principal to use is that many machines at a site will have
150      * their own service principal and keytab which identifies the
151      * machine -- in a Windows Active Directory environment all
152      * machines have a service principal and keytab.  Some of these
153      * machines (such as a financial services server) will be more
154      * trustworthy than others (such as a random machine on a
155      * coworker's desk).  If the owner of one of these untrustworthy
156      * machines can trick the client into using the untrustworthy
157      * machine's principal instead of the financial services server's
158      * principal, then he can trick the client into authenticating and
159      * connecting to the untrustworthy machine.  The untrustworthy
160      * machine can then harvest any confidential information the
161      * client sends to it, such as credit card information or social
162      * security numbers.
163      *
164      * If your protocol already involves sending the service principal
165      * as part of your authentication negotiation, your client should
166      * cache the name it gets after the first successful
167      * authentication so that the problem above can only happen on the
168      * first connection attempt -- similar to what ssh does with host
169      * keys.
170      */
171     
172     if (!err) {
173       nameBuffer.length = asprintf(&name, "%s@%s", inServiceName, inHost);
174       nameBuffer.value = name;
175
176       majorStatus = gss_import_name (&minorStatus, &nameBuffer, (gss_OID) GSS_C_NT_HOSTBASED_SERVICE, &serviceName); 
177       if (majorStatus != GSS_S_COMPLETE) { 
178         gsscon_print_gss_errors ("gss_import_name(inServiceName)", majorStatus, minorStatus);
179         err = minorStatus ? minorStatus : majorStatus; 
180       }
181     }
182     
183     /* 
184      * The main authentication loop:
185      *
186      * GSS is a multimechanism API.  Because the number of packet
187      * exchanges required to authenticate can vary between mechanisms,
188      * we need to loop calling gss_init_sec_context, passing the
189      * "input tokens" received from the server and send the resulting
190      * "output tokens" back until we get GSS_S_COMPLETE or an error.
191      */
192
193     majorStatus = GSS_S_CONTINUE_NEEDED;
194
195     gss_OID_desc EAP_OID = { 9, "\x2B\x06\x01\x05\x05\x0F\x01\x01\x11" };
196  
197     while (!err && (majorStatus != GSS_S_COMPLETE)) {
198         gss_buffer_desc outputToken = { 0, NULL }; /* buffer to send to the server */
199         OM_uint32 requestedFlags = (GSS_C_MUTUAL_FLAG | GSS_C_REPLAY_FLAG | GSS_C_SEQUENCE_FLAG | 
200                                     GSS_C_CONF_FLAG | GSS_C_INTEG_FLAG);
201         
202         majorStatus = gss_init_sec_context (&minorStatus, 
203                                             clientCredentials, 
204                                             &gssContext, 
205                                             serviceName, 
206                                             &EAP_OID /* mech_type */,
207                                             requestedFlags, 
208                                             GSS_C_INDEFINITE, 
209                                             GSS_C_NO_CHANNEL_BINDINGS, 
210                                             inputTokenPtr,
211                                             NULL /* actual_mech_type */, 
212                                             &outputToken, 
213                                             &actualFlags, 
214                                             NULL /* time_rec */);
215         
216         /* Send the output token to the server (even on error) */
217         if ((outputToken.length > 0) && (outputToken.value != NULL)) {
218             err = gsscon_write_token (*outFD, outputToken.value, outputToken.length);
219             
220             /* free the output token */
221             gss_release_buffer (&minorStatusToo, &outputToken);
222         }
223         
224         if (!err) {
225             if (majorStatus == GSS_S_CONTINUE_NEEDED) { 
226                 /* Protocol requires another packet exchange */
227                 
228                 /* Clean up old input buffer */
229                 if (inputTokenBuffer) {
230                     free (inputTokenBuffer);
231                     inputTokenBuffer = NULL;  /* don't double-free */
232                 }
233                 
234                 /* Read another input token from the server */
235                 err = gsscon_read_token (*outFD, &inputTokenBuffer, &inputTokenBufferLength);
236                 
237                 if (!err) {
238                     /* Set up input buffers for the next run through the loop */
239                     inputToken.value = inputTokenBuffer;
240                     inputToken.length = inputTokenBufferLength;
241                     inputTokenPtr = &inputToken;
242                 }
243             } else if (majorStatus != GSS_S_COMPLETE) {
244                 gsscon_print_gss_errors ("gss_init_sec_context", majorStatus, minorStatus);
245                 err = minorStatus ? minorStatus : majorStatus; 
246             }
247         }
248     }
249     
250     if (!err) { 
251         *outGSSContext = gssContext;
252         gssContext = NULL;
253     } else {
254         gsscon_print_error (err, "AuthenticateToServer failed"); 
255     }
256
257     if (inputTokenBuffer) { free (inputTokenBuffer); }
258     if (serviceName     ) { gss_release_name (&minorStatus, &serviceName); }
259     if (clientName      ) { gss_release_name (&minorStatus, &clientName); }
260     
261     if (clientCredentials != GSS_C_NO_CREDENTIAL) { 
262         gss_release_cred (&minorStatus, &clientCredentials); }
263     if (gssContext != GSS_C_NO_CONTEXT) { 
264         gss_delete_sec_context (&minorStatus, &gssContext, GSS_C_NO_BUFFER); }
265
266     return err;
267 }
268