9cf069532809369d18a69a13c679aef9beb49710
[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_C_NT_HOSTBASED_SERVICE, &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
195 /* --------------------------------------------------------------------------- */
196
197 static int ClientPrincipalIsAuthorizedForService (const char *inClientPrincipal)
198 {
199     int err = 0;
200         /* 
201          * Here is where the server checks to see if the client principal should 
202          * be allowed to use your service. Typically it should check both the name 
203          * and the realm, since with cross-realm shared keys, a user at another 
204          * realm may be trying to contact your service.  
205          */
206         err = 0;
207
208     
209     
210     return err;
211 }
212
213 /* --------------------------------------------------------------------------- */
214
215 int gsscon_authorize (gss_ctx_id_t  inContext, 
216                       int          *outAuthorized, 
217                       int          *outAuthorizationError)
218 {
219     int err = 0;
220     OM_uint32 majorStatus;
221     OM_uint32 minorStatus = 0;
222     gss_name_t clientName = NULL;
223     gss_name_t serviceName = NULL;
224     char *clientPrincipal = NULL;
225     char *servicePrincipal = NULL;
226
227     if (!inContext            ) { err = EINVAL; }
228     if (!outAuthorized        ) { err = EINVAL; }
229     if (!outAuthorizationError) { err = EINVAL; }
230     
231     if (!err) {
232         /* Get the client and service principals used to authenticate */
233         majorStatus = gss_inquire_context (&minorStatus, 
234                                            inContext, 
235                                            &clientName, 
236                                            &serviceName, 
237                                            NULL, NULL, NULL, NULL, NULL);
238         if (majorStatus != GSS_S_COMPLETE) { 
239             err = minorStatus ? minorStatus : majorStatus; 
240         }
241     }
242     
243     if (!err) {
244         /* Pull the client principal string out of the gss name */
245         gss_buffer_desc nameToken;
246         
247         majorStatus = gss_display_name (&minorStatus, 
248                                         clientName, 
249                                         &nameToken, 
250                                         NULL);
251         if (majorStatus != GSS_S_COMPLETE) { 
252             err = minorStatus ? minorStatus : majorStatus; 
253         }
254         
255         if (!err) {
256             clientPrincipal = malloc (nameToken.length + 1);
257             if (clientPrincipal == NULL) { err = ENOMEM; }
258         }
259         
260         if (!err) {
261             memcpy (clientPrincipal, nameToken.value, nameToken.length);
262             clientPrincipal[nameToken.length] = '\0';
263         }        
264
265         if (nameToken.value) { gss_release_buffer (&minorStatus, &nameToken); }
266     }
267     
268         if (!err) {
269     //    /* Pull the service principal string out of the gss name */
270     //    gss_buffer_desc nameToken;
271     //    
272     //    majorStatus = gss_display_name (&minorStatus, 
273     //                                    serviceName, 
274     //                                    &nameToken, 
275     //                                    NULL);
276     //    if (majorStatus != GSS_S_COMPLETE) { 
277     //        err = minorStatus ? minorStatus : majorStatus; 
278     //    }
279     //    
280     //    if (!err) {
281     //        servic7ePrincipal = malloc (nameToken.length + 1);
282     //        if (servicePrincipal == NULL) { err = ENOMEM; }
283     //    }
284     //    
285     //    if (!err) {
286     //        memcpy (servicePrincipal, nameToken.value, nameToken.length);
287     //        servicePrincipal[nameToken.length] = '\0';
288     //    }        
289
290     //    if (nameToken.value) { gss_release_buffer (&minorStatus, &nameToken); }
291     // }
292     
293
294           int authorizationErr = 0;
295           authorizationErr = ClientPrincipalIsAuthorizedForService (clientPrincipal);
296
297
298         
299 //        printf ("'%s' is%s authorized for service '%s'\n", 
300 //                clientPrincipal, authorizationErr ? " NOT" : "", servicePrincipal);            
301 //        
302           *outAuthorized = !authorizationErr;
303           *outAuthorizationError = authorizationErr;
304         }
305     
306     if (serviceName     ) { gss_release_name (&minorStatus, &serviceName); }
307     if (clientName      ) { gss_release_name (&minorStatus, &clientName); }
308     if (clientPrincipal ) { free (clientPrincipal); }
309     if (servicePrincipal) { free (servicePrincipal); }
310
311     return err; 
312 }
313
314