Fix memory leak in gsscon_connect()
[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 #include <netdb.h>
58
59 #include <gsscon.h>
60
61 /* ---------------------------------------------------------------------------
62  */
63
64 int gsscon_connect (const char *inHost, unsigned int inPort, const char *inServiceName, int *outFD, gss_ctx_id_t *outGSSContext)
65 {
66   int err = 0;
67   int fd = -1;
68   OM_uint32 majorStatus;
69   OM_uint32 minorStatus = 0, minorStatusToo = 0;
70   struct addrinfo *ai=NULL;
71   struct addrinfo *ai_head=NULL;
72   struct addrinfo hints={.ai_family=AF_UNSPEC, .ai_socktype=SOCK_STREAM, .ai_protocol=IPPROTO_TCP};
73   struct sockaddr_in saddr;
74   char *port=NULL;
75   gss_name_t serviceName = NULL;
76   gss_name_t clientName = NULL;
77   gss_cred_id_t clientCredentials = GSS_C_NO_CREDENTIAL;
78   gss_ctx_id_t gssContext = GSS_C_NO_CONTEXT;
79   OM_uint32 actualFlags = 0;
80   char *inputTokenBuffer = NULL;
81   size_t inputTokenBufferLength = 0;
82   gss_buffer_desc inputToken;  /* buffer received from the server */
83   gss_buffer_desc nameBuffer;
84   gss_buffer_t inputTokenPtr = GSS_C_NO_BUFFER;
85   char *name;
86   int len = 0;
87
88   if (!inServiceName) { err = EINVAL; }
89   if (!outGSSContext) { err = EINVAL; }
90     
91   if (!err) {
92     /* get a string for getaddrinfo */
93     if (asprintf(&port, "%d", inPort)>0) { 
94       err=getaddrinfo(inHost, port, &hints, &ai_head);
95       free(port);
96     } else
97       err=1;
98   }
99     
100   if (!err) {
101     /* try all options returned until one works */
102     for (ai=ai_head,fd=-1; (ai!=NULL) && (fd==-1); ai=ai->ai_next) {
103       fd=socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
104       if (fd < 0) {
105         fd=-1;
106         continue;
107       }
108
109       fprintf(stderr, "gss_connect: Connecting to host '%s' on port %d\n", inHost, inPort);
110       err=connect(fd, ai->ai_addr, ai->ai_addrlen);
111       if (err!=0) {
112         close(fd);
113         fd=-1;
114         continue;
115       }
116     }
117
118     if (fd==-1)
119       err=1;
120   }
121     
122   if (!err) {
123     *outFD = fd;
124     fd = -1; /* takes ownership */
125   } else {
126     gsscon_print_error (err, "OpenConnection failed");
127   }
128     
129   if (fd >= 0) { close (fd); }
130
131   if (!err) {
132     majorStatus = gss_acquire_cred (&minorStatus, clientName, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, 
133                                     GSS_C_INITIATE, &clientCredentials, NULL, NULL); 
134     if (majorStatus != GSS_S_COMPLETE) { 
135       gsscon_print_gss_errors ("gss_acquire_cred", majorStatus, minorStatus);
136       err = minorStatus ? minorStatus : majorStatus; 
137     }
138   }
139     
140   /*
141    * Here is where the client picks the service principal it will
142    * try to use to connect to the server.  In the case of the
143    * gssClientSample, the service principal is passed in on the
144    * command line, however, in a real world example, this would be
145    * unacceptable from a user interface standpoint since the user
146    * shouldn't need to know the server's service principal.
147    * 
148    * In traditional Kerberos setups, the service principal would be
149    * constructed from the type of the service (eg: "imap"), the DNS
150    * hostname of the server (eg: "mailserver.domain.com") and the
151    * client's local realm (eg: "DOMAIN.COM") to form a full
152    * principal string (eg: "imap/mailserver.domain.com@DOMAIN.COM").
153    *
154    * Now that many sites do not have DNS, this setup is becoming
155    * less common.  However you decide to generate the service
156    * principal, you need to adhere to the following constraint: The
157    * service principal must be constructed by the client, typed in
158    * by the user or administrator, or transmitted to the client in a
159    * secure manner from a trusted third party -- such as through an
160    * encrypted connection to a directory server.  You should not
161    * have the server send the client the service principal name as
162    * part of the authentication negotiation.
163    *
164    * The reason you can't let the server tell the client which
165    * principal to use is that many machines at a site will have
166    * their own service principal and keytab which identifies the
167    * machine -- in a Windows Active Directory environment all
168    * machines have a service principal and keytab.  Some of these
169    * machines (such as a financial services server) will be more
170    * trustworthy than others (such as a random machine on a
171    * coworker's desk).  If the owner of one of these untrustworthy
172    * machines can trick the client into using the untrustworthy
173    * machine's principal instead of the financial services server's
174    * principal, then he can trick the client into authenticating and
175    * connecting to the untrustworthy machine.  The untrustworthy
176    * machine can then harvest any confidential information the
177    * client sends to it, such as credit card information or social
178    * security numbers.
179    *
180    * If your protocol already involves sending the service principal
181    * as part of your authentication negotiation, your client should
182    * cache the name it gets after the first successful
183    * authentication so that the problem above can only happen on the
184    * first connection attempt -- similar to what ssh does with host
185    * keys.
186    */
187     
188   if (!err) {
189     len = asprintf(&name, "%s@%s", inServiceName, inHost);
190     if (len < 0) {
191       /* asprintf failed, pick an error to return... */
192       err = GSS_S_BAD_NAME;
193     } else {
194       nameBuffer.length = (size_t) len;
195       nameBuffer.value = name;
196
197       majorStatus = gss_import_name (&minorStatus, &nameBuffer, (gss_OID) GSS_C_NT_HOSTBASED_SERVICE, &serviceName);
198       if (majorStatus != GSS_S_COMPLETE) {
199         gsscon_print_gss_errors ("gss_import_name(inServiceName)", majorStatus, minorStatus);
200         err = minorStatus ? minorStatus : majorStatus;
201       }
202
203       /* free the input name and null pointers to avoid reuse */
204       free(name);
205       name = NULL;
206       nameBuffer.value = NULL;
207     }
208   }
209
210   /* 
211    * The main authentication loop:
212    *
213    * GSS is a multimechanism API.  Because the number of packet
214    * exchanges required to authenticate can vary between mechanisms,
215    * we need to loop calling gss_init_sec_context, passing the
216    * "input tokens" received from the server and send the resulting
217    * "output tokens" back until we get GSS_S_COMPLETE or an error.
218    */
219
220   majorStatus = GSS_S_CONTINUE_NEEDED;
221
222   gss_OID_desc EAP_OID = { 9, "\x2B\x06\x01\x05\x05\x0F\x01\x01\x11" };
223  
224   while (!err && (majorStatus != GSS_S_COMPLETE)) {
225     gss_buffer_desc outputToken = { 0, NULL }; /* buffer to send to the server */
226     OM_uint32 requestedFlags = (GSS_C_MUTUAL_FLAG | GSS_C_REPLAY_FLAG | GSS_C_SEQUENCE_FLAG | 
227                                 GSS_C_CONF_FLAG | GSS_C_INTEG_FLAG);
228         
229     majorStatus = gss_init_sec_context (&minorStatus, 
230                                         clientCredentials, 
231                                        &gssContext, 
232                                         serviceName, 
233                                        &EAP_OID /* mech_type */,
234                                         requestedFlags, 
235                                         GSS_C_INDEFINITE, 
236                                         GSS_C_NO_CHANNEL_BINDINGS, 
237                                         inputTokenPtr,
238                                         NULL /* actual_mech_type */, 
239                                        &outputToken, 
240                                        &actualFlags, 
241                                         NULL /* time_rec */);
242         
243     /* Send the output token to the server (even on error) */
244     if ((outputToken.length > 0) && (outputToken.value != NULL)) {
245       err = gsscon_write_token (*outFD, outputToken.value, outputToken.length);
246             
247       /* free the output token */
248       gss_release_buffer (&minorStatusToo, &outputToken);
249     }
250         
251     if (!err) {
252       if (majorStatus == GSS_S_CONTINUE_NEEDED) { 
253         /* Protocol requires another packet exchange */
254                 
255         /* Clean up old input buffer */
256         if (inputTokenBuffer) {
257           free (inputTokenBuffer);
258           inputTokenBuffer = NULL;  /* don't double-free */
259         }
260                 
261         /* Read another input token from the server */
262         err = gsscon_read_token (*outFD, &inputTokenBuffer, &inputTokenBufferLength);
263                 
264         if (!err) {
265           /* Set up input buffers for the next run through the loop */
266           inputToken.value = inputTokenBuffer;
267           inputToken.length = inputTokenBufferLength;
268           inputTokenPtr = &inputToken;
269         }
270       } else if (majorStatus != GSS_S_COMPLETE) {
271         gsscon_print_gss_errors ("gss_init_sec_context", majorStatus, minorStatus);
272         err = minorStatus ? minorStatus : majorStatus; 
273       }
274     }
275   }
276     
277   if (!err) { 
278     *outGSSContext = gssContext;
279     gssContext = NULL;
280   } else {
281     gsscon_print_error (err, "AuthenticateToServer failed"); 
282   }
283
284   if (inputTokenBuffer) { free (inputTokenBuffer); }
285   if (serviceName     ) { gss_release_name (&minorStatus, &serviceName); }
286   if (clientName      ) { gss_release_name (&minorStatus, &clientName); }
287   if (ai_head         ) { freeaddrinfo(ai_head); }
288
289   if (clientCredentials != GSS_C_NO_CREDENTIAL) { 
290     gss_release_cred (&minorStatus, &clientCredentials); }
291   if (gssContext != GSS_C_NO_CONTEXT) { 
292     gss_delete_sec_context (&minorStatus, &gssContext, GSS_C_NO_BUFFER); }
293
294   return err;
295 }
296