📄 easy-tls.c
字号:
if (!SSL_library_init() /* aka SSLeay_add_ssl_algorithms() */ ) { tls_errprintf(1, apparg, "SSL_library_init failed.\n"); return -1; } tls_init_done = 1; tls_rand_seed(); return 0;}/*****************************************************************************/static voidtls_rand_seed_uniquely(void){ struct { pid_t pid; time_t time; void *stack; } data; data.pid = getpid(); data.time = time(NULL); data.stack = (void *)&data; RAND_seed((const void *)&data, sizeof data);}voidtls_rand_seed(void){ struct { struct utsname uname; int uname_1; int uname_2; uid_t uid; uid_t euid; gid_t gid; gid_t egid; } data; data.uname_1 = uname(&data.uname); data.uname_2 = errno; /* Let's hope that uname fails randomly :-) */ data.uid = getuid(); data.euid = geteuid(); data.gid = getgid(); data.egid = getegid(); RAND_seed((const void *)&data, sizeof data); tls_rand_seed_uniquely();}static int tls_rand_seeded_p = 0;#define my_MIN_SEED_BYTES 256 /* struct stat can be larger than 128 */inttls_rand_seed_from_file(const char *filename, size_t n, void *apparg){ /* Seed OpenSSL's random number generator from file. Try to read n bytes if n > 0, whole file if n == 0. */ int r; if (tls_init(apparg) == -1) return -1; tls_rand_seed(); r = RAND_load_file(filename, (n > 0 && n < LONG_MAX) ? (long)n : LONG_MAX); /* r is the number of bytes filled into the random number generator, * which are taken from "stat(filename, ...)" in addition to the * file contents. */ assert(1 < my_MIN_SEED_BYTES); /* We need to detect at least those cases when the file does not exist * at all. With current versions of OpenSSL, this should do it: */ if (n == 0) n = my_MIN_SEED_BYTES; if (r < n) { tls_errprintf(1, apparg, "rand_seed_from_file: could not read %d bytes from %s.\n", n, filename); return -1; } else { tls_rand_seeded_p = 1; return 0; }}voidtls_rand_seed_from_memory(const void *buf, size_t n){ size_t i = 0; while (i < n) { size_t rest = n - i; int chunk = rest < INT_MAX ? (int)rest : INT_MAX; RAND_seed((const char *)buf + i, chunk); i += chunk; } tls_rand_seeded_p = 1;}/*****************************************************************************/struct tls_x509_name_string { char str[100];};static voidtls_get_x509_subject_name_oneline(X509 *cert, struct tls_x509_name_string *namestring){ X509_NAME *name; if (cert == NULL) { namestring->str[0] = '\0'; return; } name = X509_get_subject_name(cert); /* does not increment any reference counter */ assert(sizeof namestring->str >= 4); /* "?" or "...", plus 0 */ if (name == NULL) { namestring->str[0] = '?'; namestring->str[1] = 0; } else { size_t len; X509_NAME_oneline(name, namestring->str, sizeof namestring->str); len = strlen(namestring->str); assert(namestring->str[len] == 0); assert(len < sizeof namestring->str); if (len+1 == sizeof namestring->str) { /* (Probably something was cut off.) * Does not really work -- X509_NAME_oneline truncates after * name components, we cannot tell from the result whether * anything is missing. */ assert(namestring->str[len] == 0); namestring->str[--len] = '.'; namestring->str[--len] = '.'; namestring->str[--len] = '.'; } }}/*****************************************************************************//* to hinder OpenSSL from asking for passphrases */static intno_passphrase_callback(char *buf, int num, int w, void *arg){ return -1;}#if OPENSSL_VERSION_NUMBER >= 0x00907000Lstatic intverify_dont_fail_cb(X509_STORE_CTX *c, void *unused_arg)#elsestatic intverify_dont_fail_cb(X509_STORE_CTX *c)#endif{ int i; i = X509_verify_cert(c); /* sets c->error */#if OPENSSL_VERSION_NUMBER >= 0x00905000L /* don't allow unverified * certificates -- they could * survive session reuse, but * OpenSSL < 0.9.5-dev does not * preserve their verify_result */ if (i == 0) return 1; else#endif return i;}static DH *tls_dhe1024 = NULL; /* generating these takes a while, so do it just once */voidtls_set_dhe1024(int i, void *apparg){ DSA *dsaparams; DH *dhparams; const char *seed[] = { ";-) :-( :-) :-( ", ";-) :-( :-) :-( ", "Random String no. 12", ";-) :-( :-) :-( ", "hackers have even mo", /* from jargon file */ }; unsigned char seedbuf[20]; tls_init(apparg); if (i >= 0) { i %= sizeof seed / sizeof seed[0]; assert(strlen(seed[i]) == 20); memcpy(seedbuf, seed[i], 20); dsaparams = DSA_generate_parameters(1024, seedbuf, 20, NULL, NULL, 0, NULL); } else { /* random parameters (may take a while) */ dsaparams = DSA_generate_parameters(1024, NULL, 0, NULL, NULL, 0, NULL); } if (dsaparams == NULL) { tls_openssl_errors("", "", NULL, apparg); return; } dhparams = DSA_dup_DH(dsaparams); DSA_free(dsaparams); if (dhparams == NULL) { tls_openssl_errors("", "", NULL, apparg); return; } if (tls_dhe1024 != NULL) DH_free(tls_dhe1024); tls_dhe1024 = dhparams;}struct tls_create_ctx_argstls_create_ctx_defaultargs(void){ struct tls_create_ctx_args ret; ret.client_p = 0; ret.certificate_file = NULL; ret.key_file = NULL; ret.ca_file = NULL; ret.verify_depth = -1; ret.fail_unless_verified = 0; ret.export_p = 0; return ret;}SSL_CTX *tls_create_ctx(struct tls_create_ctx_args a, void *apparg){ int r; static long context_num = 0; SSL_CTX *ret; const char *err_pref_1 = "", *err_pref_2 = ""; if (tls_init(apparg) == -1) return NULL; ret = SSL_CTX_new((a.client_p? SSLv23_client_method:SSLv23_server_method)()); if (ret == NULL) goto err; SSL_CTX_set_default_passwd_cb(ret, no_passphrase_callback); SSL_CTX_set_mode(ret, SSL_MODE_ENABLE_PARTIAL_WRITE); if ((a.certificate_file != NULL) || (a.key_file != NULL)) { if (a.key_file == NULL) { tls_errprintf(1, apparg, "Need a key file.\n"); goto err_return; } if (a.certificate_file == NULL) { tls_errprintf(1, apparg, "Need a certificate chain file.\n"); goto err_return; } if (!SSL_CTX_use_PrivateKey_file(ret, a.key_file, SSL_FILETYPE_PEM)) goto err; if (!tls_rand_seeded_p) { /* particularly paranoid people may not like this -- * so provide your own random seeding before calling this */ if (tls_rand_seed_from_file(a.key_file, 0, apparg) == -1) goto err_return; } if (!SSL_CTX_use_certificate_chain_file(ret, a.certificate_file)) goto err; if (!SSL_CTX_check_private_key(ret)) { tls_errprintf(1, apparg, "Private key \"%s\" does not match certificate \"%s\".\n", a.key_file, a.certificate_file); goto err_peek; } } if ((a.ca_file != NULL) || (a.verify_depth > 0)) { context_num++; r = SSL_CTX_set_session_id_context(ret, (const void *)&context_num, (unsigned int)sizeof context_num); if (!r) goto err; SSL_CTX_set_verify(ret, SSL_VERIFY_PEER | (a.fail_unless_verified ? SSL_VERIFY_FAIL_IF_NO_PEER_CERT : 0), 0); if (!a.fail_unless_verified) SSL_CTX_set_cert_verify_callback(ret, verify_dont_fail_cb, NULL); if (a.verify_depth > 0) SSL_CTX_set_verify_depth(ret, a.verify_depth); if (a.ca_file != NULL) { r = SSL_CTX_load_verify_locations(ret, a.ca_file, NULL /* no CA-directory */); /* does not report failure if file does not exist ... */ if (!r) { err_pref_1 = " while processing certificate file "; err_pref_2 = a.ca_file; goto err; } if (!a.client_p) { /* SSL_load_client_CA_file is a misnomer, it just creates a list of CNs. */ SSL_CTX_set_client_CA_list(ret, SSL_load_client_CA_file(a.ca_file)); /* SSL_CTX_set_client_CA_list does not have a return value; * it does not really need one, but make sure * (we really test if SSL_load_client_CA_file worked) */ if (SSL_CTX_get_client_CA_list(ret) == NULL) { tls_errprintf(1, apparg, "Could not set client CA list from \"%s\".\n", a.ca_file); goto err_peek; } } } } if (!a.client_p) { if (tls_dhe1024 == NULL) { int i; RAND_bytes((unsigned char *) &i, sizeof i); /* make sure that i is non-negative -- pick one of the provided * seeds */ if (i < 0) i = -i; if (i < 0) i = 0; tls_set_dhe1024(i, apparg); if (tls_dhe1024 == NULL) goto err_return; } if (!SSL_CTX_set_tmp_dh(ret, tls_dhe1024)) goto err; /* avoid small subgroup attacks: */ SSL_CTX_set_options(ret, SSL_OP_SINGLE_DH_USE); } #ifndef NO_RSA if (!a.client_p && a.export_p) { RSA *tmpkey; tmpkey = RSA_generate_key(512, RSA_F4, 0, NULL); if (tmpkey == NULL) goto err; if (!SSL_CTX_set_tmp_rsa(ret, tmpkey)) { RSA_free(tmpkey); goto err; } RSA_free(tmpkey); /* SSL_CTX_set_tmp_rsa uses a duplicate. */ }#endif return ret; err_peek: if (!ERR_peek_error()) goto err_return; err: tls_openssl_errors(err_pref_1, err_pref_2, NULL, apparg); err_return: if (ret != NULL) SSL_CTX_free(ret); return NULL;}/*****************************************************************************/static inttls_socket_nonblocking(int fd){ int v, r; v = fcntl(fd, F_GETFL, 0); if (v == -1) { if (errno == EINVAL) return 0; /* already shut down -- ignore */ return -1; } r = fcntl(fd, F_SETFL, v | O_NONBLOCK); if (r == -1) { if (errno == EINVAL) return 0; /* already shut down -- ignore */ return -1; } return 0;}static intmax(int a, int b){ return a > b ? a : b;}static voidtls_sockets_select(int read_select_1, int read_select_2, int write_select_1, int write_select_2, int seconds /* timeout, -1 means no timeout */){ int maxfd, n; fd_set reads, writes; struct timeval timeout; struct timeval *timeout_p; assert(read_select_1 >= -1 && read_select_2 >= -1 && write_select_1 >= -1 && write_select_2 >= -1); assert(read_select_1 < FD_SETSIZE && read_select_2 < FD_SETSIZE -1 && write_select_1 < FD_SETSIZE -1 && write_select_2 < FD_SETSIZE -1); maxfd = max(max(read_select_1, read_select_2), max(write_select_1, write_select_2)); assert(maxfd >= 0); FD_ZERO(&reads); FD_ZERO(&writes); for(n = 0; n < 4; ++n) { int i = n % 2;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -