]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - testcode/petal.c
import unbound 1.5.10
[FreeBSD/FreeBSD.git] / testcode / petal.c
1 /*
2  * petal.c - https daemon that is small and beautiful.
3  *
4  * Copyright (c) 2010, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  * 
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  * 
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  * 
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  * 
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35
36 /**
37  * \file
38  *
39  * HTTP1.1/SSL server.
40  */
41
42 #include "config.h"
43 #ifdef HAVE_GETOPT_H
44 #include <getopt.h>
45 #endif
46 #ifdef HAVE_OPENSSL_SSL_H
47 #include <openssl/ssl.h>
48 #endif
49 #ifdef HAVE_OPENSSL_ERR_H
50 #include <openssl/err.h>
51 #endif
52 #ifdef HAVE_OPENSSL_RAND_H
53 #include <openssl/rand.h>
54 #endif
55 #include <openssl/x509.h>
56 #include <openssl/pem.h>
57 #include <ctype.h>
58 #include <signal.h>
59 #if defined(UNBOUND_ALLOC_LITE) || defined(UNBOUND_ALLOC_STATS)
60 #ifdef malloc
61 #undef malloc
62 #endif
63 #ifdef free
64 #undef free
65 #endif
66 #endif /* alloc lite or alloc stats */
67
68 /** verbosity for this application */
69 static int verb = 0;
70
71 /** Give petal usage, and exit (1). */
72 static void
73 usage(void)
74 {
75         printf("Usage:  petal [opts]\n");
76         printf("        https daemon serves files from ./'host'/filename\n");
77         printf("        (no hostname: from the 'default' directory)\n");
78         printf("-a addr         bind to this address, 127.0.0.1\n");
79         printf("-p port         port number, default 443\n");
80         printf("-k keyfile      SSL private key file (PEM), petal.key\n");
81         printf("-c certfile     SSL certificate file (PEM), petal.pem\n");
82         printf("-v              more verbose\n");
83         printf("-h              show this usage help\n");
84         printf("Version %s\n", PACKAGE_VERSION);
85         printf("BSD licensed, see LICENSE in source package for details.\n");
86         printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
87         exit(1);
88 }
89
90 /** fatal exit */
91 static void print_exit(const char* str) {printf("error %s\n", str); exit(1);}
92 /** print errno */
93 static void log_errno(const char* str)
94 {printf("error %s: %s\n", str, strerror(errno));}
95
96 /** parse a text IP address into a sockaddr */
97 static int
98 parse_ip_addr(char* str, int port, struct sockaddr_storage* ret, socklen_t* l)
99 {
100         socklen_t len = 0;
101         struct sockaddr_storage* addr = NULL;
102         struct sockaddr_in6 a6;
103         struct sockaddr_in a;
104         uint16_t p = (uint16_t)port;
105         int fam = 0;
106         memset(&a6, 0, sizeof(a6));
107         memset(&a, 0, sizeof(a));
108
109         if(inet_pton(AF_INET6, str, &a6.sin6_addr) > 0) {
110                 /* it is an IPv6 */
111                 fam = AF_INET6;
112                 a6.sin6_family = AF_INET6;
113                 a6.sin6_port = (in_port_t)htons(p);
114                 addr = (struct sockaddr_storage*)&a6;
115                 len = (socklen_t)sizeof(struct sockaddr_in6);
116         }
117         if(inet_pton(AF_INET, str, &a.sin_addr) > 0) {
118                 /* it is an IPv4 */
119                 fam = AF_INET;
120                 a.sin_family = AF_INET;
121                 a.sin_port = (in_port_t)htons(p);
122                 addr = (struct sockaddr_storage*)&a;
123                 len = (socklen_t)sizeof(struct sockaddr_in);
124         }
125         if(!len) print_exit("cannot parse addr");
126         *l = len;
127         memmove(ret, addr, len);
128         return fam;
129 }
130
131 /** close the fd */
132 static void
133 fd_close(int fd)
134 {
135 #ifndef USE_WINSOCK
136         close(fd);
137 #else
138         closesocket(fd);
139 #endif
140 }
141
142 /** 
143  * Read one line from SSL
144  * zero terminates.
145  * skips "\r\n" (but not copied to buf).
146  * @param ssl: the SSL connection to read from (blocking).
147  * @param buf: buffer to return line in.
148  * @param len: size of the buffer.
149  * @return 0 on error, 1 on success.
150  */
151 static int
152 read_ssl_line(SSL* ssl, char* buf, size_t len)
153 {
154         size_t n = 0;
155         int r;
156         int endnl = 0;
157         while(1) {
158                 if(n >= len) {
159                         if(verb) printf("line too long\n");
160                         return 0;
161                 }
162                 if((r = SSL_read(ssl, buf+n, 1)) <= 0) {
163                         if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
164                                 /* EOF */
165                                 break;
166                         }
167                         if(verb) printf("could not SSL_read\n");
168                         return 0;
169                 }
170                 if(endnl && buf[n] == '\n') {
171                         break;
172                 } else if(endnl) {
173                         /* bad data */
174                         if(verb) printf("error: stray linefeeds\n");
175                         return 0;
176                 } else if(buf[n] == '\r') {
177                         /* skip \r, and also \n on the wire */
178                         endnl = 1;
179                         continue;
180                 } else if(buf[n] == '\n') {
181                         /* skip the \n, we are done */
182                         break;
183                 } else n++;
184         }
185         buf[n] = 0;
186         return 1;
187 }
188
189 /** process one http header */
190 static int
191 process_one_header(char* buf, char* file, size_t flen, char* host, size_t hlen,
192         int* vs)
193 {
194         if(strncasecmp(buf, "GET ", 4) == 0) {
195                 char* e = strstr(buf, " HTTP/1.1");
196                 if(!e) e = strstr(buf, " http/1.1");
197                 if(!e) {
198                         e = strstr(buf, " HTTP/1.0");
199                         if(!e) e = strstr(buf, " http/1.0");
200                         if(!e) e = strrchr(buf, ' ');
201                         if(!e) e = strrchr(buf, '\t');
202                         if(e) *vs = 10;
203                 }
204                 if(e) *e = 0;
205                 if(strlen(buf) < 4) return 0;
206                 (void)strlcpy(file, buf+4, flen);
207         } else if(strncasecmp(buf, "Host: ", 6) == 0) {
208                 (void)strlcpy(host, buf+6, hlen);
209         }
210         return 1;
211 }
212
213 /** read http headers and process them */
214 static int
215 read_http_headers(SSL* ssl, char* file, size_t flen, char* host, size_t hlen,
216         int* vs)
217 {
218         char buf[1024];
219         file[0] = 0;
220         host[0] = 0;
221         while(read_ssl_line(ssl, buf, sizeof(buf))) {
222                 if(verb>=2) printf("read: %s\n", buf);
223                 if(buf[0] == 0)
224                         return 1;
225                 if(!process_one_header(buf, file, flen, host, hlen, vs))
226                         return 0;
227         }
228         return 0;
229 }
230
231 /** setup SSL context */
232 static SSL_CTX*
233 setup_ctx(char* key, char* cert)
234 {
235         SSL_CTX* ctx = SSL_CTX_new(SSLv23_server_method());
236         if(!ctx) print_exit("out of memory");
237         (void)SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
238         (void)SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3);
239         if(!SSL_CTX_use_certificate_chain_file(ctx, cert))
240                 print_exit("cannot read cert");
241         if(!SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM))
242                 print_exit("cannot read key");
243         if(!SSL_CTX_check_private_key(ctx))
244                 print_exit("private key is not correct");
245 #if HAVE_DECL_SSL_CTX_SET_ECDH_AUTO
246         if (!SSL_CTX_set_ecdh_auto(ctx,1))
247                 if(verb>=1) printf("failed to set_ecdh_auto, not enabling ECDHE\n");
248 #elif defined(USE_ECDSA)
249         if(1) {
250                 EC_KEY *ecdh = EC_KEY_new_by_curve_name (NID_X9_62_prime256v1);
251                 if (!ecdh) {
252                         if(verb>=1) printf("could not find p256, not enabling ECDHE\n");
253                 } else {
254                         if (1 != SSL_CTX_set_tmp_ecdh (ctx, ecdh)) {
255                                 if(verb>=1) printf("Error in SSL_CTX_set_tmp_ecdh, not enabling ECDHE\n");
256                         }
257                         EC_KEY_free(ecdh);
258                 }
259         }
260 #endif
261         if(!SSL_CTX_load_verify_locations(ctx, cert, NULL))
262                 print_exit("cannot load cert verify locations");
263         return ctx;
264 }
265
266 /** setup listening TCP */
267 static int
268 setup_fd(char* addr, int port)
269 {
270         struct sockaddr_storage ad;
271         socklen_t len;
272         int fd;
273         int c = 1;
274         int fam = parse_ip_addr(addr, port, &ad, &len);
275         fd = socket(fam, SOCK_STREAM, 0);
276         if(fd == -1) {
277                 log_errno("socket");
278                 return -1;
279         }
280         if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
281                 (void*)&c, (socklen_t) sizeof(int)) < 0) {
282                 log_errno("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
283         }
284         if(bind(fd, (struct sockaddr*)&ad, len) == -1) {
285                 log_errno("bind");
286                 fd_close(fd);
287                 return -1;
288         }
289         if(listen(fd, 5) == -1) {
290                 log_errno("listen");
291                 fd_close(fd);
292                 return -1;
293         }
294         return fd;
295 }
296
297 /** setup SSL connection to the client */
298 static SSL*
299 setup_ssl(int s, SSL_CTX* ctx)
300 {
301         SSL* ssl = SSL_new(ctx);
302         if(!ssl) return NULL;
303         SSL_set_accept_state(ssl);
304         (void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
305         if(!SSL_set_fd(ssl, s)) {
306                 SSL_free(ssl);
307                 return NULL;
308         }
309         return ssl;
310 }
311
312 /** check a file name for safety */
313 static int
314 file_name_is_safe(char* s)
315 {
316         size_t l = strlen(s);
317         if(s[0] != '/')
318                 return 0; /* must start with / */
319         if(strstr(s, "/../"))
320                 return 0; /* no updirs in URL */
321         if(l>=3 && s[l-1]=='.' && s[l-2]=='.' && s[l-3]=='/')
322                 return 0; /* ends with /.. */
323         return 1;
324 }
325
326 /** adjust host and filename */
327 static void
328 adjust_host_file(char* host, char* file)
329 {
330         size_t i, len;
331         /* remove a port number if present */
332         if(strrchr(host, ':'))
333                 *strrchr(host, ':') = 0;
334         /* lowercase */
335         len = strlen(host);
336         for(i=0; i<len; i++)
337                 host[i] = tolower((unsigned char)host[i]);
338         len = strlen(file);
339         for(i=0; i<len; i++)
340                 file[i] = tolower((unsigned char)file[i]);
341 }
342
343 /** check a host name for safety */
344 static int
345 host_name_is_safe(char* s)
346 {
347         if(strchr(s, '/'))
348                 return 0;
349         if(strcmp(s, "..") == 0)
350                 return 0;
351         if(strcmp(s, ".") == 0)
352                 return 0;
353         return 1;
354 }
355
356 /** provide file in whole transfer */
357 static void
358 provide_file_10(SSL* ssl, char* fname)
359 {
360         char* buf, *at;
361         size_t len, avail, header_reserve=1024;
362         FILE* in = fopen(fname, 
363 #ifndef USE_WINSOCK
364                 "r"
365 #else
366                 "rb"
367 #endif
368                 );
369         size_t r;
370         const char* rcode = "200 OK";
371         if(!in) {
372                 char hdr[1024];
373                 rcode = "404 File not found";
374                 snprintf(hdr, sizeof(hdr), "HTTP/1.1 %s\r\n\r\n", rcode);
375                 r = strlen(hdr);
376                 if(SSL_write(ssl, hdr, (int)r) <= 0) {
377                         /* write failure */
378                 }
379                 return;
380         }
381         fseek(in, 0, SEEK_END);
382         len = (size_t)ftell(in);
383         fseek(in, 0, SEEK_SET);
384         /* plus some space for the header */
385         buf = (char*)malloc(len+header_reserve);
386         if(!buf) {
387                 fclose(in);
388                 return;
389         }
390         avail = len+header_reserve;
391         at = buf;
392         snprintf(at, avail, "HTTP/1.1 %s\r\n", rcode);
393         r = strlen(at);
394         at += r;
395         avail -= r;
396         snprintf(at, avail, "Server: petal/%s\r\n", PACKAGE_VERSION);
397         r = strlen(at);
398         at += r;
399         avail -= r;
400         snprintf(at, avail, "Content-Length: %u\r\n", (unsigned)len);
401         r = strlen(at);
402         at += r;
403         avail -= r;
404         snprintf(at, avail, "\r\n");
405         r = strlen(at);
406         at += r;
407         avail -= r;
408         if(avail < len) { /* robust */
409                 free(buf);
410                 fclose(in);
411                 return;
412         }
413         if(fread(at, 1, len, in) != len) {
414                 free(buf);
415                 fclose(in);
416                 return;
417         }
418         fclose(in);
419         at += len;
420         avail -= len;
421         if(SSL_write(ssl, buf, at-buf) <= 0) {
422                 /* write failure */
423         }
424         free(buf);
425 }
426
427 /** provide file over SSL, chunked encoding */
428 static void
429 provide_file_chunked(SSL* ssl, char* fname)
430 {
431         char buf[16384];
432         char* tmpbuf = NULL;
433         char* at = buf;
434         size_t avail = sizeof(buf);
435         size_t r;
436         FILE* in = fopen(fname, 
437 #ifndef USE_WINSOCK
438                 "r"
439 #else
440                 "rb"
441 #endif
442                 );
443         const char* rcode = "200 OK";
444         if(!in) {
445                 rcode = "404 File not found";
446         }
447
448         /* print headers */
449         snprintf(at, avail, "HTTP/1.1 %s\r\n", rcode);
450         r = strlen(at);
451         at += r;
452         avail -= r;
453         snprintf(at, avail, "Server: petal/%s\r\n", PACKAGE_VERSION);
454         r = strlen(at);
455         at += r;
456         avail -= r;
457         snprintf(at, avail, "Transfer-Encoding: chunked\r\n");
458         r = strlen(at);
459         at += r;
460         avail -= r;
461         snprintf(at, avail, "Connection: close\r\n");
462         r = strlen(at);
463         at += r;
464         avail -= r;
465         snprintf(at, avail, "\r\n");
466         r = strlen(at);
467         at += r;
468         avail -= r;
469         if(avail < 16) { /* robust */
470                 if(in) fclose(in);
471                 return;
472         }
473
474         do {
475                 size_t red;
476                 free(tmpbuf);
477                 tmpbuf = malloc(avail-16);
478                 if(!tmpbuf)
479                         break;
480                 /* read chunk; space-16 for xxxxCRLF..CRLF0CRLFCRLF (3 spare)*/
481                 red = in?fread(tmpbuf, 1, avail-16, in):0;
482                 /* prepare chunk */
483                 snprintf(at, avail, "%x\r\n", (unsigned)red);
484                 r = strlen(at);
485                 if(verb >= 3)
486                 {printf("chunk len %x\n", (unsigned)red); fflush(stdout);}
487                 at += r;
488                 avail -= r;
489                 if(red != 0) {
490                         if(red > avail) break; /* robust */
491                         memmove(at, tmpbuf, red);
492                         at += red;
493                         avail -= red;
494                         snprintf(at, avail, "\r\n");
495                         r = strlen(at);
496                         at += r;
497                         avail -= r;
498                 }
499                 if(in && feof(in) && red != 0) {
500                         snprintf(at, avail, "0\r\n");
501                         r = strlen(at);
502                         at += r;
503                         avail -= r;
504                 }
505                 if(!in || feof(in)) {
506                         snprintf(at, avail, "\r\n");
507                         r = strlen(at);
508                         at += r;
509                         avail -= r;
510                 }
511                 /* send chunk */
512                 if(SSL_write(ssl, buf, at-buf) <= 0) {
513                         /* SSL error */
514                         break;
515                 }
516
517                 /* setup for next chunk */
518                 at = buf;
519                 avail = sizeof(buf);
520         } while(in && !feof(in) && !ferror(in));
521
522         free(tmpbuf);
523         if(in) fclose(in);
524 }
525
526 /** provide service to the ssl descriptor */
527 static void
528 service_ssl(SSL* ssl, struct sockaddr_storage* from, socklen_t falen)
529 {
530         char file[1024];
531         char host[1024];
532         char combined[2048];
533         int vs = 11;
534         if(!read_http_headers(ssl, file, sizeof(file), host, sizeof(host),
535                 &vs))
536                 return;
537         adjust_host_file(host, file);
538         if(host[0] == 0 || !host_name_is_safe(host))
539                 (void)strlcpy(host, "default", sizeof(host));
540         if(!file_name_is_safe(file)) {
541                 return;
542         }
543         snprintf(combined, sizeof(combined), "%s%s", host, file);
544         if(verb) {
545                 char out[100];
546                 void* a = &((struct sockaddr_in*)from)->sin_addr;
547                 if(falen != (socklen_t)sizeof(struct sockaddr_in))
548                         a = &((struct sockaddr_in6*)from)->sin6_addr;
549                 out[0]=0;
550                 (void)inet_ntop((int)((struct sockaddr_in*)from)->sin_family,
551                         a, out, (socklen_t)sizeof(out));
552                 printf("%s requests %s\n", out, combined);
553                 fflush(stdout);
554         }
555         if(vs == 10)
556                 provide_file_10(ssl, combined);
557         else    provide_file_chunked(ssl, combined);
558 }
559
560 /** provide ssl service */
561 static void
562 do_service(char* addr, int port, char* key, char* cert)
563 {
564         SSL_CTX* sslctx = setup_ctx(key, cert);
565         int fd = setup_fd(addr, port);
566         int go = 1;
567         if(fd == -1) print_exit("could not setup sockets");
568         if(verb) {printf("petal start\n"); fflush(stdout);}
569         while(go) {
570                 struct sockaddr_storage from;
571                 socklen_t flen = (socklen_t)sizeof(from);
572                 int s = accept(fd, (struct sockaddr*)&from, &flen);
573                 if(verb) fflush(stdout);
574                 if(s != -1) {
575                         SSL* ssl = setup_ssl(s, sslctx);
576                         if(verb) fflush(stdout);
577                         if(ssl) {
578                                 service_ssl(ssl, &from, flen);
579                                 if(verb) fflush(stdout);
580                                 SSL_shutdown(ssl);
581                                 SSL_free(ssl);
582                         }
583                         fd_close(s);
584                 } else if (verb >=2) log_errno("accept");
585                 if(verb) fflush(stdout);
586         }
587         /* if we get a kill signal, the process dies and the OS reaps us */
588         if(verb) printf("petal end\n");
589         fd_close(fd);
590         SSL_CTX_free(sslctx);
591 }
592
593 /** getopt global, in case header files fail to declare it. */
594 extern int optind;
595 /** getopt global, in case header files fail to declare it. */
596 extern char* optarg;
597
598 /** Main routine for petal */
599 int main(int argc, char* argv[])
600 {
601         int c;
602         int port = 443;
603         char* addr = "127.0.0.1", *key = "petal.key", *cert = "petal.pem";
604 #ifdef USE_WINSOCK
605         WSADATA wsa_data;
606         if((c=WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0)
607         {       printf("WSAStartup failed\n"); exit(1); }
608         atexit((void (*)(void))WSACleanup);
609 #endif
610
611         /* parse the options */
612         while( (c=getopt(argc, argv, "a:c:k:hp:v")) != -1) {
613                 switch(c) {
614                 case 'a':
615                         addr = optarg;
616                         break;
617                 case 'c':
618                         cert = optarg;
619                         break;
620                 case 'k':
621                         key = optarg;
622                         break;
623                 case 'p':
624                         port = atoi(optarg);
625                         break;
626                 case 'v':
627                         verb++;
628                         break;
629                 case '?':
630                 case 'h':
631                 default:
632                         usage();
633                 }
634         }
635         argc -= optind;
636         argv += optind;
637         if(argc != 0)
638                 usage();
639
640 #ifdef SIGPIPE
641         (void)signal(SIGPIPE, SIG_IGN);
642 #endif
643 #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
644         ERR_load_crypto_strings();
645 #endif
646         ERR_load_SSL_strings();
647 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
648         OpenSSL_add_all_algorithms();
649 #else
650         OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
651                 | OPENSSL_INIT_ADD_ALL_DIGESTS
652                 | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
653 #endif
654 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
655         (void)SSL_library_init();
656 #else
657         (void)OPENSSL_init_ssl(0, NULL);
658 #endif
659
660         do_service(addr, port, key, cert);
661
662 #ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
663         CRYPTO_cleanup_all_ex_data();
664 #endif
665 #ifdef HAVE_ERR_FREE_STRINGS
666         ERR_free_strings();
667 #endif
668         return 0;
669 }