Changes to add realm name (from config) to end of service name for passive authentica...
[trust_router.git] / gsscon / gsscon_passive.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 const char *gServiceName = NULL;
58
59 int gsscon_passive_authenticate (int           inSocket, 
60                                  gss_buffer_desc inNameBuffer,
61                                  gss_name_t inServiceName,
62                                  gss_ctx_id_t *outGSSContext,
63                                  client_cb_fn clientCb,
64                                  void *clientCbData)
65 {
66     int err = 0;
67     OM_uint32 majorStatus;
68     OM_uint32 minorStatus = 0;
69     gss_ctx_id_t gssContext = GSS_C_NO_CONTEXT;
70     gss_name_t clientName = GSS_C_NO_NAME;
71     gss_cred_id_t acceptorCredentials = NULL;
72     gss_buffer_desc clientDisplayName = {0, NULL};
73     char *inputTokenBuffer = NULL;
74     size_t inputTokenBufferLength = 0;
75     gss_buffer_desc inputToken;  /* buffer received from the server */
76     
77     if (inSocket <  0 ) { err = EINVAL; }
78     if (!outGSSContext) { err = EINVAL; }
79
80     if (!err)
81       majorStatus = gss_import_name (&minorStatus, &inNameBuffer, (gss_OID) GSS_KRB5_NT_PRINCIPAL_NAME, &inServiceName); 
82     if (majorStatus != GSS_S_COMPLETE) {
83         gsscon_print_gss_errors ("gss_import_name(inServiceName)", majorStatus, minorStatus);
84         err = minorStatus ? minorStatus : majorStatus; 
85       }
86
87     if (!err) {
88       majorStatus = gss_acquire_cred ( &minorStatus, inServiceName,
89                                        GSS_C_INDEFINITE, GSS_C_NO_OID_SET,
90                                        GSS_C_ACCEPT, &acceptorCredentials,
91                                        NULL /*mechs out*/, NULL /*time out*/);
92       if (majorStatus != GSS_S_COMPLETE) { 
93         gsscon_print_gss_errors ("gss_acquire_cred", majorStatus, minorStatus);
94         err = minorStatus ? minorStatus : majorStatus; 
95       }
96     }
97
98     /* 
99      * The main authentication loop:
100      *
101      * GSS is a multimechanism API.  The number of packet exchanges required to  
102      * authenticatevaries between mechanisms.  As a result, we need to loop reading 
103      * input tokens from the client, calling gss_accept_sec_context on the input 
104      * tokens and send the resulting output tokens back to the client until we 
105      * get GSS_S_COMPLETE or an error.
106      *
107      * When we are done, save the client principal so we can make authorization 
108      * checks.
109      */
110     
111     majorStatus = GSS_S_CONTINUE_NEEDED;
112     while (!err && (majorStatus != GSS_S_COMPLETE)) {
113         /* Clean up old input buffer */
114         if (inputTokenBuffer != NULL) {
115             free (inputTokenBuffer);
116             inputTokenBuffer = NULL;  /* don't double-free */
117         }
118         
119         err = gsscon_read_token (inSocket, &inputTokenBuffer, &inputTokenBufferLength);
120         
121         if (!err) {
122             /* Set up input buffers for the next run through the loop */
123             inputToken.value = inputTokenBuffer;
124             inputToken.length = inputTokenBufferLength;
125         }
126         
127         if (!err) {
128             /* buffer to send to the server */
129             gss_buffer_desc outputToken = { 0, NULL }; 
130             
131             /*
132              * accept_sec_context does the actual work of taking the client's 
133              * request and generating an appropriate reply.              */
134             majorStatus = gss_accept_sec_context (&minorStatus, 
135                                                   &gssContext, 
136                                                   acceptorCredentials,
137                                                   &inputToken, 
138                                                   GSS_C_NO_CHANNEL_BINDINGS, 
139                                                   &clientName,
140                                                   NULL /* actual_mech_type */,
141                                                   &outputToken, 
142                                                   NULL /* req_flags */, 
143                                                   NULL /* time_rec */, 
144                                                   NULL /* delegated_cred_handle */);
145             
146             if ((outputToken.length > 0) && (outputToken.value != NULL)) {
147                 /* Send the output token to the client (even on error) */
148                 err = gsscon_write_token (inSocket, outputToken.value, outputToken.length);
149                 
150                 /* free the output token */
151                 gss_release_buffer (&minorStatus, &outputToken);
152             }
153         }
154         
155         if ((majorStatus != GSS_S_COMPLETE) && (majorStatus != GSS_S_CONTINUE_NEEDED)) {
156             gsscon_print_gss_errors ("gss_accept_sec_context", majorStatus, minorStatus);
157             err = minorStatus ? minorStatus : majorStatus; 
158         }            
159     }
160
161     if (!err) {
162       majorStatus = gss_display_name(&minorStatus, clientName, &clientDisplayName, NULL);
163       if (GSS_ERROR(majorStatus)) {
164         gsscon_print_gss_errors("gss_display_name", majorStatus, minorStatus);
165         err = EINVAL;
166       }
167       if (!err)
168         err = clientCb(clientName, &clientDisplayName, clientCbData);
169     }
170
171     if (!err) { 
172         *outGSSContext = gssContext;
173         gssContext = NULL;
174     } else {
175         gsscon_print_error (err, "Authenticate failed");
176     }
177     
178     if (inputTokenBuffer) { free (inputTokenBuffer); }
179     if (gssContext != GSS_C_NO_CONTEXT) { 
180         gss_delete_sec_context (&minorStatus, &gssContext, GSS_C_NO_BUFFER); }
181 if (clientName != GSS_C_NO_NAME)
182   gss_release_name(&minorStatus, &clientName);
183 if (clientDisplayName.value != NULL)
184   gss_release_buffer(&minorStatus, &clientDisplayName);
185  gss_release_name( &minorStatus, &inServiceName);
186  gss_release_cred( &minorStatus, &acceptorCredentials);
187         
188     return err;
189 }
190
191 /* --------------------------------------------------------------------------- */
192
193 static int ServicePrincipalIsValidForService (const char *inServicePrincipal)
194 {
195     int err = 0;
196     krb5_context context = NULL;
197     krb5_principal principal = NULL;
198     
199     if (!inServicePrincipal) { err = EINVAL; }
200     
201     if (!err) {
202         err = krb5_init_context (&context);
203     }
204     
205     if (!err) {
206         err = krb5_parse_name (context, inServicePrincipal, &principal);
207     }
208     
209     if (!err) {
210         /* 
211          * Here is where we check to see if the service principal the client 
212          * used is valid.  Typically we would just check that the first component 
213          * is the name of the service provided by the server.  This check exists
214          * to make sure the server is using the correct key in its keytab since
215          * we passed GSS_C_NO_CREDENTIAL into gss_accept_sec_context().
216          */
217         if (gServiceName && strcmp (gServiceName, 
218                                     krb5_princ_name (context, principal)->data) != 0) {
219             err = KRB5KRB_AP_WRONG_PRINC;
220         }
221     }
222     
223     if (principal) { krb5_free_principal (context, principal); }
224     if (context  ) { krb5_free_context (context); }
225     
226     return err;
227 }
228
229
230 /* --------------------------------------------------------------------------- */
231
232 static int ClientPrincipalIsAuthorizedForService (const char *inClientPrincipal)
233 {
234     int err = 0;
235         /* 
236          * Here is where the server checks to see if the client principal should 
237          * be allowed to use your service. Typically it should check both the name 
238          * and the realm, since with cross-realm shared keys, a user at another 
239          * realm may be trying to contact your service.  
240          */
241         err = 0;
242
243     
244     
245     return err;
246 }
247
248 /* --------------------------------------------------------------------------- */
249
250 int gsscon_authorize (gss_ctx_id_t  inContext, 
251                       int          *outAuthorized, 
252                       int          *outAuthorizationError)
253 {
254     int err = 0;
255     OM_uint32 majorStatus;
256     OM_uint32 minorStatus = 0;
257     gss_name_t clientName = NULL;
258     gss_name_t serviceName = NULL;
259     char *clientPrincipal = NULL;
260     char *servicePrincipal = NULL;
261
262     if (!inContext            ) { err = EINVAL; }
263     if (!outAuthorized        ) { err = EINVAL; }
264     if (!outAuthorizationError) { err = EINVAL; }
265     
266     if (!err) {
267         /* Get the client and service principals used to authenticate */
268         majorStatus = gss_inquire_context (&minorStatus, 
269                                            inContext, 
270                                            &clientName, 
271                                            &serviceName, 
272                                            NULL, NULL, NULL, NULL, NULL);
273         if (majorStatus != GSS_S_COMPLETE) { 
274             err = minorStatus ? minorStatus : majorStatus; 
275         }
276     }
277     
278     if (!err) {
279         /* Pull the client principal string out of the gss name */
280         gss_buffer_desc nameToken;
281         
282         majorStatus = gss_display_name (&minorStatus, 
283                                         clientName, 
284                                         &nameToken, 
285                                         NULL);
286         if (majorStatus != GSS_S_COMPLETE) { 
287             err = minorStatus ? minorStatus : majorStatus; 
288         }
289         
290         if (!err) {
291             clientPrincipal = malloc (nameToken.length + 1);
292             if (clientPrincipal == NULL) { err = ENOMEM; }
293         }
294         
295         if (!err) {
296             memcpy (clientPrincipal, nameToken.value, nameToken.length);
297             clientPrincipal[nameToken.length] = '\0';
298         }        
299
300         if (nameToken.value) { gss_release_buffer (&minorStatus, &nameToken); }
301     }
302     
303         if (!err) {
304     //    /* Pull the service principal string out of the gss name */
305     //    gss_buffer_desc nameToken;
306     //    
307     //    majorStatus = gss_display_name (&minorStatus, 
308     //                                    serviceName, 
309     //                                    &nameToken, 
310     //                                    NULL);
311     //    if (majorStatus != GSS_S_COMPLETE) { 
312     //        err = minorStatus ? minorStatus : majorStatus; 
313     //    }
314     //    
315     //    if (!err) {
316     //        servic7ePrincipal = malloc (nameToken.length + 1);
317     //        if (servicePrincipal == NULL) { err = ENOMEM; }
318     //    }
319     //    
320     //    if (!err) {
321     //        memcpy (servicePrincipal, nameToken.value, nameToken.length);
322     //        servicePrincipal[nameToken.length] = '\0';
323     //    }        
324
325     //    if (nameToken.value) { gss_release_buffer (&minorStatus, &nameToken); }
326     // }
327     
328 //    if (!err) {
329 //        int authorizationErr = ServicePrincipalIsValidForService (servicePr// incipal);
330 //        
331 //        if (!authorizationErr) {
332
333           int authorizationErr = 0;
334           authorizationErr = ClientPrincipalIsAuthorizedForService (clientPrincipal);
335
336 //        }
337         
338 //        printf ("'%s' is%s authorized for service '%s'\n", 
339 //                clientPrincipal, authorizationErr ? " NOT" : "", servicePrincipal);            
340 //        
341           *outAuthorized = !authorizationErr;
342           *outAuthorizationError = authorizationErr;
343         }
344     
345     if (serviceName     ) { gss_release_name (&minorStatus, &serviceName); }
346     if (clientName      ) { gss_release_name (&minorStatus, &clientName); }
347     if (clientPrincipal ) { free (clientPrincipal); }
348     if (servicePrincipal) { free (servicePrincipal); }
349
350     return err; 
351 }
352
353