/ tools / server.c
server.c
   1  /*
   2   * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
   3   *
   4   * Permission is hereby granted, free of charge, to any person obtaining 
   5   * a copy of this software and associated documentation files (the
   6   * "Software"), to deal in the Software without restriction, including
   7   * without limitation the rights to use, copy, modify, merge, publish,
   8   * distribute, sublicense, and/or sell copies of the Software, and to
   9   * permit persons to whom the Software is furnished to do so, subject to
  10   * the following conditions:
  11   *
  12   * The above copyright notice and this permission notice shall be 
  13   * included in all copies or substantial portions of the Software.
  14   *
  15   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
  16   * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17   * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
  18   * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  19   * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  20   * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21   * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22   * SOFTWARE.
  23   */
  24  
  25  #include <stdio.h>
  26  #include <stdlib.h>
  27  #include <string.h>
  28  #include <stdint.h>
  29  #include <errno.h>
  30  #include <signal.h>
  31  
  32  #ifdef _WIN32
  33  #include <winsock2.h>
  34  #include <ws2tcpip.h>
  35  #else
  36  #include <sys/types.h>
  37  #include <sys/socket.h>
  38  #include <netdb.h>
  39  #include <netinet/in.h>
  40  #include <arpa/inet.h>
  41  #include <unistd.h>
  42  #include <fcntl.h>
  43  
  44  #define SOCKET             int
  45  #define INVALID_SOCKET     (-1)
  46  #define SOCKADDR_STORAGE   struct sockaddr_storage
  47  #endif
  48  
  49  #include "brssl.h"
  50  
  51  static SOCKET
  52  host_bind(const char *host, const char *port, int verbose)
  53  {
  54  	struct addrinfo hints, *si, *p;
  55  	SOCKET fd;
  56  	int err;
  57  
  58  	memset(&hints, 0, sizeof hints);
  59  	hints.ai_family = PF_UNSPEC;
  60  	hints.ai_socktype = SOCK_STREAM;
  61  	err = getaddrinfo(host, port, &hints, &si);
  62  	if (err != 0) {
  63  		fprintf(stderr, "ERROR: getaddrinfo(): %s\n",
  64  			gai_strerror(err));
  65  		return INVALID_SOCKET;
  66  	}
  67  	fd = INVALID_SOCKET;
  68  	for (p = si; p != NULL; p = p->ai_next) {
  69  		struct sockaddr *sa;
  70  		struct sockaddr_in sa4;
  71  		struct sockaddr_in6 sa6;
  72  		size_t sa_len;
  73  		void *addr;
  74  		int opt;
  75  
  76  		sa = (struct sockaddr *)p->ai_addr;
  77  		if (sa->sa_family == AF_INET) {
  78  			memcpy(&sa4, sa, sizeof sa4);
  79  			sa = (struct sockaddr *)&sa4;
  80  			sa_len = sizeof sa4;
  81  			addr = &sa4.sin_addr;
  82  			if (host == NULL) {
  83  				sa4.sin_addr.s_addr = INADDR_ANY;
  84  			}
  85  		} else if (sa->sa_family == AF_INET6) {
  86  			memcpy(&sa6, sa, sizeof sa6);
  87  			sa = (struct sockaddr *)&sa6;
  88  			sa_len = sizeof sa6;
  89  			addr = &sa6.sin6_addr;
  90  			if (host == NULL) {
  91  				sa6.sin6_addr = in6addr_any;
  92  			}
  93  		} else {
  94  			addr = NULL;
  95  			sa_len = p->ai_addrlen;
  96  		}
  97  		if (verbose) {
  98  			char tmp[INET6_ADDRSTRLEN + 50];
  99  
 100  			if (addr != NULL) {
 101  				if (!inet_ntop(p->ai_family, addr,
 102  					tmp, sizeof tmp))
 103  				{
 104  					strcpy(tmp, "<invalid>");
 105  				}
 106  			} else {
 107  				sprintf(tmp, "<unknown family: %d>",
 108  					(int)sa->sa_family);
 109  			}
 110  			fprintf(stderr, "binding to: %s\n", tmp);
 111  		}
 112  		fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
 113  		if (fd == INVALID_SOCKET) {
 114  			if (verbose) {
 115  				perror("socket()");
 116  			}
 117  			continue;
 118  		}
 119  		opt = 1;
 120  		setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
 121  			(void *)&opt, sizeof opt);
 122  #ifdef IPV6_V6ONLY
 123  		/*
 124  		 * We want to make sure that the server socket works for
 125  		 * both IPv4 and IPv6. But IPV6_V6ONLY is not defined on
 126  		 * some very old systems.
 127  		 */
 128  		opt = 0;
 129  		setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
 130  			(void *)&opt, sizeof opt);
 131  #endif
 132  		if (bind(fd, sa, sa_len) < 0) {
 133  			if (verbose) {
 134  				perror("bind()");
 135  			}
 136  #ifdef _WIN32
 137  			closesocket(fd);
 138  #else
 139  			close(fd);
 140  #endif
 141  			continue;
 142  		}
 143  		break;
 144  	}
 145  	if (p == NULL) {
 146  		freeaddrinfo(si);
 147  		fprintf(stderr, "ERROR: failed to bind\n");
 148  		return INVALID_SOCKET;
 149  	}
 150  	freeaddrinfo(si);
 151  	if (listen(fd, 5) < 0) {
 152  		if (verbose) {
 153  			perror("listen()");
 154  		}
 155  #ifdef _WIN32
 156  		closesocket(fd);
 157  #else
 158  		close(fd);
 159  #endif
 160  		return INVALID_SOCKET;
 161  	}
 162  	if (verbose) {
 163  		fprintf(stderr, "bound.\n");
 164  	}
 165  	return fd;
 166  }
 167  
 168  static SOCKET
 169  accept_client(SOCKET server_fd, int verbose, int nonblock)
 170  {
 171  	int fd;
 172  	SOCKADDR_STORAGE sa;
 173  	socklen_t sa_len;
 174  
 175  	sa_len = sizeof sa;
 176  	fd = accept(server_fd, (struct sockaddr *)&sa, &sa_len);
 177  	if (fd == INVALID_SOCKET) {
 178  		if (verbose) {
 179  			perror("accept()");
 180  		}
 181  		return INVALID_SOCKET;
 182  	}
 183  	if (verbose) {
 184  		char tmp[INET6_ADDRSTRLEN + 50];
 185  		const char *name;
 186  
 187  		name = NULL;
 188  		switch (((struct sockaddr *)&sa)->sa_family) {
 189  		case AF_INET:
 190  			name = inet_ntop(AF_INET,
 191  				&((struct sockaddr_in *)&sa)->sin_addr,
 192  				tmp, sizeof tmp);
 193  			break;
 194  		case AF_INET6:
 195  			name = inet_ntop(AF_INET6,
 196  				&((struct sockaddr_in6 *)&sa)->sin6_addr,
 197  				tmp, sizeof tmp);
 198  			break;
 199  		}
 200  		if (name == NULL) {
 201  			sprintf(tmp, "<unknown: %lu>", (unsigned long)
 202  				((struct sockaddr *)&sa)->sa_family);
 203  			name = tmp;
 204  		}
 205  		fprintf(stderr, "accepting connection from: %s\n", name);
 206  	}
 207  
 208  	/*
 209  	 * We make the socket non-blocking, since we are going to use
 210  	 * poll() or select() to organise I/O.
 211  	 */
 212  	if (nonblock) {
 213  #ifdef _WIN32
 214  		u_long arg;
 215  
 216  		arg = 1;
 217  		ioctlsocket(fd, FIONBIO, &arg);
 218  #else
 219  		fcntl(fd, F_SETFL, O_NONBLOCK);
 220  #endif
 221  	}
 222  	return fd;
 223  }
 224  
 225  static void
 226  usage_server(void)
 227  {
 228  	fprintf(stderr,
 229  "usage: brssl server [ options ]\n");
 230  	fprintf(stderr,
 231  "options:\n");
 232  	fprintf(stderr,
 233  "   -q              suppress verbose messages\n");
 234  	fprintf(stderr,
 235  "   -trace          activate extra debug messages (dump of all packets)\n");
 236  	fprintf(stderr,
 237  "   -b name         bind to a specific address or host name\n");
 238  	fprintf(stderr,
 239  "   -p port         bind to a specific port (default: 4433)\n");
 240  	fprintf(stderr,
 241  "   -mono           use monodirectional buffering\n");
 242  	fprintf(stderr,
 243  "   -buf length     set the I/O buffer length (in bytes)\n");
 244  	fprintf(stderr,
 245  "   -cache length   set the session cache storage length (in bytes)\n");
 246  	fprintf(stderr,
 247  "   -cert fname     read certificate chain from file 'fname'\n");
 248  	fprintf(stderr,
 249  "   -key fname      read private key from file 'fname'\n");
 250  	fprintf(stderr,
 251  "   -CA file        add trust anchors from 'file' (for client auth)\n");
 252  	fprintf(stderr,
 253  "   -anon_ok        request but do not require a client certificate\n");
 254  	fprintf(stderr,
 255  "   -list           list supported names (protocols, algorithms...)\n");
 256  	fprintf(stderr,
 257  "   -vmin name      set minimum supported version (default: TLS-1.0)\n");
 258  	fprintf(stderr,
 259  "   -vmax name      set maximum supported version (default: TLS-1.2)\n");
 260  	fprintf(stderr,
 261  "   -cs names       set list of supported cipher suites (comma-separated)\n");
 262  	fprintf(stderr,
 263  "   -hf names       add support for some hash functions (comma-separated)\n");
 264  	fprintf(stderr,
 265  "   -cbhash         test hashing in policy callback\n");
 266  	fprintf(stderr,
 267  "   -serverpref     enforce server's preferences for cipher suites\n");
 268  	fprintf(stderr,
 269  "   -noreneg        prohibit renegotiations\n");
 270  	fprintf(stderr,
 271  "   -alpn name      add protocol name to list of protocols (ALPN extension)\n");
 272  	fprintf(stderr,
 273  "   -strictalpn     fail on ALPN mismatch\n");
 274  	exit(EXIT_FAILURE);
 275  }
 276  
 277  typedef struct {
 278  	const br_ssl_server_policy_class *vtable;
 279  	int verbose;
 280  	br_x509_certificate *chain;
 281  	size_t chain_len;
 282  	int cert_signer_algo;
 283  	private_key *sk;
 284  	int cbhash;
 285  } policy_context;
 286  
 287  static void
 288  print_hashes(unsigned chashes)
 289  {
 290  	int i;
 291  
 292  	for (i = 2; i <= 6; i ++) {
 293  		if ((chashes >> i) & 1) {
 294  			int z;
 295  
 296  			switch (i) {
 297  			case 3: z = 224; break;
 298  			case 4: z = 256; break;
 299  			case 5: z = 384; break;
 300  			case 6: z = 512; break;
 301  			default:
 302  				z = 1;
 303  				break;
 304  			}
 305  			fprintf(stderr, " sha%d", z);
 306  		}
 307  	}
 308  }
 309  
 310  static unsigned
 311  choose_hash(unsigned chashes)
 312  {
 313  	unsigned hash_id;
 314  
 315  	for (hash_id = 6; hash_id >= 2; hash_id --) {
 316  		if (((chashes >> hash_id) & 1) != 0) {
 317  			return hash_id;
 318  		}
 319  	}
 320  	/*
 321  	 * Normally unreachable.
 322  	 */
 323  	return 0;
 324  }
 325  
 326  static int
 327  sp_choose(const br_ssl_server_policy_class **pctx,
 328  	const br_ssl_server_context *cc,
 329  	br_ssl_server_choices *choices)
 330  {
 331  	policy_context *pc;
 332  	const br_suite_translated *st;
 333  	size_t u, st_num;
 334  	unsigned chashes;
 335  
 336  	pc = (policy_context *)pctx;
 337  	st = br_ssl_server_get_client_suites(cc, &st_num);
 338  	chashes = br_ssl_server_get_client_hashes(cc);
 339  	if (pc->verbose) {
 340  		fprintf(stderr, "Client parameters:\n");
 341  		fprintf(stderr, "   Maximum version:      ");
 342  		switch (cc->client_max_version) {
 343  		case BR_SSL30:
 344  			fprintf(stderr, "SSL 3.0");
 345  			break;
 346  		case BR_TLS10:
 347  			fprintf(stderr, "TLS 1.0");
 348  			break;
 349  		case BR_TLS11:
 350  			fprintf(stderr, "TLS 1.1");
 351  			break;
 352  		case BR_TLS12:
 353  			fprintf(stderr, "TLS 1.2");
 354  			break;
 355  		default:
 356  			fprintf(stderr, "unknown (0x%04X)",
 357  				(unsigned)cc->client_max_version);
 358  			break;
 359  		}
 360  		fprintf(stderr, "\n");
 361  		fprintf(stderr, "   Compatible cipher suites:\n");
 362  		for (u = 0; u < st_num; u ++) {
 363  			char csn[80];
 364  
 365  			get_suite_name_ext(st[u][0], csn, sizeof csn);
 366  			fprintf(stderr, "      %s\n", csn);
 367  		}
 368  		fprintf(stderr, "   Common sign+hash functions:\n");
 369  		if ((chashes & 0xFF) != 0) {
 370  			fprintf(stderr, "      with RSA:");
 371  			print_hashes(chashes);
 372  			fprintf(stderr, "\n");
 373  		}
 374  		if ((chashes >> 8) != 0) {
 375  			fprintf(stderr, "      with ECDSA:");
 376  			print_hashes(chashes >> 8);
 377  			fprintf(stderr, "\n");
 378  		}
 379  	}
 380  	for (u = 0; u < st_num; u ++) {
 381  		unsigned tt;
 382  
 383  		tt = st[u][1];
 384  		switch (tt >> 12) {
 385  		case BR_SSLKEYX_RSA:
 386  			if (pc->sk->key_type == BR_KEYTYPE_RSA) {
 387  				choices->cipher_suite = st[u][0];
 388  				goto choose_ok;
 389  			}
 390  			break;
 391  		case BR_SSLKEYX_ECDHE_RSA:
 392  			if (pc->sk->key_type == BR_KEYTYPE_RSA) {
 393  				choices->cipher_suite = st[u][0];
 394  				if (br_ssl_engine_get_version(&cc->eng)
 395  					< BR_TLS12)
 396  				{
 397  					if (pc->cbhash) {
 398  						choices->algo_id = 0x0001;
 399  					} else {
 400  						choices->algo_id = 0xFF00;
 401  					}
 402  				} else {
 403  					unsigned id;
 404  
 405  					id = choose_hash(chashes);
 406  					if (pc->cbhash) {
 407  						choices->algo_id =
 408  							(id << 8) + 0x01;
 409  					} else {
 410  						choices->algo_id = 0xFF00 + id;
 411  					}
 412  				}
 413  				goto choose_ok;
 414  			}
 415  			break;
 416  		case BR_SSLKEYX_ECDHE_ECDSA:
 417  			if (pc->sk->key_type == BR_KEYTYPE_EC) {
 418  				choices->cipher_suite = st[u][0];
 419  				if (br_ssl_engine_get_version(&cc->eng)
 420  					< BR_TLS12)
 421  				{
 422  					if (pc->cbhash) {
 423  						choices->algo_id = 0x0203;
 424  					} else {
 425  						choices->algo_id =
 426  							0xFF00 + br_sha1_ID;
 427  					}
 428  				} else {
 429  					unsigned id;
 430  
 431  					id = choose_hash(chashes >> 8);
 432  					if (pc->cbhash) {
 433  						choices->algo_id =
 434  							(id << 8) + 0x03;
 435  					} else {
 436  						choices->algo_id =
 437  							0xFF00 + id;
 438  					}
 439  				}
 440  				goto choose_ok;
 441  			}
 442  			break;
 443  		case BR_SSLKEYX_ECDH_RSA:
 444  			if (pc->sk->key_type == BR_KEYTYPE_EC
 445  				&& pc->cert_signer_algo == BR_KEYTYPE_RSA)
 446  			{
 447  				choices->cipher_suite = st[u][0];
 448  				goto choose_ok;
 449  			}
 450  			break;
 451  		case BR_SSLKEYX_ECDH_ECDSA:
 452  			if (pc->sk->key_type == BR_KEYTYPE_EC
 453  				&& pc->cert_signer_algo == BR_KEYTYPE_EC)
 454  			{
 455  				choices->cipher_suite = st[u][0];
 456  				goto choose_ok;
 457  			}
 458  			break;
 459  		}
 460  	}
 461  	return 0;
 462  
 463  choose_ok:
 464  	choices->chain = pc->chain;
 465  	choices->chain_len = pc->chain_len;
 466  	if (pc->verbose) {
 467  		char csn[80];
 468  
 469  		get_suite_name_ext(choices->cipher_suite, csn, sizeof csn);
 470  		fprintf(stderr, "Using: %s\n", csn);
 471  	}
 472  	return 1;
 473  }
 474  
 475  static uint32_t
 476  sp_do_keyx(const br_ssl_server_policy_class **pctx,
 477  	unsigned char *data, size_t *len)
 478  {
 479  	policy_context *pc;
 480  	uint32_t r;
 481  	size_t xoff, xlen;
 482  
 483  	pc = (policy_context *)pctx;
 484  	switch (pc->sk->key_type) {
 485  		const br_ec_impl *iec;
 486  
 487  	case BR_KEYTYPE_RSA:
 488  		return br_rsa_ssl_decrypt(
 489  			br_rsa_private_get_default(),
 490  			&pc->sk->key.rsa, data, *len);
 491  	case BR_KEYTYPE_EC:
 492  		iec = br_ec_get_default();
 493  		r = iec->mul(data, *len, pc->sk->key.ec.x,
 494  			pc->sk->key.ec.xlen, pc->sk->key.ec.curve);
 495  		xoff = iec->xoff(pc->sk->key.ec.curve, &xlen);
 496  		memmove(data, data + xoff, xlen);
 497  		*len = xlen;
 498  		return r;
 499  	default:
 500  		fprintf(stderr, "ERROR: unknown private key type (%d)\n",
 501  			(int)pc->sk->key_type);
 502  		return 0;
 503  	}
 504  }
 505  
 506  static size_t
 507  sp_do_sign(const br_ssl_server_policy_class **pctx,
 508  	unsigned algo_id, unsigned char *data, size_t hv_len, size_t len)
 509  {
 510  	policy_context *pc;
 511  	unsigned char hv[64];
 512  
 513  	pc = (policy_context *)pctx;
 514  	if (algo_id >= 0xFF00) {
 515  		algo_id &= 0xFF;
 516  		memcpy(hv, data, hv_len);
 517  	} else {
 518  		const br_hash_class *hc;
 519  		br_hash_compat_context zc;
 520  
 521  		if (pc->verbose) {
 522  			fprintf(stderr, "Callback hashing, algo = 0x%04X,"
 523  				" data_len = %lu\n",
 524  				algo_id, (unsigned long)hv_len);
 525  		}
 526  		algo_id >>= 8;
 527  		hc = get_hash_impl(algo_id);
 528  		if (hc == NULL) {
 529  			if (pc->verbose) {
 530  				fprintf(stderr,
 531  					"ERROR: unsupported hash function %u\n",
 532  					algo_id);
 533  			}
 534  			return 0;
 535  		}
 536  		hc->init(&zc.vtable);
 537  		hc->update(&zc.vtable, data, hv_len);
 538  		hc->out(&zc.vtable, hv);
 539  		hv_len = (hc->desc >> BR_HASHDESC_OUT_OFF)
 540  			& BR_HASHDESC_OUT_MASK;
 541  	}
 542  	switch (pc->sk->key_type) {
 543  		size_t sig_len;
 544  		uint32_t x;
 545  		const unsigned char *hash_oid;
 546  		const br_hash_class *hc;
 547  
 548  	case BR_KEYTYPE_RSA:
 549  		hash_oid = get_hash_oid(algo_id);
 550  		if (hash_oid == NULL && algo_id != 0) {
 551  			if (pc->verbose) {
 552  				fprintf(stderr, "ERROR: cannot RSA-sign with"
 553  					" unknown hash function: %u\n",
 554  					algo_id);
 555  			}
 556  			return 0;
 557  		}
 558  		sig_len = (pc->sk->key.rsa.n_bitlen + 7) >> 3;
 559  		if (len < sig_len) {
 560  			if (pc->verbose) {
 561  				fprintf(stderr, "ERROR: cannot RSA-sign,"
 562  					" buffer is too small"
 563  					" (sig=%lu, buf=%lu)\n",
 564  					(unsigned long)sig_len,
 565  					(unsigned long)len);
 566  			}
 567  			return 0;
 568  		}
 569  		x = br_rsa_pkcs1_sign_get_default()(
 570  			hash_oid, hv, hv_len, &pc->sk->key.rsa, data);
 571  		if (!x) {
 572  			if (pc->verbose) {
 573  				fprintf(stderr, "ERROR: RSA-sign failure\n");
 574  			}
 575  			return 0;
 576  		}
 577  		return sig_len;
 578  
 579  	case BR_KEYTYPE_EC:
 580  		hc = get_hash_impl(algo_id);
 581  		if (hc == NULL) {
 582  			if (pc->verbose) {
 583  				fprintf(stderr, "ERROR: cannot ECDSA-sign with"
 584  					" unknown hash function: %u\n",
 585  					algo_id);
 586  			}
 587  			return 0;
 588  		}
 589  		if (len < 139) {
 590  			if (pc->verbose) {
 591  				fprintf(stderr, "ERROR: cannot ECDSA-sign"
 592  					" (output buffer = %lu)\n",
 593  					(unsigned long)len);
 594  			}
 595  			return 0;
 596  		}
 597  		sig_len = br_ecdsa_sign_asn1_get_default()(
 598  			br_ec_get_default(), hc, hv, &pc->sk->key.ec, data);
 599  		if (sig_len == 0) {
 600  			if (pc->verbose) {
 601  				fprintf(stderr, "ERROR: ECDSA-sign failure\n");
 602  			}
 603  			return 0;
 604  		}
 605  		return sig_len;
 606  
 607  	default:
 608  		return 0;
 609  	}
 610  }
 611  
 612  static const br_ssl_server_policy_class policy_vtable = {
 613  	sizeof(policy_context),
 614  	sp_choose,
 615  	sp_do_keyx,
 616  	sp_do_sign
 617  };
 618  
 619  void
 620  free_alpn(void *alpn)
 621  {
 622  	xfree(*(char **)alpn);
 623  }
 624  
 625  /* see brssl.h */
 626  int
 627  do_server(int argc, char *argv[])
 628  {
 629  	int retcode;
 630  	int verbose;
 631  	int trace;
 632  	int i, bidi;
 633  	const char *bind_name;
 634  	const char *port;
 635  	unsigned vmin, vmax;
 636  	cipher_suite *suites;
 637  	size_t num_suites;
 638  	uint16_t *suite_ids;
 639  	unsigned hfuns;
 640  	int cbhash;
 641  	br_x509_certificate *chain;
 642  	size_t chain_len;
 643  	int cert_signer_algo;
 644  	private_key *sk;
 645  	anchor_list anchors = VEC_INIT;
 646  	VECTOR(char *) alpn_names = VEC_INIT;
 647  	br_x509_minimal_context xc;
 648  	const br_hash_class *dnhash;
 649  	size_t u;
 650  	br_ssl_server_context cc;
 651  	policy_context pc;
 652  	br_ssl_session_cache_lru lru;
 653  	unsigned char *iobuf, *cache;
 654  	size_t iobuf_len, cache_len;
 655  	uint32_t flags;
 656  	SOCKET server_fd, fd;
 657  
 658  	retcode = 0;
 659  	verbose = 1;
 660  	trace = 0;
 661  	bind_name = NULL;
 662  	port = NULL;
 663  	bidi = 1;
 664  	vmin = 0;
 665  	vmax = 0;
 666  	suites = NULL;
 667  	num_suites = 0;
 668  	hfuns = 0;
 669  	cbhash = 0;
 670  	suite_ids = NULL;
 671  	chain = NULL;
 672  	chain_len = 0;
 673  	sk = NULL;
 674  	iobuf = NULL;
 675  	iobuf_len = 0;
 676  	cache = NULL;
 677  	cache_len = (size_t)-1;
 678  	flags = 0;
 679  	server_fd = INVALID_SOCKET;
 680  	fd = INVALID_SOCKET;
 681  	for (i = 0; i < argc; i ++) {
 682  		const char *arg;
 683  
 684  		arg = argv[i];
 685  		if (arg[0] != '-') {
 686  			usage_server();
 687  			goto server_exit_error;
 688  		}
 689  		if (eqstr(arg, "-v") || eqstr(arg, "-verbose")) {
 690  			verbose = 1;
 691  		} else if (eqstr(arg, "-q") || eqstr(arg, "-quiet")) {
 692  			verbose = 0;
 693  		} else if (eqstr(arg, "-trace")) {
 694  			trace = 1;
 695  		} else if (eqstr(arg, "-b")) {
 696  			if (++ i >= argc) {
 697  				fprintf(stderr,
 698  					"ERROR: no argument for '-b'\n");
 699  				usage_server();
 700  				goto server_exit_error;
 701  			}
 702  			if (bind_name != NULL) {
 703  				fprintf(stderr, "ERROR: duplicate bind host\n");
 704  				usage_server();
 705  				goto server_exit_error;
 706  			}
 707  			bind_name = argv[i];
 708  		} else if (eqstr(arg, "-p")) {
 709  			if (++ i >= argc) {
 710  				fprintf(stderr,
 711  					"ERROR: no argument for '-p'\n");
 712  				usage_server();
 713  				goto server_exit_error;
 714  			}
 715  			if (port != NULL) {
 716  				fprintf(stderr, "ERROR: duplicate bind port\n");
 717  				usage_server();
 718  				goto server_exit_error;
 719  			}
 720  			port = argv[i];
 721  		} else if (eqstr(arg, "-mono")) {
 722  			bidi = 0;
 723  		} else if (eqstr(arg, "-buf")) {
 724  			if (++ i >= argc) {
 725  				fprintf(stderr,
 726  					"ERROR: no argument for '-buf'\n");
 727  				usage_server();
 728  				goto server_exit_error;
 729  			}
 730  			arg = argv[i];
 731  			if (iobuf_len != 0) {
 732  				fprintf(stderr,
 733  					"ERROR: duplicate I/O buffer length\n");
 734  				usage_server();
 735  				goto server_exit_error;
 736  			}
 737  			iobuf_len = parse_size(arg);
 738  			if (iobuf_len == (size_t)-1) {
 739  				usage_server();
 740  				goto server_exit_error;
 741  			}
 742  		} else if (eqstr(arg, "-cache")) {
 743  			if (++ i >= argc) {
 744  				fprintf(stderr,
 745  					"ERROR: no argument for '-cache'\n");
 746  				usage_server();
 747  				goto server_exit_error;
 748  			}
 749  			arg = argv[i];
 750  			if (cache_len != (size_t)-1) {
 751  				fprintf(stderr, "ERROR: duplicate session"
 752  					" cache length\n");
 753  				usage_server();
 754  				goto server_exit_error;
 755  			}
 756  			cache_len = parse_size(arg);
 757  			if (cache_len == (size_t)-1) {
 758  				usage_server();
 759  				goto server_exit_error;
 760  			}
 761  		} else if (eqstr(arg, "-cert")) {
 762  			if (++ i >= argc) {
 763  				fprintf(stderr,
 764  					"ERROR: no argument for '-cert'\n");
 765  				usage_server();
 766  				goto server_exit_error;
 767  			}
 768  			if (chain != NULL) {
 769  				fprintf(stderr,
 770  					"ERROR: duplicate certificate chain\n");
 771  				usage_server();
 772  				goto server_exit_error;
 773  			}
 774  			arg = argv[i];
 775  			chain = read_certificates(arg, &chain_len);
 776  			if (chain == NULL || chain_len == 0) {
 777  				goto server_exit_error;
 778  			}
 779  		} else if (eqstr(arg, "-key")) {
 780  			if (++ i >= argc) {
 781  				fprintf(stderr,
 782  					"ERROR: no argument for '-key'\n");
 783  				usage_server();
 784  				goto server_exit_error;
 785  			}
 786  			if (sk != NULL) {
 787  				fprintf(stderr,
 788  					"ERROR: duplicate private key\n");
 789  				usage_server();
 790  				goto server_exit_error;
 791  			}
 792  			arg = argv[i];
 793  			sk = read_private_key(arg);
 794  			if (sk == NULL) {
 795  				goto server_exit_error;
 796  			}
 797  		} else if (eqstr(arg, "-CA")) {
 798  			if (++ i >= argc) {
 799  				fprintf(stderr,
 800  					"ERROR: no argument for '-CA'\n");
 801  				usage_server();
 802  				goto server_exit_error;
 803  			}
 804  			arg = argv[i];
 805  			if (read_trust_anchors(&anchors, arg) == 0) {
 806  				usage_server();
 807  				goto server_exit_error;
 808  			}
 809  		} else if (eqstr(arg, "-anon_ok")) {
 810  			flags |= BR_OPT_TOLERATE_NO_CLIENT_AUTH;
 811  		} else if (eqstr(arg, "-list")) {
 812  			list_names();
 813  			goto server_exit;
 814  		} else if (eqstr(arg, "-vmin")) {
 815  			if (++ i >= argc) {
 816  				fprintf(stderr,
 817  					"ERROR: no argument for '-vmin'\n");
 818  				usage_server();
 819  				goto server_exit_error;
 820  			}
 821  			arg = argv[i];
 822  			if (vmin != 0) {
 823  				fprintf(stderr,
 824  					"ERROR: duplicate minimum version\n");
 825  				usage_server();
 826  				goto server_exit_error;
 827  			}
 828  			vmin = parse_version(arg, strlen(arg));
 829  			if (vmin == 0) {
 830  				fprintf(stderr,
 831  					"ERROR: unrecognised version '%s'\n",
 832  					arg);
 833  				usage_server();
 834  				goto server_exit_error;
 835  			}
 836  		} else if (eqstr(arg, "-vmax")) {
 837  			if (++ i >= argc) {
 838  				fprintf(stderr,
 839  					"ERROR: no argument for '-vmax'\n");
 840  				usage_server();
 841  				goto server_exit_error;
 842  			}
 843  			arg = argv[i];
 844  			if (vmax != 0) {
 845  				fprintf(stderr,
 846  					"ERROR: duplicate maximum version\n");
 847  				usage_server();
 848  				goto server_exit_error;
 849  			}
 850  			vmax = parse_version(arg, strlen(arg));
 851  			if (vmax == 0) {
 852  				fprintf(stderr,
 853  					"ERROR: unrecognised version '%s'\n",
 854  					arg);
 855  				usage_server();
 856  				goto server_exit_error;
 857  			}
 858  		} else if (eqstr(arg, "-cs")) {
 859  			if (++ i >= argc) {
 860  				fprintf(stderr,
 861  					"ERROR: no argument for '-cs'\n");
 862  				usage_server();
 863  				goto server_exit_error;
 864  			}
 865  			arg = argv[i];
 866  			if (suites != NULL) {
 867  				fprintf(stderr, "ERROR: duplicate list"
 868  					" of cipher suites\n");
 869  				usage_server();
 870  				goto server_exit_error;
 871  			}
 872  			suites = parse_suites(arg, &num_suites);
 873  			if (suites == NULL) {
 874  				usage_server();
 875  				goto server_exit_error;
 876  			}
 877  		} else if (eqstr(arg, "-hf")) {
 878  			unsigned x;
 879  
 880  			if (++ i >= argc) {
 881  				fprintf(stderr,
 882  					"ERROR: no argument for '-hf'\n");
 883  				usage_server();
 884  				goto server_exit_error;
 885  			}
 886  			arg = argv[i];
 887  			x = parse_hash_functions(arg);
 888  			if (x == 0) {
 889  				usage_server();
 890  				goto server_exit_error;
 891  			}
 892  			hfuns |= x;
 893  		} else if (eqstr(arg, "-cbhash")) {
 894  			cbhash = 1;
 895  		} else if (eqstr(arg, "-serverpref")) {
 896  			flags |= BR_OPT_ENFORCE_SERVER_PREFERENCES;
 897  		} else if (eqstr(arg, "-noreneg")) {
 898  			flags |= BR_OPT_NO_RENEGOTIATION;
 899  		} else if (eqstr(arg, "-alpn")) {
 900  			if (++ i >= argc) {
 901  				fprintf(stderr,
 902  					"ERROR: no argument for '-alpn'\n");
 903  				usage_server();
 904  				goto server_exit_error;
 905  			}
 906  			VEC_ADD(alpn_names, xstrdup(argv[i]));
 907  		} else if (eqstr(arg, "-strictalpn")) {
 908  			flags |= BR_OPT_FAIL_ON_ALPN_MISMATCH;
 909  		} else {
 910  			fprintf(stderr, "ERROR: unknown option: '%s'\n", arg);
 911  			usage_server();
 912  			goto server_exit_error;
 913  		}
 914  	}
 915  	if (port == NULL) {
 916  		port = "4433";
 917  	}
 918  	if (vmin == 0) {
 919  		vmin = BR_TLS10;
 920  	}
 921  	if (vmax == 0) {
 922  		vmax = BR_TLS12;
 923  	}
 924  	if (vmax < vmin) {
 925  		fprintf(stderr, "ERROR: impossible minimum/maximum protocol"
 926  			" version combination\n");
 927  		usage_server();
 928  		goto server_exit_error;
 929  	}
 930  	if (suites == NULL) {
 931  		num_suites = 0;
 932  
 933  		for (u = 0; cipher_suites[u].name; u ++) {
 934  			if ((cipher_suites[u].req & REQ_TLS12) == 0
 935  				|| vmax >= BR_TLS12)
 936  			{
 937  				num_suites ++;
 938  			}
 939  		}
 940  		suites = xmalloc(num_suites * sizeof *suites);
 941  		num_suites = 0;
 942  		for (u = 0; cipher_suites[u].name; u ++) {
 943  			if ((cipher_suites[u].req & REQ_TLS12) == 0
 944  				|| vmax >= BR_TLS12)
 945  			{
 946  				suites[num_suites ++] = cipher_suites[u];
 947  			}
 948  		}
 949  	}
 950  	if (hfuns == 0) {
 951  		hfuns = (unsigned)-1;
 952  	}
 953  	if (chain == NULL || chain_len == 0) {
 954  		fprintf(stderr, "ERROR: no certificate chain provided\n");
 955  		goto server_exit_error;
 956  	}
 957  	if (sk == NULL) {
 958  		fprintf(stderr, "ERROR: no private key provided\n");
 959  		goto server_exit_error;
 960  	}
 961  	switch (sk->key_type) {
 962  		int curve;
 963  		uint32_t supp;
 964  
 965  	case BR_KEYTYPE_RSA:
 966  		break;
 967  	case BR_KEYTYPE_EC:
 968  		curve = sk->key.ec.curve;
 969  		supp = br_ec_get_default()->supported_curves;
 970  		if (curve > 31 || !((supp >> curve) & 1)) {
 971  			fprintf(stderr, "ERROR: private key curve (%d)"
 972  				" is not supported\n", curve);
 973  			goto server_exit_error;
 974  		}
 975  		break;
 976  	default:
 977  		fprintf(stderr, "ERROR: unsupported private key type (%d)\n",
 978  			sk->key_type);
 979  		break;
 980  	}
 981  	cert_signer_algo = get_cert_signer_algo(chain);
 982  	if (cert_signer_algo == 0) {
 983  		goto server_exit_error;
 984  	}
 985  	if (verbose) {
 986  		const char *csas;
 987  
 988  		switch (cert_signer_algo) {
 989  		case BR_KEYTYPE_RSA: csas = "RSA"; break;
 990  		case BR_KEYTYPE_EC:  csas = "EC"; break;
 991  		default:
 992  			csas = "unknown";
 993  			break;
 994  		}
 995  		fprintf(stderr, "Issuing CA key type: %d (%s)\n",
 996  			cert_signer_algo, csas);
 997  	}
 998  	if (iobuf_len == 0) {
 999  		if (bidi) {
1000  			iobuf_len = BR_SSL_BUFSIZE_BIDI;
1001  		} else {
1002  			iobuf_len = BR_SSL_BUFSIZE_MONO;
1003  		}
1004  	}
1005  	iobuf = xmalloc(iobuf_len);
1006  	if (cache_len == (size_t)-1) {
1007  		cache_len = 5000;
1008  	}
1009  	cache = xmalloc(cache_len);
1010  
1011  	/*
1012  	 * Compute implementation requirements and inject implementations.
1013  	 */
1014  	suite_ids = xmalloc(num_suites * sizeof *suite_ids);
1015  	br_ssl_server_zero(&cc);
1016  	br_ssl_engine_set_versions(&cc.eng, vmin, vmax);
1017  	br_ssl_engine_set_all_flags(&cc.eng, flags);
1018  	if (vmin <= BR_TLS11) {
1019  		if (!(hfuns & (1 << br_md5_ID))) {
1020  			fprintf(stderr, "ERROR: TLS 1.0 and 1.1 need MD5\n");
1021  			goto server_exit_error;
1022  		}
1023  		if (!(hfuns & (1 << br_sha1_ID))) {
1024  			fprintf(stderr, "ERROR: TLS 1.0 and 1.1 need SHA-1\n");
1025  			goto server_exit_error;
1026  		}
1027  	}
1028  	for (u = 0; u < num_suites; u ++) {
1029  		unsigned req;
1030  
1031  		req = suites[u].req;
1032  		suite_ids[u] = suites[u].suite;
1033  		if ((req & REQ_TLS12) != 0 && vmax < BR_TLS12) {
1034  			fprintf(stderr,
1035  				"ERROR: cipher suite %s requires TLS 1.2\n",
1036  				suites[u].name);
1037  			goto server_exit_error;
1038  		}
1039  		if ((req & REQ_SHA1) != 0 && !(hfuns & (1 << br_sha1_ID))) {
1040  			fprintf(stderr,
1041  				"ERROR: cipher suite %s requires SHA-1\n",
1042  				suites[u].name);
1043  			goto server_exit_error;
1044  		}
1045  		if ((req & REQ_SHA256) != 0 && !(hfuns & (1 << br_sha256_ID))) {
1046  			fprintf(stderr,
1047  				"ERROR: cipher suite %s requires SHA-256\n",
1048  				suites[u].name);
1049  			goto server_exit_error;
1050  		}
1051  		if ((req & REQ_SHA384) != 0 && !(hfuns & (1 << br_sha384_ID))) {
1052  			fprintf(stderr,
1053  				"ERROR: cipher suite %s requires SHA-384\n",
1054  				suites[u].name);
1055  			goto server_exit_error;
1056  		}
1057  		/* TODO: algorithm implementation selection */
1058  		if ((req & REQ_AESCBC) != 0) {
1059  			br_ssl_engine_set_default_aes_cbc(&cc.eng);
1060  		}
1061  		if ((req & REQ_AESCCM) != 0) {
1062  			br_ssl_engine_set_default_aes_ccm(&cc.eng);
1063  		}
1064  		if ((req & REQ_AESGCM) != 0) {
1065  			br_ssl_engine_set_default_aes_gcm(&cc.eng);
1066  		}
1067  		if ((req & REQ_CHAPOL) != 0) {
1068  			br_ssl_engine_set_default_chapol(&cc.eng);
1069  		}
1070  		if ((req & REQ_3DESCBC) != 0) {
1071  			br_ssl_engine_set_default_des_cbc(&cc.eng);
1072  		}
1073  		if ((req & (REQ_ECDHE_RSA | REQ_ECDHE_ECDSA)) != 0) {
1074  			br_ssl_engine_set_default_ec(&cc.eng);
1075  		}
1076  	}
1077  	br_ssl_engine_set_suites(&cc.eng, suite_ids, num_suites);
1078  
1079  	dnhash = NULL;
1080  	for (u = 0; hash_functions[u].name; u ++) {
1081  		const br_hash_class *hc;
1082  		int id;
1083  
1084  		hc = hash_functions[u].hclass;
1085  		id = (hc->desc >> BR_HASHDESC_ID_OFF) & BR_HASHDESC_ID_MASK;
1086  		if ((hfuns & ((unsigned)1 << id)) != 0) {
1087  			dnhash = hc;
1088  			br_ssl_engine_set_hash(&cc.eng, id, hc);
1089  		}
1090  	}
1091  	if (vmin <= BR_TLS11) {
1092  		br_ssl_engine_set_prf10(&cc.eng, &br_tls10_prf);
1093  	}
1094  	if (vmax >= BR_TLS12) {
1095  		if ((hfuns & ((unsigned)1 << br_sha256_ID)) != 0) {
1096  			br_ssl_engine_set_prf_sha256(&cc.eng,
1097  				&br_tls12_sha256_prf);
1098  		}
1099  		if ((hfuns & ((unsigned)1 << br_sha384_ID)) != 0) {
1100  			br_ssl_engine_set_prf_sha384(&cc.eng,
1101  				&br_tls12_sha384_prf);
1102  		}
1103  	}
1104  
1105  	br_ssl_session_cache_lru_init(&lru, cache, cache_len);
1106  	br_ssl_server_set_cache(&cc, &lru.vtable);
1107  
1108  	if (VEC_LEN(alpn_names) != 0) {
1109  		br_ssl_engine_set_protocol_names(&cc.eng,
1110  			(const char **)&VEC_ELT(alpn_names, 0),
1111  			VEC_LEN(alpn_names));
1112  	}
1113  
1114  	/*
1115  	 * Set the policy handler (that chooses the actual cipher suite,
1116  	 * selects the certificate chain, and runs the private key
1117  	 * operations).
1118  	 */
1119  	pc.vtable = &policy_vtable;
1120  	pc.verbose = verbose;
1121  	pc.chain = chain;
1122  	pc.chain_len = chain_len;
1123  	pc.cert_signer_algo = cert_signer_algo;
1124  	pc.sk = sk;
1125  	pc.cbhash = cbhash;
1126  	br_ssl_server_set_policy(&cc, &pc.vtable);
1127  
1128  	/*
1129  	 * If trust anchors have been configured, then set an X.509
1130  	 * validation engine and activate client certificate
1131  	 * authentication.
1132  	 */
1133  	if (VEC_LEN(anchors) != 0) {
1134  		br_x509_minimal_init(&xc, dnhash,
1135  			&VEC_ELT(anchors, 0), VEC_LEN(anchors));
1136  		for (u = 0; hash_functions[u].name; u ++) {
1137  			const br_hash_class *hc;
1138  			int id;
1139  
1140  			hc = hash_functions[u].hclass;
1141  			id = (hc->desc >> BR_HASHDESC_ID_OFF)
1142  				& BR_HASHDESC_ID_MASK;
1143  			if ((hfuns & ((unsigned)1 << id)) != 0) {
1144  				br_x509_minimal_set_hash(&xc, id, hc);
1145  			}
1146  		}
1147  		br_ssl_engine_set_default_rsavrfy(&cc.eng);
1148  		br_ssl_engine_set_default_ecdsa(&cc.eng);
1149  		br_x509_minimal_set_rsa(&xc, br_rsa_pkcs1_vrfy_get_default());
1150  		br_x509_minimal_set_ecdsa(&xc,
1151  			br_ec_get_default(), br_ecdsa_vrfy_asn1_get_default());
1152  		br_ssl_engine_set_x509(&cc.eng, &xc.vtable);
1153  		br_ssl_server_set_trust_anchor_names_alt(&cc,
1154  			&VEC_ELT(anchors, 0), VEC_LEN(anchors));
1155  	}
1156  
1157  	br_ssl_engine_set_buffer(&cc.eng, iobuf, iobuf_len, bidi);
1158  
1159  	/*
1160  	 * On Unix systems, we need to ignore SIGPIPE.
1161  	 */
1162  #ifndef _WIN32
1163  	signal(SIGPIPE, SIG_IGN);
1164  #endif
1165  
1166  	/*
1167  	 * Open the server socket.
1168  	 */
1169  	server_fd = host_bind(bind_name, port, verbose);
1170  	if (server_fd == INVALID_SOCKET) {
1171  		goto server_exit_error;
1172  	}
1173  
1174  	/*
1175  	 * Process incoming clients, one at a time. Note that we do not
1176  	 * accept any client until the previous connection has finished:
1177  	 * this is voluntary, since the tool uses stdin/stdout for
1178  	 * application data, and thus cannot really run two connections
1179  	 * simultaneously.
1180  	 */
1181  	for (;;) {
1182  		int x;
1183  		unsigned run_flags;
1184  
1185  		fd = accept_client(server_fd, verbose, 1);
1186  		if (fd == INVALID_SOCKET) {
1187  			goto server_exit_error;
1188  		}
1189  		br_ssl_server_reset(&cc);
1190  		run_flags = (verbose ? RUN_ENGINE_VERBOSE : 0)
1191  			| (trace ? RUN_ENGINE_TRACE : 0);
1192  		x = run_ssl_engine(&cc.eng, fd, run_flags);
1193  #ifdef _WIN32
1194  		closesocket(fd);
1195  #else
1196  		close(fd);
1197  #endif
1198  		fd = INVALID_SOCKET;
1199  		if (x < -1) {
1200  			goto server_exit_error;
1201  		}
1202  	}
1203  
1204  	/*
1205  	 * Release allocated structures.
1206  	 */
1207  server_exit:
1208  	xfree(suites);
1209  	xfree(suite_ids);
1210  	free_certificates(chain, chain_len);
1211  	free_private_key(sk);
1212  	VEC_CLEAREXT(anchors, &free_ta_contents);
1213  	VEC_CLEAREXT(alpn_names, &free_alpn);
1214  	xfree(iobuf);
1215  	xfree(cache);
1216  	if (fd != INVALID_SOCKET) {
1217  #ifdef _WIN32
1218  		closesocket(fd);
1219  #else
1220  		close(fd);
1221  #endif
1222  	}
1223  	if (server_fd != INVALID_SOCKET) {
1224  #ifdef _WIN32
1225  		closesocket(server_fd);
1226  #else
1227  		close(server_fd);
1228  #endif
1229  	}
1230  	return retcode;
1231  
1232  server_exit_error:
1233  	retcode = -1;
1234  	goto server_exit;
1235  }