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