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