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