s4:torture: Adapt KDC canon test to Heimdal upstream changes
[samba.git] / third_party / heimdal / appl / test / http_client.c
1 /*
2  * Copyright (c) 2003 - 2005 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #include "test_locl.h"
35 #include <gssapi/gssapi.h>
36 #include <gssapi/gssapi_krb5.h>
37 #include <gssapi/gssapi_spnego.h>
38 #include "gss_common.h"
39 #include <base64.h>
40
41 RCSID("$Id$");
42
43 /*
44  * A simplistic client implementing draft-brezak-spnego-http-04.txt
45  */
46
47 static int
48 do_connect (const char *hostname, const char *port)
49 {
50     struct addrinfo *ai, *a;
51     struct addrinfo hints;
52     int error;
53     int s = -1;
54
55     memset (&hints, 0, sizeof(hints));
56     hints.ai_family = PF_UNSPEC;
57     hints.ai_socktype = SOCK_STREAM;
58     hints.ai_protocol = 0;
59
60     error = getaddrinfo (hostname, port, &hints, &ai);
61     if (error)
62         errx (1, "getaddrinfo(%s): %s", hostname, gai_strerror(error));
63
64     for (a = ai; a != NULL; a = a->ai_next) {
65         s = socket (a->ai_family, a->ai_socktype, a->ai_protocol);
66         if (s < 0)
67             continue;
68         if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
69             warn ("connect(%s)", hostname);
70             close (s);
71             continue;
72         }
73         break;
74     }
75     freeaddrinfo (ai);
76     if (a == NULL)
77         errx (1, "failed to contact %s", hostname);
78
79     return s;
80 }
81
82 static void
83 fdprintf(int s, const char *fmt, ...)
84 {
85     size_t len;
86     ssize_t ret;
87     va_list ap;
88     char *str, *buf;
89
90     va_start(ap, fmt);
91     vasprintf(&str, fmt, ap);
92     va_end(ap);
93
94     if (str == NULL)
95         errx(1, "vasprintf");
96
97     buf = str;
98     len = strlen(buf);
99     while (len) {
100         ret = write(s, buf, len);
101         if (ret == 0)
102             err(1, "connection closed");
103         else if (ret < 0)
104             err(1, "error");
105         len -= ret;
106         buf += ret;
107     }
108     free(str);
109 }
110
111 static int help_flag;
112 static int version_flag;
113 static int verbose_flag;
114 static int mutual_flag = 1;
115 static int delegate_flag;
116 static char *port_str = "http";
117 static char *gss_service = "HTTP";
118
119 static struct getargs http_args[] = {
120     { "verbose", 'v', arg_flag, &verbose_flag, "verbose logging", NULL },
121     { "port", 'p', arg_string, &port_str, "port to connect to", "port" },
122     { "delegate", 0, arg_flag, &delegate_flag, "gssapi delegate credential",
123       NULL },
124     { "gss-service", 's', arg_string, &gss_service, "gssapi service to use",
125       "service" },
126     { "mech", 'm', arg_string, &mech, "gssapi mech to use", "mech" },
127     { "mutual", 0, arg_negative_flag, &mutual_flag, "no gssapi mutual auth",
128       NULL },
129     { "help", 'h', arg_flag, &help_flag, NULL, NULL },
130     { "version", 0, arg_flag, &version_flag, NULL, NULL }
131 };
132
133 static int num_http_args = sizeof(http_args) / sizeof(http_args[0]);
134
135 static void
136 usage(int code)
137 {
138     arg_printusage(http_args, num_http_args, NULL, "host [page]");
139     exit(code);
140 }
141
142 /*
143  *
144  */
145
146 struct http_req {
147     char *response;
148     char **headers;
149     int num_headers;
150     void *body;
151     size_t body_size;
152 };
153
154
155 static void
156 http_req_zero(struct http_req *req)
157 {
158     req->response = NULL;
159     req->headers = NULL;
160     req->num_headers = 0;
161     req->body = NULL;
162     req->body_size = 0;
163 }
164
165 static void
166 http_req_free(struct http_req *req)
167 {
168     int i;
169
170     free(req->response);
171     for (i = 0; i < req->num_headers; i++)
172         free(req->headers[i]);
173     free(req->headers);
174     free(req->body);
175     http_req_zero(req);
176 }
177
178 static const char *
179 http_find_header(struct http_req *req, const char *header)
180 {
181     int i, len = strlen(header);
182
183     for (i = 0; i < req->num_headers; i++) {
184         if (strncasecmp(header, req->headers[i], len) == 0) {
185             return req->headers[i] + len + 1;
186         }
187     }
188     return NULL;
189 }
190
191
192 static int
193 http_query(const char *host, const char *page,
194            char **headers, struct http_req *req)
195 {
196     enum { RESPONSE, HEADER, BODY } state;
197     ssize_t ret;
198     char in_buf[1024], *in_ptr = in_buf;
199     size_t in_len = 0;
200     int s, i;
201
202     http_req_zero(req);
203
204     s = do_connect(host, port_str);
205     if (s < 0)
206         errx(1, "connection failed");
207
208     fdprintf(s, "GET %s HTTP/1.0\r\n", page);
209     for (i = 0; headers[i]; i++)
210         fdprintf(s, "%s\r\n", headers[i]);
211     fdprintf(s, "Host: %s\r\n\r\n", host);
212
213     state = RESPONSE;
214
215     while (1) {
216         ret = read (s, in_ptr, sizeof(in_buf) - in_len - 1);
217         if (ret == 0)
218             break;
219         else if (ret < 0)
220             err (1, "read: %lu", (unsigned long)ret);
221
222         in_buf[ret + in_len] = '\0';
223
224         if (state == HEADER || state == RESPONSE) {
225             char *p;
226
227             in_len += ret;
228             in_ptr += ret;
229
230             while (1) {
231                 p = strstr(in_buf, "\r\n");
232
233                 if (p == NULL) {
234                     break;
235                 } else if (p == in_buf) {
236                     memmove(in_buf, in_buf + 2, sizeof(in_buf) - 2);
237                     state = BODY;
238                     in_len -= 2;
239                     in_ptr -= 2;
240                     break;
241                 } else if (state == RESPONSE) {
242                     req->response = emalloc(p - in_buf + 1);
243                     memcpy(req->response, in_buf, p - in_buf);
244                     req->response[p - in_buf] = '\0';
245                     state = HEADER;
246                 } else {
247                     req->headers = realloc(req->headers,
248                                            (req->num_headers + 1) * sizeof(req->headers[0]));
249                     req->headers[req->num_headers] = emalloc(p - in_buf + 1);
250                     memcpy(req->headers[req->num_headers], in_buf, p - in_buf);
251                     req->headers[req->num_headers][p - in_buf] = '\0';
252                     if (req->headers[req->num_headers] == NULL)
253                         errx(1, "strdup");
254                     req->num_headers++;
255                 }
256                 memmove(in_buf, p + 2, sizeof(in_buf) - (p - in_buf) - 2);
257                 in_len -= (p - in_buf) + 2;
258                 in_ptr -= (p - in_buf) + 2;
259             }
260         }
261
262         if (state == BODY) {
263
264             req->body = erealloc(req->body, req->body_size + ret + 1);
265
266             memcpy((char *)req->body + req->body_size, in_buf, ret);
267             req->body_size += ret;
268             ((char *)req->body)[req->body_size] = '\0';
269
270             in_ptr = in_buf;
271             in_len = 0;
272         } else
273             abort();
274     }
275
276     if (verbose_flag) {
277         int i;
278         printf("response: %s\n", req->response);
279         for (i = 0; i < req->num_headers; i++)
280             printf("header[%d] %s\n", i, req->headers[i]);
281         printf("body: %.*s\n", (int)req->body_size, (char *)req->body);
282     }
283
284     close(s);
285     return 0;
286 }
287
288
289 int
290 main(int argc, char **argv)
291 {
292     struct http_req req;
293     const char *host, *page;
294     int i, done, print_body, gssapi_done, gssapi_started;
295     char *headers[10] = { 0 };
296     int num_headers = 0;
297     gss_ctx_id_t context_hdl = GSS_C_NO_CONTEXT;
298     gss_name_t server = GSS_C_NO_NAME;
299     int optind = 0;
300     gss_OID mech_oid;
301     OM_uint32 flags;
302
303     setprogname(argv[0]);
304
305     if(getarg(http_args, num_http_args, argc, argv, &optind))
306         usage(1);
307
308     if (help_flag)
309         usage (0);
310
311     if(version_flag) {
312         print_version(NULL);
313         exit(0);
314     }
315
316     argc -= optind;
317     argv += optind;
318
319     mech_oid = select_mech(mech);
320
321     if (argc != 1 && argc != 2)
322         errx(1, "usage: %s host [page]", getprogname());
323     host = argv[0];
324     if (argc == 2)
325         page = argv[1];
326     else
327         page = "/";
328
329     flags = 0;
330     if (delegate_flag)
331         flags |= GSS_C_DELEG_FLAG;
332     if (mutual_flag)
333         flags |= GSS_C_MUTUAL_FLAG;
334
335     done = 0;
336     num_headers = 0;
337     gssapi_done = 1;
338     gssapi_started = 0;
339     do {
340         print_body = 0;
341
342         http_query(host, page, headers, &req);
343         for (i = 0 ; headers[i]; i++) {
344             free(headers[i]);
345             headers[i] = NULL;
346         }
347         num_headers = 0;
348
349         if (strstr(req.response, " 200 ") != NULL) {
350             print_body = 1;
351             done = 1;
352         } else if (strstr(req.response, " 401 ") != NULL) {
353             if (http_find_header(&req, "WWW-Authenticate:") == NULL)
354                 errx(1, "Got %s but missed `WWW-Authenticate'", req.response);
355             gssapi_done = 0;
356         }
357
358         if (!gssapi_done) {
359             const char *h = http_find_header(&req, "WWW-Authenticate:");
360             if (h == NULL)
361                 errx(1, "Got %s but missed `WWW-Authenticate'", req.response);
362
363             if (strncasecmp(h, "Negotiate", 9) == 0) {
364                 OM_uint32 maj_stat, min_stat;
365                 gss_buffer_desc input_token, output_token;
366
367                 if (verbose_flag)
368                     printf("Negotiate found\n");
369
370                 if (server == GSS_C_NO_NAME) {
371                     char *name;
372                     asprintf(&name, "%s@%s", gss_service, host);
373                     input_token.length = strlen(name);
374                     input_token.value = name;
375
376                     maj_stat = gss_import_name(&min_stat,
377                                                &input_token,
378                                                GSS_C_NT_HOSTBASED_SERVICE,
379                                                &server);
380                     if (GSS_ERROR(maj_stat))
381                         gss_err (1, min_stat, "gss_inport_name");
382                     free(name);
383                     input_token.length = 0;
384                     input_token.value = NULL;
385                 }
386
387                 i = 9;
388                 while(h[i] && isspace((unsigned char)h[i]))
389                     i++;
390                 if (h[i] != '\0') {
391                     int len = strlen(&h[i]);
392                     if (len == 0)
393                         errx(1, "invalid Negotiate token");
394                     input_token.value = emalloc(len);
395                     len = rk_base64_decode(&h[i], input_token.value);
396                     if (len < 0)
397                         errx(1, "invalid base64 Negotiate token %s", &h[i]);
398                     input_token.length = len;
399                 } else {
400                     if (gssapi_started)
401                         errx(1, "Negotiate already started");
402                     gssapi_started = 1;
403
404                     input_token.length = 0;
405                     input_token.value = NULL;
406                 }
407
408                 maj_stat =
409                     gss_init_sec_context(&min_stat,
410                                          GSS_C_NO_CREDENTIAL,
411                                          &context_hdl,
412                                          server,
413                                          mech_oid,
414                                          flags,
415                                          0,
416                                          GSS_C_NO_CHANNEL_BINDINGS,
417                                          &input_token,
418                                          NULL,
419                                          &output_token,
420                                          NULL,
421                                          NULL);
422                 if (GSS_ERROR(maj_stat))
423                     gss_err (1, min_stat, "gss_init_sec_context");
424                 else if (maj_stat & GSS_S_CONTINUE_NEEDED)
425                     gssapi_done = 0;
426                 else {
427                     gss_name_t targ_name, src_name;
428                     gss_buffer_desc name_buffer;
429                     gss_OID mech_type;
430
431                     gssapi_done = 1;
432
433                     printf("Negotiate done: %s\n", mech);
434
435                     maj_stat = gss_inquire_context(&min_stat,
436                                                    context_hdl,
437                                                    &src_name,
438                                                    &targ_name,
439                                                    NULL,
440                                                    &mech_type,
441                                                    NULL,
442                                                    NULL,
443                                                    NULL);
444                     if (GSS_ERROR(maj_stat))
445                         gss_err (1, min_stat, "gss_inquire_context");
446
447                     maj_stat = gss_display_name(&min_stat,
448                                                 src_name,
449                                                 &name_buffer,
450                                                 NULL);
451                     if (GSS_ERROR(maj_stat))
452                         gss_err (1, min_stat, "gss_display_name");
453
454                     printf("Source: %.*s\n",
455                            (int)name_buffer.length,
456                            (char *)name_buffer.value);
457
458                     gss_release_buffer(&min_stat, &name_buffer);
459
460                     maj_stat = gss_display_name(&min_stat,
461                                                 targ_name,
462                                                 &name_buffer,
463                                                 NULL);
464                     if (GSS_ERROR(maj_stat))
465                         gss_err (1, min_stat, "gss_display_name");
466
467                     printf("Target: %.*s\n",
468                            (int)name_buffer.length,
469                            (char *)name_buffer.value);
470
471                     gss_release_name(&min_stat, &targ_name);
472                     gss_release_buffer(&min_stat, &name_buffer);
473                 }
474
475                 if (output_token.length) {
476                     char *neg_token;
477
478                     rk_base64_encode(output_token.value,
479                                      output_token.length,
480                                      &neg_token);
481
482                     asprintf(&headers[num_headers++], "Authorization: Negotiate %s",
483                              neg_token);
484
485                     free(neg_token);
486                     gss_release_buffer(&min_stat, &output_token);
487                 }
488                 if (input_token.length)
489                     free(input_token.value);
490
491             } else
492                 done = 1;
493         } else
494             done = 1;
495
496         if (verbose_flag) {
497             printf("%s\n\n", req.response);
498
499             for (i = 0; i < req.num_headers; i++)
500                 printf("%s\n", req.headers[i]);
501             printf("\n");
502         }
503         if (print_body || verbose_flag)
504             printf("%.*s\n", (int)req.body_size, (char *)req.body);
505
506         http_req_free(&req);
507     } while (!done);
508
509     if (gssapi_done == 0)
510         errx(1, "gssapi not done but http dance done");
511
512     return 0;
513 }