Further cleanup of tr_gss and usage for tids handling
[trust_router.git] / common / tr_gss.c
1 /*
2  * Copyright (c) 2018, 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  */
34
35 #include <talloc.h>
36 #include <gssapi.h>
37 #include <string.h>
38
39 #include <tr_msg.h>
40 #include <tr_debug.h>
41 #include <gsscon.h>
42 #include <tr_gss.h>
43
44 /**
45  * tr_gss.c - GSS connection handler
46  *
47  * The chief entry point to this module is tr_gss_handle_connection(). This
48  * function accepts an incoming socket connection, runs the GSS authorization
49  * and authentication process, accepts a request, processes it, then sends
50  * the reply and returns without closing the connection.
51  *
52  * Callers need to provide two callbacks, each with a cookie for passing
53  * custom data to the callback.
54  *
55  *   * TR_GSS_AUTH_FN auth_cb: Authorization callback
56  *     - This callback is used during the GSS auth process to determine whether
57  *       a credential should be authorized to connect.
58  *
59  *   * TR_GSS_HANDLE_REQ_FN req_cb: Request handler callback
60  *     - After auth, this callback is passed the string form of the incoming request.
61  *       It should process the request and return a string form of the outgoing
62  *       response, if any.
63  */
64
65 typedef struct tr_gss_cookie {
66   TR_GSS_AUTH_FN *auth_cb;
67   void *auth_cookie;
68 } TR_GSS_COOKIE;
69
70 static int tr_gss_auth_cb(gss_name_t clientName, gss_buffer_t displayName, void *data)
71 {
72   TR_GSS_COOKIE *cookie = talloc_get_type_abort(data, TR_GSS_COOKIE);
73   TR_NAME name ={(char *) displayName->value, (int) displayName->length};
74   int result=0;
75
76   if (cookie->auth_cb(clientName, &name, cookie->auth_cookie)) {
77     tr_debug("tr_gss_auth_cb: client '%.*s' denied authorization.", name.len, name.buf);
78     result=EACCES; /* denied */
79   }
80
81   return result;
82 }
83
84
85 /**
86  * Handle GSS authentication and authorization
87  *
88  * @param conn connection file descriptor
89  * @param acceptor_name name of acceptor to present to initiator
90  * @param acceptor_realm realm of acceptor to present to initiator
91  * @param gssctx GSS context
92  * @param auth_cb authorization callback
93  * @param auth_cookie generic data to pass to the authorization callback
94  * @return 0 on successful auth, 1 on disallowed auth, -1 on error
95  */
96 static int tr_gss_auth_connection(int conn,
97                                   const char *acceptor_name,
98                                   const char *acceptor_realm,
99                                   gss_ctx_id_t *gssctx,
100                                   TR_GSS_AUTH_FN auth_cb,
101                                   void *auth_cookie)
102 {
103   int rc = 0;
104   int auth, autherr = 0;
105   gss_buffer_desc nameBuffer = {0, NULL};
106   TR_GSS_COOKIE *cookie = NULL;
107
108   nameBuffer.value = talloc_asprintf(NULL, "%s@%s", acceptor_name, acceptor_realm);
109   if (nameBuffer.value == NULL) {
110     tr_err("tr_gss_auth_connection: Error allocating acceptor name.");
111     return -1;
112   }
113   nameBuffer.length = strlen(nameBuffer.value);
114
115   /* Set up for the auth callback. There are two layers of callbacks here: we
116    * use our own, which handles gsscon interfacing and calls the auth_cb parameter
117    * to do the actual auth. Store the auth_cb information in a metacookie. */
118   cookie = talloc(NULL, TR_GSS_COOKIE);
119   cookie->auth_cb=auth_cb;
120   cookie->auth_cookie=auth_cookie;
121
122   /* Now call gsscon with *our* auth callback and cookie */
123   rc = gsscon_passive_authenticate(conn, nameBuffer, gssctx, tr_gss_auth_cb, cookie);
124   talloc_free(cookie);
125   talloc_free(nameBuffer.value);
126   if (rc) {
127     tr_debug("tr_gss_auth_connection: Error from gsscon_passive_authenticate(), rc = %d.", rc);
128     return -1;
129   }
130
131   rc = gsscon_authorize(*gssctx, &auth, &autherr);
132   if (rc) {
133     tr_debug("tr_gss_auth_connection: Error from gsscon_authorize, rc = %d, autherr = %d.",
134              rc, autherr);
135     return -1;
136   }
137
138   if (auth)
139     tr_debug("tr_gss_auth_connection: Connection authenticated, conn = %d.", conn);
140   else
141     tr_debug("tr_gss_auth_connection: Authentication failed, conn %d.", conn);
142
143   return !auth;
144 }
145
146 /**
147  * Read a request from the GSS connection
148  *
149  * @param mem_ctx talloc context for the result
150  * @param conn file descriptor for the connection
151  * @param gssctx GSS context
152  * @return talloc'ed string containing the request, or null on error
153  */
154 static char *tr_gss_read_req(TALLOC_CTX *mem_ctx, int conn, gss_ctx_id_t gssctx)
155 {
156   int err;
157   char *retval = NULL;
158   char *buf = NULL;
159   size_t buflen = 0;
160
161   err = gsscon_read_encrypted_token(conn, gssctx, &buf, &buflen);
162   if (err || (buf == NULL)) {
163     if (buf)
164       free(buf);
165     tr_debug("tr_gss_read_req: Error reading from connection, rc=%d", err);
166     return NULL;
167   }
168
169   tr_debug("tr_gss_read_req: Read %u bytes.", (unsigned) buflen);
170
171   // get a talloc'ed version, guaranteed to have a null termination
172   retval = talloc_asprintf(mem_ctx, "%.*s", (int) buflen, buf);
173   free(buf);
174
175   return retval;
176 }
177
178 /**
179  * Write a response to the GSS connection
180  *
181  * @param conn file descriptor for the connection
182  * @param gssctx GSS context
183  * @param resp encoded response string to send
184  * @return 0 on success, -1 on error
185  */
186 static int tr_gss_write_resp(int conn, gss_ctx_id_t gssctx, const char *resp)
187 {
188   int err = 0;
189
190   /* Send the response over the connection */
191   err = gsscon_write_encrypted_token (conn, gssctx, resp, strlen(resp) + 1);
192   if (err) {
193     tr_debug("tr_gss_send_response: Error sending response over connection, rc=%d.", err);
194     return -1;
195   }
196   return 0;
197 }
198
199 /**
200  * Handle a request/response connection
201  *
202  * Authorizes/authenticates the connection, then reads a response, passes that to a
203  * callback to get a response, sends that, then returns.
204  *
205  * @param conn connection file descriptor
206  * @param acceptor_name acceptor name to present
207  * @param acceptor_realm acceptor realm to present
208  * @param auth_cb callback for authorization
209  * @param auth_cookie cookie for the auth_cb
210  * @param req_cb callback to handle the request and produce the response
211  * @param req_cookie cookie for the req_cb
212  */
213 void tr_gss_handle_connection(int conn,
214                               const char *acceptor_name,
215                               const char *acceptor_realm,
216                               TR_GSS_AUTH_FN auth_cb,
217                               void *auth_cookie,
218                               TR_GSS_HANDLE_REQ_FN req_cb,
219                               void *req_cookie)
220 {
221   TALLOC_CTX *tmp_ctx = talloc_new(NULL);
222   gss_ctx_id_t gssctx = GSS_C_NO_CONTEXT;
223   char *req_str = NULL;
224   char *resp_str = NULL;
225
226   if (tr_gss_auth_connection(conn,
227                              acceptor_name,
228                              acceptor_realm,
229                              &gssctx,
230                              auth_cb,
231                              auth_cookie)) {
232     tr_notice("tr_gss_handle_connection: Error authorizing connection.");
233     goto cleanup;
234   }
235
236   tr_debug("tr_gss_handle_connection: Connection authorized");
237
238   // TODO: should there be a timeout on this?
239   while (1) {   /* continue until an error breaks us out */
240     // try to read a request
241     req_str = tr_gss_read_req(tmp_ctx, conn, gssctx);
242
243     if ( req_str == NULL) {
244       // an error occurred, give up
245       tr_notice("tr_gss_handle_connection: Error reading request");
246       goto cleanup;
247     } else if (strlen(req_str) > 0) {
248       // we got a request message, exit the loop and process it
249       break;
250     }
251
252     // no error, but no message, keep waiting for one
253     talloc_free(req_str); // this would be cleaned up anyway, but may as well free it
254   }
255
256   /* Hand off the request for processing and get the response */
257   resp_str = req_cb(tmp_ctx, req_str, req_cookie);
258
259   if (resp_str == NULL) {
260     // no response, clean up
261     goto cleanup;
262   }
263
264   // send the response
265   if (tr_gss_write_resp(conn, gssctx, resp_str)) {
266     tr_notice("tr_gss_handle_connection: Error writing response");
267   }
268
269 cleanup:
270   talloc_free(tmp_ctx);
271 }